我有一个加密和解密文本的项目。我正在使用 Fernet 进行加密和解密。我学习了如何使用 encrypt_at_time
函数,但不理解 decrypt_at_time
函数。我在这里被看:
https://cryptography.io/en/latest/fernet/#
它说我必须在 decrypt_at_time()
函数中写入 token
、ttl
和 current_time
。 Token是加密文本,但我不明白什么是ttl
和current_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 到创建 token s 之间耗时(以秒为单位)。 here 。因此,根据时间戳可以确定耗时(以秒为单位),并由此确定日期 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 创建时间之间经过的。通过将加密替换为以下内容,可以使用上述代码轻松测试:
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 和所谓的解密时间之间经过) token )。第二个参数 (ttl
) 指定 token 创建后的有效时间(以秒为单位)。测试:
token = f.encrypt_at_time(b'My secret data', 0)
plaintext = f.decrypt_at_time(token, 45, 30)
print(plaintext) # b'My secret data'
这里的 token 据称是在 1970-01-01 00:00:00 UTC 创建的,据称是在 1970-01-01 00:00:30 UTC 执行解密的。 token 有效,创建后45秒内有效。
关于python-3.x - 如何在 Fernet (Python 3.9) 中使用 crypto_at_time 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67300341/