我在PHP中有一个现有的代码,它解密了一个DES-ECB模式的字符串。我知道DES已被弃用,我应该改变一些东西,但这就是现在的样子。示例代码如下所示:$enc_string = '9bb6eab4c48319d09921c7400abdc811d54981744e9a2f40'; // A encrypted string in hex format$key = 'F6d^*g'; // A 6 bytes decryption key$decrypted_string = openssl_decrypt( pack("H*" ,$enc_string), //Use HEX to bin packing 'DES-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING ,'' );请注意,我使用的是6字节长的解密密钥。我现在必须将代码转移到python。我想出了以下结论:>>> from Crypto.Cipher import DES>>> import binascii>>> enc_string = '9bb6eab4c48319d09921c7400abdc811d54981744e9a2f40'>>> key = 'F6d^*g'>>> a = DES.new(key,DES.MODE_ECB) # This gives me errorTraceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.7/site-packages/Crypto/Cipher/DES.py", line 99, in new return DESCipher(key, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/Crypto/Cipher/DES.py", line 63, in __init__ blockalgo.BlockAlgo.__init__(self, _DES, key, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/Crypto/Cipher/blockalgo.py", line 141, in __init__ self._cipher = factory.new(key, *args, **kwargs)ValueError: Key must be 8 bytes long, not 6>>> decrypted = a.decrypt(binascii.unhexlify(enc_string)) # This can't work with 6 bytes long key问题:为什么 6 字节长的密钥适用于 PHP,但不适用于 Python?Python中是否有任何其他模块可以使它工作?
1 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
PHP 实现为键添加零填充。手动向键添加填充后,以下代码工作正常:
from Crypto.Cipher import DES
import binascii
enc_string = '9bb6eab4c48319d09921c7400abdc811d54981744e9a2f40'
key = 'F6d^*g'.encode('utf-8')
key = key + b'\0' * (8 - len(key) % 8) ## add padding
a = DES.new(key, DES.MODE_ECB) # This gives me error
decrypted = a.decrypt(binascii.unhexlify(enc_string))
print(decrypted.hex())
- 1 回答
- 0 关注
- 130 浏览
添加回答
举报
0/150
提交
取消