首页 > 解决方案 > 如何使用 python 获得与使用 OpenSSL 相同的解密结果?

问题描述

出于某种原因,我需要使用 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 内容时有类似需求的人。

标签: pythonencryptionopenssl3despycryptodome

解决方案


抱歉,我在计算文件大小时出错了。调整后,它就像一个魅力。

填充也可以,我用过:

decrypted_content = unpad(decrypted_content, 8)

推荐阅读