简体   繁体   中英

DES ECB decryption in PHP vs Python

I have an existing code in PHP which decrypts a DES-ECB mode encypted string. I know DES has been deprecated and I should be changing things but it is what it is for now.

Sample code looks like this:


$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 ,''
                    );

Please note that I am using a 6 bytes long decryption key.

I now have to shift the code to python. I came up with following:

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

Questions:

  1. Why does a 6 bytes long key works with PHP but not with python?
  2. Is there any other module in python to make this work?

PHP implementation adds zero padding to the key. The below code works fine after manually adding padding to the key:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM