Python加密失败,出现“ciperagrithm的预期接口”

2024-09-29 01:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用加密python模块(cryptography.io),但无法实现一个有效的示例。From example in documentation。在

此代码:

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import openssl
from cryptography.hazmat.backends import default_backend

dbackend = default_backend
iv = 'ababababcdcdcdcd1212121234343434'.encode('hex')
cipher = Cipher(modes.CBC(iv), algorithms.AES('aabbccddaabbccdd1122334411223344'.decode('hex')), backend=dbackend)

e = cipher.encryptor()
ct = e.update("Secret messagexx") + e.finalize()

d = cipher.decryptor()

clear = d.update(ct) + d.finalize()

失败原因:

^{pr2}$

然后我尝试使用openssl后端:

obackend = openssl.backend
cipher = Cipher(modes.CBC(iv), algorithms.AES('aabbccddaabbccdd1122334411223344'.decode('hex')), backend=obackend)

失败的原因是:

TypeError: Expected interface of CipherAlgorithm.

我一直在尝试阅读文档,但我甚至不能让示例代码正常工作。感谢任何帮助。在

更新-已解决

如果有人在这个问题上遇到了问题,我在这里添加了一个有效的例子(我使用了ECB模式,这正是我真正想要的)。在

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

backend = default_backend()
cipher = Cipher(algorithms.AES('aabbccddaabbccdd1122334411223344'.decode('hex')), modes.ECB(), backend=backend)

e = cipher.encryptor()
ct = e.update("Secret messagexx") + e.finalize()

d = cipher.decryptor()

clear = d.update(ct) + d.finalize()

print clear

Tags: fromimportbackenddefaultupdatebackendscryptographycipher
1条回答
网友
1楼 · 发布于 2024-09-29 01:23:06

您将default_backend作为后端参数传递,但这实际上是一个函数。用default_backend()调用它,它将返回一个可以传入的后端对象。在

非危险层包含一个对称加密配方(称为Fernet),因此如果满足您的需要,您可能会考虑使用它。在

相关问题 更多 >