I create the key and I encrypt the message send by user, and store this message in a file and after i try to decrypt this message in the file, but i get this error cryptography.fernet.InvalidToken. I don't use the time for the token and I have also converted in byte after.
My code is:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
def encry():
global f
what = input("What i need to encrypt?")
what_b = str.encode(what)
token = f.encrypt(what_b)
print("key generated")
print("encrypted")
file1=open("string.txt", "w")
file1.write(str(token))
file1.close()
file2=open("key.txt", "w")
file2.write(str(key))
file2.close()
def decry():
global f
print("decrypted")
file1=open("string.txt", "r").read()
file_de=str.encode(file1)
file2=open("de.txt", "w")
what_d = f.decrypt(file_de)
file1.close()
file2.write(str(what_d))
file2.close()
choose = input("Do you want, encrypt or decrypt?" + " " + "(e/d)")
if choose == "e":
encry()
elif choose == "d":
decry()
else:
print("Nothing to do")
The problem comes from the way you write and read the message and the key to and from the files. Indeed, the encrypted text and the keys are not strings, but byte strings and need to be treated in a different way.
In your case, when reading and writing it is enough to specify that you do it in binary mode and you can do it by adding the b flag. See the documentation for more detailed information.
Moreover, in your decrypt you also need to read the key from the file.
def encry():
key = Fernet.generate_key()
f = Fernet(key)
what = "example"
what_b = str.encode(what)
token = f.encrypt(what_b)
with open("string.txt", "wb") as f1, open("key.txt", "wb") as f2:
f1.write(token)
f2.write(key)
def decry():
with open("string.txt", "rb") as f1, open("key.txt", "rb") as f2:
token = f1.read()
key = f2.read()
f = Fernet(key)
what_d = str(f.decrypt(token),'utf-8') #converting back to string
encry()
decry()
Related
I am trying to create a python script in which you run through all the files in the directory and encrypt them as an alternative to BitLocker. One of the files is just an example passkey as a proof of concept.
I got so far as to get the passkey(s) as input from the user. I downloaded, and imported cryptography.fernet, and created a list of the files in the directory.
I also generated the key that I will use for encryption but am unsure of how to do file encryption with Fernet.
#Script is named match_key.py
from cryptography.fernet import Fernet
import os
#Initialize variables; Specifically the passkey variables
passkey = input("Enter your key: ")
add_key = input("Do you want to enter another key? (y/N) ")
key_list = []
key_list.append(passkey)
encr_file_list = []
#Checks if the user wants to input another key
while add_key == "y" or add_key == "Y":
key = input("Enter your key: ")
key_list.append(passkey)
add_key = input("Do you want to enter another key? (y/N) ")
if add_key == "n" or add_key == "N":
#Store the passwords in a file written to the disk
with open("passwords.txt", "wb") as passwords:
passwords.write(key_list)
break
else:
pass
print(key_list)
#Add each file of the directory to a list except for match_key.py and the encryption key
key = Fernet.generate_key()
for file in os.listdir():
if file == "match_key.py":
continue
if os.path.isfile(file):
encr_file_list.append(file)
print(encr_file_list)
My main question is:
How would I take each file, besides match_key.py and the key, in the directory and encrypt it?
Would this be (preferably) possible with a for loop?
After generating the key for encryption, initialize a Fernet object with it, and call encrypt() on the file contents in a for loop. Remember that the same key is needed to decrypt() the files again, so store the key in file.
encr_file_list = []
for file in os.listdir():
if file == "match_key.py":
continue
if os.path.isfile(file):
encr_file_list.append(file)
key = Fernet.generate_key()
f = Fernet(key)
# store the key to use later for decryption
with open('encryptionkey.key', 'wb') as f:
f.write(key)
for file in encr_file_list:
with open(file, 'rb') as f:
file_content = f.read()
encrypted_content = f.encrypt(file_content)
with open(file, 'wb') as f:
f.write(encrypted_content)
Later on to decrypt, do the following
# Get the key back from the file
with open('encryptionkey.key', 'rb') as f:
key = f.read()
f = Fernet(key)
# Store the files you want to decrypt in decr_file_list then do the following
for file in decr_file_list:
with open(file, 'rb') as f:
file_content = f.read()
decrypted_content = f.decrypt(file_content)
with open(file, 'wb') as f:
f.write(decrypted_content)
I'm trying to decrypt a string using fernet. My code (assume files already exist with pre-filled data):
import hashlib
import bcrypt
from cryptography.fernet import Fernet
import base64
#encrypting
############################################################
file = open('message.txt', 'r+')
message = file.read()
file.close()
password = input("Enter password: ")
file = open('passsalt.txt', 'r+')
salt = file.read()
file.close()
passwordnhash = str(password) + str(salt)
passwordnhash = passwordnhash.encode('utf-8')
hash = hashlib.sha256(passwordnhash).digest()
key = base64.urlsafe_b64encode(hash)
fernet = Fernet(key)
encMessage = fernet.encrypt(message.encode())
file = open('message.ivf', 'w+')
file.write(str(encMessage))
file.close()
############################################################
#decrypting
file = open('message.ivf', 'r+')
token = file.read()
file.close()
token = token.encode('utf-8')
file = open('passsalt.txt', 'r+')
salt = file.read()
file.close()
passwordnhash = str(password) + str(salt)
passwordnhash = passwordnhash.encode('utf-8')
hash = hashlib.sha256(passwordnhash).digest()
key = base64.urlsafe_b64encode(hash)
fernet = Fernet(key)
#token = fernet.encrypt(message)
d = fernet.decrypt(token)
print(d)
This returns the error
cryptography.fernet.InvalidToken
While decrypting. I'm unsure on what to do. I have viewed many questions but none have a fix for me. Links:
Stack Overflow question 1
Stack Overflow question 2
Stack Overflow question 3
Thanks in advance
Good day,
I am doing an assignment for cryptography. It's an easy task I need to take any image, turn it into HEX, encrypt it and then decrypt it.
As I am working in Python and there was no specific encryption method in the task I just use Fernet.
I have an encryptor and decryptor scripts.
Encryption seems to be working because as a test I create a txt document with original HEX and after decryption the program states that original HEX and decrypted one are the same, however the decrypted image is not loading.
Could anyone help out a newbie?
Encryptor:
import binascii
from cryptography.fernet import Fernet
img = 'panda.png'
with open(img, 'rb') as f:
content = f.read()
hexValue = binascii.hexlify(content)
key = Fernet.generate_key()
with open('info/key.txt', mode='w+') as keyValue:
keyValue.write(key)
keyValue.seek(0)
f = Fernet(key)
encHexVal = f.encrypt(hexValue)
with open('info/encryptedHex.txt', mode='w+') as hexValueFile:
hexValueFile.write(encHexVal)
hexValueFile.seek(0)
a = f.decrypt(encHexVal)
with open('info/realValue.txt', mode='w+') as writeHex:
originalHex = writeHex.write(hexValue)
with open('info/realValue.txt', mode='r') as reading:
realValue = reading.read()
if realValue == a:
print("We're good to go!")
else:
print("Oops something went wrong. Check the source code.")
Decryptor:
import binascii
from cryptography.fernet import Fernet
with open('info/key.txt', mode='rb') as keyValue:
key = keyValue.read()
f = Fernet(key)
with open('info/encryptedHex.txt', mode='rb') as imageHexValue:
hexValue = imageHexValue.read()
a = f.decrypt(hexValue)
with open('info/realValue.txt', mode='r') as compare:
realContents = compare.read()
print("Small test in safe environment...")
if realContents == a:
print("All good!")
else:
print("Something is wrong...")
data = a.encode()
data = data.strip()
data = data.replace(' ', '')
data = data.replace('\n', '')
with open('newImage.png', 'wb') as file:
file.write(data)
I am using a random image from the internet of Po from Kung Fu Panda:
The principle problem is that although you hexlify then encrypt in the encryptor you don't unhexlify after decrypting in the decryptor. Its far more common to do things the other way, encrypt then hexlify so that the encrypted binary can be stored in regular text files or sent via http.
You have several problems with trying to write bytes objects to files open in text. I fixed those along the way. But it does leave me puzzled why a file called 'info/encryptedHex.txt' would be binary.
Encryptor
import binascii
from cryptography.fernet import Fernet
# Generate keyfile
#
# TODO: Overwrites key file on each run, invalidating previous
# saves. You could do `if not os.path.exists('info/key.txt'):`
key = Fernet.generate_key()
with open('info/key.txt', mode='wb') as keyValue:
keyValue.write(key)
# Encrypt image
img = 'panda.png'
with open(img, 'rb') as f:
content = f.read()
hexValue = binascii.hexlify(content)
f = Fernet(key)
encHexVal = f.encrypt(hexValue)
with open('info/encryptedHex.txt', mode='wb') as hexValueFile:
hexValueFile.write(encHexVal)
# Verification checks
a = f.decrypt(encHexVal)
# hexed bytes is same encoding as 'ascii'
with open('info/realValue.txt', mode='wb') as writeHex:
originalHex = writeHex.write(hexValue)
with open('info/realValue.txt', mode='r', encoding='ascii') as reading:
realValue = reading.read()
if realValue == a.decode('ascii'):
print("We're good to go!")
else:
print("Oops something went wrong. Check the source code.")
Decryptor
import binascii
from cryptography.fernet import Fernet
# Generate keyfile
#
# TODO: Overwrites key file on each run, invalidating previous
# saves. You could do `if not os.path.exists('info/key.txt'):`
key = Fernet.generate_key()
with open('info/key.txt', mode='wb') as keyValue:
keyValue.write(key)
# Encrypt image
img = 'panda.png'
with open(img, 'rb') as f:
content = f.read()
hexValue = binascii.hexlify(content)
f = Fernet(key)
encHexVal = f.encrypt(hexValue)
with open('info/encryptedHex.txt', mode='wb') as hexValueFile:
hexValueFile.write(encHexVal)
# Verification checks
a = f.decrypt(encHexVal)
# hexed bytes is same encoding as 'ascii'
with open('info/realValue.txt', mode='wb') as writeHex:
originalHex = writeHex.write(hexValue)
with open('info/realValue.txt', mode='r', encoding='ascii') as reading:
realValue = reading.read()
if realValue == a.decode('ascii'):
print("We're good to go!")
else:
print("Oops something went wrong. Check the source code.")
(base) td#timpad:~/dev/SO/Encrypting and decrypting in image$ cat de.py
import binascii
from cryptography.fernet import Fernet
with open('info/key.txt', mode='rb') as keyValue:
key = keyValue.read()
f = Fernet(key)
with open('info/encryptedHex.txt', mode='rb') as imageHexValue:
encHexValue = imageHexValue.read()
hexValue = f.decrypt(encHexValue)
binValue = binascii.unhexlify(hexValue)
with open('info/realValue.txt', mode='rb') as compare:
realContents = compare.read()
print("Small test in safe environment...")
if realContents == hexValue:
print("All good!")
else:
print("Something is wrong...")
with open('newImage.png', 'wb') as file:
file.write(binValue)
I have this error =>cryptography.fernet.InvalidToken, when I try to decrypt the content of my file at this line exit1 = key.decrypt(listCipher[0]).
I sought everywhere but I didn't found anything about this problem. I tried to replace the list by using ConfigParser but it still doesn't work and I don't think that is the problem. Some help is welcome.
from cryptography.fernet import Fernet
entry1 = "First_sentence"
entry2 = "Second_sentence"
entry3 = "Third_sentence"
##--- Key creation
firstKey = Fernet.generate_key()
file = open('.\\TEST\\key.key', 'wb')
file.write(firstKey)
file.close()
##--- Cipher entries
key = Fernet(firstKey)
chiffrentry1 = key.encrypt(bytes(entry1, "utf-8"))
chiffrentry2 = key.encrypt(bytes(entry2, "utf-8"))
chiffrentry3 = key.encrypt(bytes(entry3, "utf-8"))
listAll = [chiffrentry1, chiffrentry2, chiffrentry3]
##-- Write cipher text in file
with open('.\\TEST\\text_encrypt.txt', 'w') as pt:
for ligne in listAll:
pt.write("%s\n" % ligne)
##--- Recover file to decrypt cipher text
listCipher = []
with open('.\\TEST\\text_encrypt.txt', 'rb') as pt:
for line in pt:
listCipher.append(line.strip())
exit1 = key.decrypt(listCipher[0])
exit2 = key.decrypt(listCipher[1])
exit3 = key.decrypt(listCipher[2])
print(exit1)
print(exit2)
print(exit3)
The '%s\n'%ligne is modifying your data. For instance if I do the following:
>>> with open('afile.txt', 'w') as fh:
for i in range(2):
fh.write('%s\n'%b'hi there')
12
12
>>> with open('afile.txt', 'rb') as fh:
for line in fh:
print(line)
b"b'hi there'\n"
b"b'hi there'\n"
The issue here is the type conversions you are doing. Fernet's operations expect bytes and you are storing the encrypted values as strings. When you convert a bytes object to a string, you don't get exactly what that byte-string was. To avoid this, don't convert the types
with open('.\\TEST\\text_encrypt.txt', 'wb') as pt:
# join supports byte-strings
to_write = b'\n'.join(listAll)
pt.write(to_write)
# Now I can read a bytes object directly
with open('.\\TEST\\text_encrypt.txt', 'rb') as fh:
# this is a single bytes-string with b'\n' chars inside it
contents = fh.read()
# byte-strings also support split
ciphers = contents.split(b'\n')
for cipher in ciphers:
print(key.decrypt(cipher))
Here is my code:
from Crypto.PublicKey import RSA
#Write key to file
key = RSA.generate(4096)
privateKey = key.exportKey()
file1 = open('keyfile.pem', 'wb')
file1.write(privateKey)
file1.close()
#Read key from file
file2 = open('keyfile.pem', 'rb')
key = RSA.importKey(file2.read()) #this is the problem
The error is "RSA key format is not supported." Can anyone help me with the best way to write/read the private key from a file?
My answer and a little more complicated with pair of keys
from Crypto.PublicKey import RSA
key = RSA.generate(4096)
f = open('/home/john/Desktop/my_rsa_public.pem', 'wb')
f.close()
f.write(key.publickey().exportKey('PEM'))
f = open('/home/john/Desktop/my_rsa_private.pem', 'wb')
f.write(key.exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_public.pem', 'rb')
f1 = open('/home/john/Desktop/my_rsa_private.pem', 'rb')
key = RSA.importKey(f.read())
key1 = RSA.importKey(f1.read())
x = key.encrypt(b"dddddd",32)
print(x)
z = key1.decrypt(x)
print(z)
You have multiple issues with your code, mainly the way you are reading and writing the key. You never close the file, then open it twice during your read function; try changing your code to:
#Write key to file
key = RSA.generate(4096)
f = open('keyfile.pem', 'wb')
f.write(key.exportKey('PEM'))
f.close()
#Read key from file
f = open('keyfile.pem', 'rb')
key = RSA.importKey(f.read())
Result:
<_RSAobj #0x10d3cb2d8 n(4096),e,d,p,q,u,private>