Python 将整数转换为 16 字节字节

Luk*_*uke 0 python cryptography type-conversion data-conversion

我正在尝试在我的代码中使用 AES-CTR-128。我使用Python 2.7并利用该cryptography模块进行加密。

我需要设置特定的计数器值,例如 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()
Run Code Online (Sandbox Code Playgroud)

这给了我一条错误消息:

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
Run Code Online (Sandbox Code Playgroud)

我认为它告诉我 counter_iv 应该是一个 16 字节的字符串。

我的问题是如何将整数或长整数转换为 16 字节字符串?

另外,有没有办法将整数转换为任意长度的字符串?感谢您的帮助。

Ser*_*sta 5

首先,您是否有充分的理由使用低含量有害物质而不是较高含量 API?此级别旨在仅通过用于特殊目的的高级 API 来使用。

接下来,您通过编写误导任何进一步的读者modes.CTR(counter_iv),因为计数器模式不使用初始化向量,而是根据其文档使用随机数您得到的错误是正常的,因为文档规定随机数应是与密码块大小相同的字节字符串,因此对于 AES,它必须是 128 位或 16 字节。

顺便说一句,文档还指出随机数永远不应该被重复使用

...永远不要对给定的密钥重复使用随机数,这一点至关重要。任何使用相同密钥的随机数的重复使用都会损害使用该密钥加密的每条消息的安全性。

Nayuki 的回答解释了如何从 int 构建 16 字节字符串,但如果您使用低级有害物质,请务必正确使用加密技术