1

I am trying a very basic use case to encrypt and decrypt a sample string. Below is my method. I am using pycryptodome for the encryption.

@staticmethod
def encryptdecrypt(field):
    if field is None:
        return None
    else:
        print("Input Text is --> "+field)
        cipher = AES.new(CryptHelper.secret_key,AES.MODE_EAX)
        text = cipher.encrypt(field.encode('UTF-8'))
        print("Encrypted String --> "+str(text))
        cipher = AES.new(CryptHelper.secret_key,AES.MODE_EAX)
        text = cipher.decrypt(text).decode('cp1252')
        print("Decrypted String --> " +text)        

I am not able to regenerate the original string. I get gibberish o/ps such as below. I tried with different encodings as I am on Windows 10. But none of the give me the original string. Am I missing something here? Am very new to python. so incase if I am performing a blunder, please do let me know.

Input Text is --> Secret
Encrypted String --> b'^\xb4\xc7A\xbc\x05'
Decrypted String --> >F8Ò³…
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
javaShilp
  • 59
  • 1
  • 6

1 Answers1

1

There are two issues with the code within the question:

  1. the nonce is randomly created by the AES object, there needs to be some way to transfer and use the nonce during decryption;
  2. it is required to use encrypt_and_digest and decrypt_and_verify instead of the calls to just encrypt and decrypt, otherwise the authentication tag isn't created (as you would expect for an authenticated mode of operation such as EAX).

The first issue generates the random data, as a different nonces during encryption and decryption will completely change the result after decryption.

The second issue will let the wrong ciphertext pass without verification of the authentication tag, which would generate an error instead of the wrong plaintext message during decryption.

You can read more about this here (cryptodome documentation on authenticated ciphers.


Of course the character encoding has nothing to do with this. You should use the same character encoding on both encryption and decryption. Usually UTF-8 is preferred.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • I will correct the 2 points u mentioned. However, the encoding decoding is still a problem, if I give UTF-8 it says, invalid start byte or invalid continuation byte errors. – javaShilp Apr 06 '18 at 05:37
  • Sorry, did you get the UTF-8 errors before or after fixing the code? Because you *should* expect those errors before fixing them. – Maarten Bodewes Apr 06 '18 at 11:33