Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Bytes & Lists & Encryption

I’m using Fernet to encrypt my data. Let’s assume that I have these three data:

data = [fernet.encrypt("Hello".encode()), fernet.encrypt("Stack".encode()), fernet.encrypt("Overflow".encode())]

After this operation, Python automatically converts bytes to string, and I’m writing them to a csv file. When I need to decrypt them like:

fernet.decrypt(data)

It gives me an error like you can only decrypt only bytes etc. I also checked that my data in the csv file is already bytes but string form.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

b'gAAAAABiVUw5BzOkOv3VxlV5xa57Iaf0R4dzPbgsrnheAME8uYeslCZfTx9GeyRWe7l9VMM-gdDXiPZ4zsAXoXkG6T1dyXH6EztcqirrPhXX3YCt65_3xXvykVTDPdbEXs51cHvR-3HH'

>Solution :

An end-to-end usage example for encoding, writing to text, reading, and decoding.

The Fernet documentation can be referenced here.

from cryptography.fernet import Fernet

# Auto-generate a secret key.
key = Fernet.generate_key()
f = Fernet(key)

# Encode the string 'Hello' and encrypt.
encoded = f.encrypt('Hello'.encode())

This creates a bytestring (a bytes object) as:

b'gAAAAABiVVOOeO-hUG2QaKCVOyshntpbqVbxnexIVsFr7ttBGmKhHlDeM7jkTCjPPGphZxbh4D15X82pts3hKes12DjzwI8_jQ=='

Write, read and decrypt:

# Write the *decoded* encrypted string to a TXT file.
with open('/tmp/encoded.txt', 'w') as fh:
    fh.write(encoded.decode())
    
# Read the encrypted string from TXT file.
with open('/tmp/encoded.txt') as fh:
    encoded = fh.read()
    
# Encode the string, pass through fernet for decryption, 
# and decode the bytes output.
f.decrypt(encoded.encode()).decode()

Output:

'Hello'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading