在 PHP 中用于 ECB 解密与蟒蛇

我在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 error


Traceback (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

问题:

  1. 为什么 6 字节长的密钥适用于 PHP,但不适用于 Python?

  2. Python中是否有任何其他模块可以使它工作?


烙印99
浏览 136回答 1
1回答

慕姐8265434

PHP 实现为键添加零填充。手动向键添加填充后,以下代码工作正常:from Crypto.Cipher import DESimport binasciienc_string = '9bb6eab4c48319d09921c7400abdc811d54981744e9a2f40'key = 'F6d^*g'.encode('utf-8')key = key + b'\0' * (8 - len(key) % 8) ## add paddinga = DES.new(key, DES.MODE_ECB) # This gives me errordecrypted = a.decrypt(binascii.unhexlify(enc_string))print(decrypted.hex())
打开App,查看更多内容
随时随地看视频慕课网APP