【问题标题】:python aes encrypt/decrypt does not return the same resultspython aes 加密/解密不返回相同的结果
【发布时间】:2012-03-12 18:42:30
【问题描述】:

以下代码示例在加密/解密操作后不返回原始文本,我正在尝试找出原因

from Crypto.Cipher import AES

text = """This is plain text 
to use.
It should be exqctly 128 characters long to avoid padding and it is split
with new lines as in 
file"""

password = "password........"

block = 32
mode = AES.MODE_CBC

enc = AES.new(password, mode)

encrypted = enc.encrypt(text)

print "ORIGINAL: " + text

print "ENCRYPTED: " + str(encrypted)

print "DECRYPTED: " + str(enc.decrypt(encrypted))

谁能说出为什么文本的第一部分格式错误?

【问题讨论】:

    标签: python cryptography aes malformed


    【解决方案1】:

    我认为,您需要重置初始化向量 (IV),以获得所需的结果。最简单的方法可能是创建一个新的 AES 对象进行解密:

    enc = AES.new(password, mode)
    encrypted = enc.encrypt(text)
    print "ORIGINAL: " + text
    print "ENCRYPTED: " + str(encrypted)
    dec = AES.new(password, mode)
    print "DECRYPTED: " + str(dec.decrypt(encrypted))
    

    【讨论】:

    • 您不能明确设置并获取 IV 吗?最好是获取加密器的IV并设置解密器的IV。
    • 可以在构造函数中设置(第三个参数为AES.new)。我认为当前的实现使用默认的 IV(不是随机的),因此没有必要将其从加密器复制到解密器(注意,这必须在加密之前完成 ! )。出于安全原因,最好为每次加密使用不同的(随机)IV,但您需要以某种方式将其传递给解密器,因此可能不值得付出额外的努力......有关更多信息,请参阅en.wikipedia.org/wiki/Initialization_vector .
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    相关资源
    最近更新 更多