问题描述
出于某种原因,我需要使用 3DES,我知道它很弱。
这是未加密的原始文本文件:
# cat test.txt
This is the test text file. Used for testing the encryption and decryption differences.
# openssl enc -des3 -pass pass:cfe4ec9fcec928d51d243855a094b05ebb7bc870 -S 3AA6A64F87764632 -in test.txt -out test_encrypted
# cat test_encrypted
Salted__:▒▒O▒vF2^Y▒▒▒▒▒XDŽ▒▒%0-▒1▒▒!▒▒Tn▒▒▒▒9▒▒%w,56,m^δFߚ▒Ű▒>▒-▒J▒zdl▒▒-Y▒r▒(G▒▒▒_A▒▒oD
我把salted-head(16字节)剪成encrypted_content,然后用下面的方法解密:
...
password = 'cfe4ec9fcec928d51d243855a094b05ebb7bc870'.encode()
salt = bytes.fromhex('3AA6A64F87764632')
d1 = hashlib.md5(password+salt)
d2 = hashlib.md5(d1.digest()+password+salt)
keymatter = d1.digest() + d2.digest()
key = keymatter[:24].hex().upper()
iv = keymatter[24:32].hex().upper()
import binascii
import Crypto.Cipher
from Crypto.Cipher import DES3
from Crypto.Util.Padding import pad,unpad
k = Crypto.Cipher.DES3.new(key=binascii.unhexlify(key),mode=2,iv=binascii.unhexlify(iv))
decrypted = k.decrypt(encrypted_content)
print ('decrypted:',decrypted)
但我得到了这个结果:
decrypted: b'\xae\xbb\xef&\xe6|\xfd\x16\xb0\xe23\xad{~\xd2&the test text file. Used for testing the encryption and decryption differences.\x01'
好像头部和尾部没有正确处理?我在想是不是填充问题,但我不能在 Crypto.Util.Padding 中使用填充函数,它总是会提示错误。
更新: 上面的代码将起作用,然后正确加载“encrypted_content”。 我不想删除这个帖子,因为我相信它可以帮助其他有类似需求的人在解密 3DES 内容时。
解决方法
抱歉,我在计算文件大小时出错。调整后,效果很赞。
填充也有效,我用过:
decrypted_content = unpad(decrypted_content,8)