如何在 Fernet (Python 3.9) 中使用 decrypt_at_time 函数

How can I use decrypt_at_time function in Fernet (Python 3.9)

我有一个加密和解密文本的项目。我正在使用 Fernet 进行加密和解密。我学会了如何使用 encrypt_at_time 函数,但我不明白 decrypt_at_time 函数。我被看这里了:

https://cryptography.io/en/latest/fernet/#

它说我必须在decrypt_at_time()函数中写tokenttlcurrent_time。 Token是密文,但是没看懂什么是ttlcurrent_time

我想从加密文本中获取加密时间。我该怎么做?

I want to get the encrypted time from encrypted text. How can I do it?

Fernet 代币的结构是,s。 Fernet Spec:

Version | Timestamp | IV | Ciphertext | HMAC

其中版本为 1 字节长,时间戳为 8 字节,IV 为 16 字节,密文为 16 字节的倍数,HMAC 为 32 字节。

这里的时间戳是从 1970-01-01 00:00:00 UTC 到创建令牌 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

encrypt_at_time()中,第二个参数(current_time)可以指定任意时间作为token的创建时间。这里必须再次指定以秒为单位的时间,它在 1970-01-01 00:00:00 UTC 和所谓的令牌创建时间之间流逝。通过将加密替换为:

,可以使用上面的代码轻松测试这一点
token = f.encrypt_at_time(b'My secret data', 0)
print(getCreationDateTime(token)) # 1970-01-01 00:00:00

将 1970-01-01 00:00:00 UTC 设置为创建时间。

decrypt_at_time()中,第三个参数(current_time)可用于指定任意时间作为解密时间(同样是在 1970-01-01 之间经过的时间(以秒为单位)00:00:00 UTC 和所谓的令牌解密时间)。第二个参数 (ttl) 指定令牌在创建后有效的时间(以秒为单位)。测试:

token = f.encrypt_at_time(b'My secret data', 0)
plaintext = f.decrypt_at_time(token, 45, 30)
print(plaintext) # b'My secret data'

这里的令牌应该是在 1970-01-01 00:00:00 UTC 创建的,据称是在 1970-01-01 00:00:30 UTC 执行解密的。该令牌有效,因为它在创建后的 45 秒内有效。