【发布时间】:2019-09-22 12:07:17
【问题描述】:
在Python中,使用Cryptography.Hazmat模块对于AES,加密的输出长度不是16的倍数;我是否实施了错误的加密密码,如果是,出了什么问题?我收到的输出长度是16 + len(input)(16,因为它是 IV 的长度)。下面是代码:
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers.modes import CBC,OFB,CFB
class AES_Cipher:
def __init__(self,key):
self.key = key
def encrypt(self,plain_text):
initialization_vector = urandom(16)
cipher = Cipher(AES(self.key),OFB(initialization_vector),backend)
encryption_engine = cipher.encryptor()
return initialization_vector + encryption_engine.update(plain_text.encode("utf-8")) + encryption_engine.finalize()
def decrypt(self,cipher_text):
initialization_vector = cipher_text[:16]
cipher = Cipher(AES(self.key),OFB(initialization_vector),backend)
decryption_engine = cipher.decryptor()
return (decryption_engine.update(cipher_text[16:]) + decryption_engine.finalize()).decode("utf-8")
密码是这样调用的:
from hashlib import sha3_256
aes_key = sha3_256(b"Strong Encryption Key").digest()
aes_engine = AES_Cipher(aes_key)
aes_engine.encrypt("Hello World")
结果如下:
b'\xc4I\xf2\xe5\xf4\xaeX\x96\xa5\xfe\xbd+\xde\x8ca\xd5\xdb\xad\x97S\x01\x81C\x9e\xd5\xd8@'
与预期的 32 字节相比,这只有 27 字节长。 27 = 16 + len("Hello World")。为什么不是 32 字节长?缺少什么代码?另一件事;解密工作得很好。
【问题讨论】:
标签: python encryption cryptography string-length