Search code examples
pythonencryption

pyAesCrypt crypt dictionary, save cipher text to file then read file and decrypt


So I am trying to encrypt a dictionary and save it as cypher text, then open and decrypt the file so my program can use the passwords.
I do not want to save the decrypted file and it should only be stored in a variable.

My current .py is as follows:

import io
import json
import pyAesCrypt


password = 'some_password'
bufferSize = 64 * 1024


def enc():
    loaded_settings = {'pass1': 'xxx',
                       'pass2': 'ccc',
                       'key': 'ddd',
                       'secret': 'sss'}

    # binary data to be encoded
    user_encode_data = json.dumps(loaded_settings).encode('utf-8')

    # input plaintext binary stream
    fIn = io.BytesIO(user_encode_data)

    # initialize ciphertext binary stream
    fCiph = io.BytesIO()

    # encrypt stream
    pyAesCrypt.encryptStream(fIn, fCiph, password, bufferSize)

    # print encrypted data
    print("This is the ciphertext:\n" + str(fCiph.getvalue()))
    with open("Output.txt", "w") as text_file:
        text_file.write(str(fCiph.getvalue()))


def dec():
    with open("Output.txt", "r") as text_file:
        cipher_text = text_file
        fCiph = io.BytesIO(cipher_text.read().encode())
    # get ciphertext length
    ctlen = len(fCiph.getvalue())

    # go back to the start of the ciphertext stream
    fCiph.seek(0)

    # initialize decrypted binary stream
    fDec = io.BytesIO()

    # decrypt stream
    pyAesCrypt.decryptStream(fCiph, fDec, password, bufferSize, ctlen)

    # print decrypted data
    print("Decrypted data:\n" + str(fDec.getvalue()))

    # decrypted data back as dict
    output_dict = json.loads(fDec.getvalue())

    print(output_dict['pass1'])


enc()
dec()

I am getting the error ValueError: File is corrupted or not an AES Crypt (or pyAesCrypt) file.
Is there something wrong with the way I am opening the cypher text?


Solution

  • The data must be stored and read in binary, otherwise they will be corrupted, i.e.

    • at the end of enc() it must be:
    with open("Output.txt", "wb") as text_file: # Fix 1a: binary, i.e. replace w with wb
        text_file.write(fCiph.getvalue())       # Fix 2a: binary, i.e. remove str()
    
    • and accordingly at the beginning of dec():
    with open("Output.txt", "rb") as text_file: # Fix 1:  binary, ie. replace r with rb
        cipher_text = text_file
        fCiph = io.BytesIO(cipher_text.read())  # Fix 2b: binary, i.e. remove encode()
    

    With these changes, decryption works.