Decrypt message with cryptography.fernet do not work - python

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.

Related

Python path error in encryption decryption function

I am attempting to use encryption key from my USB stick to decrypt a file on my computer.
The output I get from my current script (based on source: https://medium.com/codex/encrypting-your-files-using-a-usb-stick-as-the-key-python-e04b26657357) keeps throwing path errors. It can load the key but somehow doesnt decrypt the file on my computer. Can someone see where this error is coming from or how it can be solved?
I get the following output:
C:\Users\Asus\PycharmProjects\pythonProject220728usbkey\venv\Scripts\python.exe C:/Users/Asus/PycharmProjects/pythonProject220728usbkey/main.py
Trying to find key...
Key Found
Traceback (most recent call last):
File "C:\Users\Asus\PycharmProjects\pythonProject220728usbkey\main.py", line 68, in <module>
encryptFiles(key,files)
File "C:\Users\Asus\PycharmProjects\pythonProject220728usbkey\main.py", line 30, in encryptFiles
files = os.listdir(directory)
NotADirectoryError: [WinError 267] El nombre del directorio no es vĂ¡lido: 'C:\\Users\\Asus\\PycharmProjects\\pythonProject220728usbkey\\enc_levensonderhoud.xlsx'
Process finished with exit code 1
-------------------------------------------------------------------------------------#
#See my current script below:
import os
import wmi
from cryptography.fernet import Fernet
my_key = 'TICOZM'
files = r'C:\Users\Asus\PycharmProjects\pythonProject220728usbkey\enc_levensonderhoud.xlsx'
c = wmi.WMI()
def check_for_key():
for disk in c.Win32_LogicalDisk():
if disk.VolumeName==my_key:
return disk
def load_key(usbDisk):
port = usbDisk.DeviceID
try:
print('Trying to find key...')
with open(f'{port}\\encryptionKey.key','rb') as encryptKey:
key = encryptKey.read()
print('Key Found')
except:
print('Key not found... Creating a new key')
key = Fernet.generate_key()
with open(f'{port}\\encryptionKey.key','wb') as encryptKey:
encryptKey.write(key)
return key
def encryptFiles(key,directory):
files = os.listdir(directory)
cipher = Fernet(key)
global state
state = 'encrypted'
for file in files:
with open(f'{directory}\{file}','rb') as old:
original = old.read()
encrypted = cipher.encrypt(original)
with open(f'{directory}\{file}','wb') as old:
old.write(encrypted)
def decryptFiles(key, directory):
files = os.listdir(directory)
cipher = Fernet(key)
global state
state = 'decrypted'
for file in files:
with open(f'{directory}\{file}', 'rb') as old:
encrypted = old.read()
decrypted = cipher.decrypt(encrypted)
with open(f'{directory}\{file}', 'wb') as old:
old.write(decrypted)
state = 'decrypted'
if __name__=='__main__':
while True:
disk = check_for_key()
try:
key = load_key(disk)
except:
print('No Key Available')
if disk!=None:
current_state = 'decrypted'
if current_state!=state:
decryptFiles(key,files)
else:
current_state = 'encrypted'
if current_state!=state:
encryptFiles(key,files)

cryptography.fernet.InvalidToken problem with cryptography

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

How to save and load rsa keys

I'm trying to encrypt some text and then save the ciphertext and the keys in separate files, then decrypting the "file" file (ciphertext) using the "keys" (keys in json)
Breakdown of my code
Creating keys
Opening keys file
Converting keys to json
Saving file
Getting text from user
Encrypting it
Writing ciphertext to file
Loading keys
Taking e, n, d, p, q values and assigning them
Opening and reading ciphertext from file
Decripting and outputting
All of the code works except when I try to assign the keys from my json file,
I get:
Traceback (most recent call last):
File "C:\Users\user\Desktop\python projects\encrption\test.py", line 48, in <module>
text = rsa.decrypt(cyphertext, loadkedkeys[1]).decode()
File "C:\Users\user\Desktop\python projects\encrption\.venv\lib\site-packages\rsa\pkcs1.py", line 249, in decrypt
decrypted = priv_key.blinded_decrypt(encrypted)
TypeError: blinded_decrypt() missing 1 required positional argument: 'encrypted'
My code:
import rsa
import json
#make keys
print("new keys")
loadkedkeys = rsa.newkeys(256)
print("file")
#turn keys into json
keysfile = open(file=("kes"), mode="w")
keys = {"keys": []}
keys["keys"].append(((loadkedkeys[0].e), (loadkedkeys[0].n)))
keys["keys"].append(
(((loadkedkeys[1].e), loadkedkeys[1].n, (loadkedkeys[1].d), (loadkedkeys[1].p),
(loadkedkeys[1].q))))
keysfile.write(str(json.dumps(keys)))
keysfile.close()
text = input("message: ")
#encrypt
cyphertext = rsa.encrypt(text.encode(), loadkedkeys[0])
keysFile = open(file="kes", mode="r")
keysfilecontents = keysFile.read()
try:
keys = json.loads(keysfilecontents)
except:
print("json error")
loadkedkeys = (rsa.key.PublicKey, rsa.key.PrivateKey)
# setting public key
loadkedkeys[0].e = keys["keys"][0][0]
loadkedkeys[0].n = keys["keys"][0][1]
# setting private key
loadkedkeys[1].e = keys["keys"][1][0]
loadkedkeys[1].n = keys["keys"][1][1]
loadkedkeys[1].d = keys["keys"][1][2]
loadkedkeys[1].p = keys["keys"][1][3]
loadkedkeys[1].q = keys["keys"][1][4]
keysFile.close()
print(loadkedkeys[0])
print(loadkedkeys[1])
open("text.txt", "wb").write(cyphertext)
text = open("text.txt", "rb").read()
text = rsa.decrypt(cyphertext, loadkedkeys[1]).decode()
print(text)
So I seem to have figured it out, I changed so I assign the values though rsa.PublicKey(value,value), also swapped the e and n values

How to make sure the Fernet key stays the same when initialized?

So, I am making a password manager and I am using the cryptography module. The problem with this program is when decrypting. It will work fine when I encrypt and decrypt in the same session but when I encrypt, close, and then decrypt in a different session, errors will be raised. This error isn't happening because I am generating a random key every time, but I think the key is changing when I initialize it using the Fernet() method. How do I solve this?
#The Dependicies and Packages required for this script
import sqlite3
from cryptography.fernet import Fernet
def generate_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("secret.key", "wb") as key_file:
key_file.write(key)
def load_key():
"""
Loads the key named `secret.key` from the current directory.
"""
return open("secret.key", "rb").read()
#These are the keys for encryption
Key = load_key()
f = Fernet(Key)
def decode_data(datas):
new_name = f.decrypt(datas)
final_name = new_name.decode()
return final_name
def find_password():
"""
This function is to get the password of the website that the user expected
"""
website_name = input("What is the website's name for which you need a password>")
c.execute("SELECT * FROM passwords")
data = c.fetchall()
print(data)
for row in data:
print(row[0])
name = decode_data(row[0])
if name == website_name:
password = decode_data(row[2])
print(f'The password to {website_name} is {password}')
def main():
go_on = True
while go_on:
direction_question = input("This is your password manager. Press 1 to create a new pasword, Press 2 to search for a password, or Press 3 to exit the program>")
if direction_question.lower() == "1":
create_password()
if direction_question.lower() == "2":
find_password()
if direction_question.lower() == "3":
go_on = False
else:
print("Invalid response")
db.commit()
db.close()
if __name__ == "__main__":
db = sqlite3.connect('password.db')
c = db.cursor()
main()
These errors were raised
File "/usr/local/lib/python3.7/site-packages/cryptography/fernet.py", line 114, in _verify_signature
h.verify(data[-32:])
File "/usr/local/lib/python3.7/site-packages/cryptography/hazmat/primitives/hmac.py", line 68, in verify
ctx.verify(signature)
File "/usr/local/lib/python3.7/site-packages/cryptography/hazmat/backends/openssl/hmac.py", line 78, in verify
raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "password_manager.py", line 86, in <module>
main()
File "password_manager.py", line 74, in main
find_password()
File "password_manager.py", line 61, in find_password
name = decode_data(row[0])
File "password_manager.py", line 28, in decode_data
new_name = f.decrypt(datas)
File "/usr/local/lib/python3.7/site-packages/cryptography/fernet.py", line 77, in decrypt
return self._decrypt_data(data, timestamp, ttl, int(time.time()))
File "/usr/local/lib/python3.7/site-packages/cryptography/fernet.py", line 126, in _decrypt_data
self._verify_signature(data)
File "/usr/local/lib/python3.7/site-packages/cryptography/fernet.py", line 116, in _verify_signature
raise InvalidToken
cryptography.fernet.InvalidToken
You have done a good job storing once generated keys to a separate file.I've run your scrip and it works fine. The only issue I found is that the following part should be within the main() method.
Key = load_key()
f = Fernet(Key)
As the main() method is actually getting an empty string as a key rather than reading the stored key in the .key file.Hence, it is throwing
raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.
and
raise InvalidToken
cryptography.fernet.InvalidToken

Attribute error while using lambda in python

okay so here is my code so far:
import os
import time
import random
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import AES
import base64
key = 'MIICWwIBAAKBgQDN'
print('do you have a encrypted string in a file?')
fileexist = input('if so then input 1:')
if fileexist == 1:
filename = raw_input('please input path to file:')
file = open(filename,'r')
encoded = file.read()
type = type(encoded)
else:
encoded = raw_input('please enter encrypted text')
encoded = str(encoded)
BLOCK_SIZE = 16
PADDING = '{'
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
decoded = DecodeAES(key, encoded)
print(decoded)
I keep geting a attribute error on line 24 my exact error message is as bellow
AttributeError: 'str' object has no attribute 'decrpt'
I am trying to decrypt a message using AES. my encrypter works just fine using almost the exact same syntax. I dont fully understand the why the error apears. I know this is possible I have seen other post using this syntax.
Spelling issues set aside, in the code you link to, the first argument to DecodeAES is a AES.AESCipher object created with AES.new :
# create a cipher object using the random secret
cipher = AES.new(secret)
In your own code you are passing the string key, which doesn't have a decrypt method.
And FWIW this has nothing to do with the function being defined as a lambda - the function version would behave the very same way:
def DecodeAES(c, e):
return c.decrypt(base64.b64decode(e)).rstrip(PADDING)
DecodeAES("foo", "bar")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in DecodeAES
AttributeError: 'str' object has no attribute 'decrypt'
You first need to create an AES object to pass in DecodeAES.
Do it using
key = 'MIICWwIBAAKBgQDN'
cipher = AES.new(key)
Now instead of calling DecodeAES on the key, you call it on the cipher object we created with the key:
decoded = DecodeAES(cipher, encoded)
That should make your code working.

Categories