0

只是尝试使用MultiFernet.

我的代码是:

from cryptography.fernet import Fernet, MultiFernet

fetnet_keys = [
      Fernet.generate_key(), 
      Fernet.generate_key()
]    
mulfern = MultiFernet(fetnet_keys)
enc = mulfern.encrypt("My Message in Plain Text".encode('utf-8'))

print(enc)

尝试加密我得到的纯文本时:

Traceback (most recent call last):
  File "encryption1.py", line 21, in <module>
    enc = mulfern.encrypt("My Message in Plain Text".encode('utf-8'))
  File "venv3.8\lib\site-packages\cryptography\fernet.py", line 169, in encrypt
    return self.encrypt_at_time(msg, int(time.time()))
  File "venv3.8\lib\site-packages\cryptography\fernet.py", line 172, in encrypt_at_time
    return self._fernets[0].encrypt_at_time(msg, current_time)
AttributeError: 'bytes' object has no attribute 'encrypt_at_time'

解决方案是什么?

4

1 回答 1

1

Fernet.generate_key()返回一个bytes对象。该键应该用于初始化Fernet对象。 MultiFernet()获取Fernet对象列表。NoteMultiFernet使用列表中的第一个密钥进行加密,但通过尝试每个密钥进行解密。

例子:

from cryptography.fernet import Fernet, MultiFernet, InvalidToken

old_key = Fernet(Fernet.generate_key())
new_key = Fernet(Fernet.generate_key())

mulfern = MultiFernet([new_key, old_key])

old_enc = old_key.encrypt(b'old message')
print(old_enc)
new_enc = mulfern.encrypt(b'My Message in Plain Text')
print(new_enc)

try:
    print(old_key.decrypt(new_enc))
except InvalidToken:
    print('old_key failed')
print(mulfern.decrypt(old_enc))
print(mulfern.decrypt(new_enc))

输出:

b'gAAAAABgo0EvjyAPIc3jHHYBc8iTppwENHPO16S_suoaq3u3UzXUuTcxEmvFr62ZEvw53lPJ9MDYO2A5Ys2dPP77B61jHYbrFQ=='
b'gAAAAABgo0Ev8a4Ixt6HHGVJ8Udkr1gJfjmcfg-Wd96NOR8lrpkhS7USVrZj0WiF74druiZHiDhXxxSt1Wb2CURHYdlZ8-o0SEcEhfOzEl66qgVX2pyNP6Y='
old_key failed
b'old message'
b'My Message in Plain Text'
于 2021-05-18T04:04:44.300 回答