Skip to main content
 首页 » 编程设计

Python 2之解密 Java 的 PBEWithMD5AndDES

2025年05月04日19飞鱼

这个问题与这个问题相关:Replicate Java's PBEWithMD5AndDES in Python 2.7


这是问题的答案(Python代码):
from Crypto.Hash import MD5 
from Crypto.Cipher import DES 
 
_password = 'q1w2e3r4t5y6' 
_salt = '\x80\x40\xe0\x10\xf8\x04\xfe\x01' 
_iterations = 50 
 
if "__main__" == __name__: 
 
    """Mimic Java's PBEWithMD5AndDES algorithm to produce a DES key""" 
    print "Enter the password to encrypt:", 
    plaintext_to_encrypt = raw_input() 
 
    hasher = MD5.new() 
    hasher.update(_password) 
    hasher.update(_salt) 
    result = hasher.digest() 
 
    for i in range(1, _iterations): 
        hasher = MD5.new() 
        hasher.update(result) 
        result = hasher.digest() 
 
    # Pad plaintext per RFC 2898 Section 6.1 
    padding = 8 - len(plaintext_to_encrypt) % 8 
    plaintext_to_encrypt += chr(padding) * padding 
 
    encoder = DES.new(result[:8], DES.MODE_CBC, result[8:16]) 
    encrypted = encoder.encrypt(plaintext_to_encrypt) 
 
    print encrypted.encode('base64') 

我现在正尝试在知道_password、_salt 和_iterations解密) em> 当然是变量。

print encoder.decrypt(encrypted) 与初始密码不匹配。

我不知道接下来要做什么。我阅读了 rfc2898 的 §6.1.2,但它对我没有帮助。谁能指导我找到正确答案?

编辑:
似乎需要以下内容:

encoder2 = DES.new(result[:8], DES.MODE_CBC, result[8:16]) 
print encoder2.decrypt(encrypted) 

为什么我必须再次使用 DES.new()?我怎样才能去掉填充?
“123456”的实际解密输出是 123456☻☻

请您参考如下方法:

这样做

    decrypted = encoder2.decrypt(encrypted) 
    print decrypted.rstrip('\2,\1,\3,\4,\5,\6,\7') 

“123456”的长度为6,解密器输出8字节。剩余位置用默认字节填充,因此 rstrip 剥离字节并给出字符串。

编辑:我已经创建了一个要点引用这个 Link