I have a project which encrypts and decrypts texts. I am using Fernet to encrypt and decrypt. I learned how to use encrypt_at_time
function but I didn't understood decrypt_at_time
function. I was looked here:
https://cryptography.io/en/latest/fernet/#
It says I must write token
, ttl
and current_time
in the decrypt_at_time()
function. Token is encrypted text, but I didn't understood what is ttl
and current_time
I want to get the encrypted time from encrypted text. How can I do it?
I want to get the encrypted time from encrypted text. How can I do it?
The structure of the Fernet token is, s. Fernet Spec:
Version | Timestamp | IV | Ciphertext | HMAC
where version is 1 byte long, timestamp 8 bytes, IV 16 bytes, ciphertext a multiple of 16 bytes, and HMAC 32 bytes.
Here the timestamp is the time in seconds elapsed between 1970-01-01 00:00:00 UTC and the creation of the token, s. here. Thus from the timestamp the elapsed time in seconds can be determined and from this the date, s. here:
from cryptography.fernet import Fernet
from datetime import datetime
def getCreationDateTime(token):
timestamp = f.extract_timestamp(token)
creationDateTime = datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
return creationDateTime
key = Fernet.generate_key()
f = Fernet(key)
token = f.encrypt(b'My secret data')
print(getCreationDateTime(token)) # e.g. 2021-04-28 18:29:42
I didn't understood decrypt_at_time function...I didn't understood what is ttl and current_time
In encrypt_at_time()
with the second parameter (current_time
) an arbitrary time can be specified as creation time of the token. Here again the time in seconds must be specified, which elapsed between 1970-01-01 00:00:00 UTC and the alleged creation time of the token. This can be easily tested with the above code by replacing the encryption with:
token = f.encrypt_at_time(b'My secret data', 0)
print(getCreationDateTime(token)) # 1970-01-01 00:00:00
which sets the 1970-01-01 00:00:00 UTC as the creation time.
In decrypt_at_time()
the third parameter (current_time
) can be used to specify an arbitrary time as decryption time (again as time in seconds which elapsed between 1970-01-01 00:00:00 UTC and the alleged decryption time of the token). The second parameter (ttl
) specifies the time in seconds that the token is valid after its creation. Test:
token = f.encrypt_at_time(b'My secret data', 0)
plaintext = f.decrypt_at_time(token, 45, 30)
print(plaintext) # b'My secret data'
Here the token is supposedly created on 1970-01-01 00:00:00 UTC, on allegedly 1970-01-01 00:00:30 UTC the decryption is performed. The token is valid because it is valid for 45s after its creation.