1

Fernet encryption token varies even though the key remains the same. Executing the following example repeatedly will show that.

from cryptography.fernet import Fernet

f = Fernet(b'vIkpEFEgCEOSQDfr9cTgDJnOFp9b2Wb7MLv55BhFYYY=')
print(f.encrypt(b'my_dark_secret'))

Why does this happen and how can I ensure the produced token will remain the same?

cheesus
  • 1,111
  • 1
  • 16
  • 44
  • 1
    Fernet uses AES(-128) in CBC mode under the hood. For each encryption a random IV is generated, so the ciphertext (and the MAC and therefore the token) changes every time. This is for security reasons and cannot be changed. Apart from that, the token also contains a timestamp which also contributes to the change. S. the [Fernet spec](https://github.com/fernet/spec/blob/master/Spec.md). – Topaco Sep 04 '22 at 11:59

1 Answers1

0

As noted by Topcao, the function contains a random + time based factor. Workaround is using the internal Fernet function _encrypt_from_parts:

from cryptography.fernet import Fernet

f = Fernet(b'vIkpEFEgCEOSQDfr9cTgDJnOFp9b2Wb7MLv55BhFYYY=')

def encrypt(unencrypted_string):
    return f._encrypt_from_parts(unencrypted_string.encode(), 0,b'\xbd\xc0,\x16\x87\xd7G\xb5\xe5\xcc\xdb\xf9\x07\xaf\xa0\xfa')

print(encrypt('my dark secret'))
cheesus
  • 1,111
  • 1
  • 16
  • 44