【发布时间】:2016-05-19 21:19:04
【问题描述】:
我正在尝试在我的代码中使用 AES-CTR-128。我使用 Python 2.7 并利用 cryptography 模块进行加密。
我需要设置特定的Counter值,例如counter_iv = 112。当我尝试时
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
backend = default_backend()
key = os.urandom(32)
counter_iv = 112
cipher = Cipher(algorithms.AES(key), modes.CTR(counter_iv), backend=backend)
encryptor = cipher.encryptor()
ciphertext = encryptor.update(b"a secret message") + encryptor.finalize()
这给了我一条错误消息:
Traceback (most recent call last): File "aestest.py", line 14, in <module> cipher = Cipher(algorithms.AES(key), modes.CTR(counter_iv), backend=backend) File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/primitives/ciphers/modes.py", line 139, in __init__ raise TypeError("nonce must be bytes") TypeError: nonce must be bytes
我认为它告诉我 counter_iv 应该是一个 16 字节的字符串。
我的问题是如何将整数或长整数转换为 16 字节字符串?
此外,有没有办法将整数转换为任意长度的字符串?感谢您的帮助。
【问题讨论】:
-
什么是
encryptor? -
@Padraic Cunningham 忘记添加了。现在它就在那里。
-
警告:你的计数器不应该是静态的,当然不能用于 CTR 模式。请理解 nonce 和计数器值之间的区别,否则您的方案可能非常不安全。
标签: python cryptography type-conversion data-conversion