Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Why does a Fernet encryption token always start with the same sequence? (Python Cryptography package)

I've been playing around with the Cryptography package, and the Fernet (symmetric encryption) module.

When encrypting some text like:

key = Fernet.generate_key()
f = Fernet(key)
token = f.encrypt(b"some random text")

The token always starts with the same sequence of bytes like this: "gAAAABU80.....".

Why is this?

like image 663
deef Avatar asked Mar 17 '23 21:03


1 Answers

As you can gather from reading the source code, the encrypted payload has the following structure:

b"\x80" + struct.pack(">Q", current_time) + iv + ciphertext

and what you get back from encrypt is the base64 encoding of the payload.

The first byte is 0x80, hardcoded. The following 8 bytes are a 64bit timestamp, in big-endian order. Since it's a timestamp, the most significant bytes will change slowly over time. Big-endian is ordered MSB to LSB, so those "sticky" bytes are the first you will encounter when reading the string.

Base64 (partial) string gAAAABU80 encodes 54bits, which is almost 7 bytes. So, that part encodes the 0x80 magic and the 6 MSBs of the timestamp, those that will change slower over time. Wait a few hours before encrypting a new message and you will see the header change.

like image 82
Stefano Sanfilippo Avatar answered Mar 30 '23 00:03

Stefano Sanfilippo