用PHP加密,用Python解密(des)

时间:2015-03-11 19:02:31

标签: php python encryption

我有PHP代码:

$source = 'test message';
$crypt_key = '01234567';
$td = mcrypt_module_open('des', '', 'ecb', '');
$key = substr($crypt_key, 0, mcrypt_enc_get_key_size($td));
$iv_size = mcrypt_enc_get_iv_size($td);
# MCRYPT_RAND = 2
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); 

if (mcrypt_generic_init($td, $key, $iv) != -1) {
  $crypt = mcrypt_generic($td, $source);
  mcrypt_generic_deinit($td);
  mcrypt_module_close($td);
}
$tokenHex = '';
$tokenLength = strlen($crypt);
for ($i = 0; $i < $tokenLength; $i++) {
  $tokenHex .= sprintf("%02x", ord($crypt{$i}));
}
echo($tokenHex);

结果:

8998c67c86cd5d4d0221e1bee3f3e03e

请帮忙!如何在Python中解密?谢谢!

我试着这样:

from Crypto.Cipher import Blowfish
import binascii
key = b'01234567'
c1  = Blowfish.new(key, Blowfish.MODE_ECB)
res = c1.decrypt(binascii.unhexlify('8998c67c86cd5d4d0221e1bee3f3e03e'))
print(res)

但结果:

b'\xbbU;\x8d\x97{\xbc\x01I\x8bV\x10f%\xabh'

我也试试:

from Crypto.Cipher import DES
des = DES.new('01234567', DES.MODE_ECB)
s1 = binascii.unhexlify('8998c67c86cd5d4d0221e1bee3f3e03e')
print( des.encrypt(s1))

但结果又错了:

b't\xceS\x0b\x97\x14S}\x14\xcc\xf8\x91e\x83e\xd9

1 个答案:

答案 0 :(得分:2)

使用decrypt而不是encrypt(在你的第二个pycrypto示例中)(假设你要解密...而不是加密

>>> print( des.decrypt(s1))
test message