dongqian7545 2014-05-02 12:24
浏览 123
已采纳

PHP中的3DES结果与Python中的3DES产生不同的结果

PHP code:

$key = '111111111111111111111111'; //length: 24
$iv = "\0\0\0\0\0\0\0\0"; //8 bytes
$data = mcrypt_encrypt(MCRYPT_TRIPLEDES, $key, "SECRET", MCRYPT_MODE_CBC, $iv);  
base64_encode($data); 
// Result: ZGF0YQ==

Python code (using m2crypto):

cipher = Cipher(alg='des_ede3_ecb', key="111111111111111111111111", op=encrypt, iv='\0'*8)
ciphertext = cipher.update("SECRET")
ciphertext += cipher.final()
base64.b64encode(ciphertext)
# Result: LhBqW6pGRoQ=

Python code (using pyDes):

k = pyDes.triple_des('111111111111111111111111', mode=pyDes.CBC, IV=b'\0'*8, pad=None, padmode=pyDes.PAD_PKCS5)
d = k.encrypt("SECRET")
base64.b64encode(d)
# Result: LhBqW6pGRoQ=

So Python gets the same result for different library, but PHP not ;/ Anybody see here any bug?

Thank you!

  • 写回答

1条回答 默认 最新

  • doume5227 2014-05-02 12:41
    关注

    PHP mcrypt doesn't handle PKCS5 padding, instead it uses simple zero padding. This is why you get different results compared to Python libs which use PKCS5 padding.

    Here a workaround to get PKCS5 padding in PHP: https://chrismckee.co.uk/handling-tripledes-ecb-pkcs5padding-php/

    EDIT

    I confirm it works with this guy's lib:

    $key = '111111111111111111111111';
    $x = "SECRET";
    print(urldecode(encrypt($x, $key)));
    

    (for some reason he decided to URL encode the result)

    $ php test.php 
    LhBqW6pGRoQ=
    

    EDIT2

    Here is how to use classic padding with pyDes:

    import pyDes
    import base64
    
    k = pyDes.triple_des('111111111111111111111111', mode=pyDes.CBC, IV=b'\0'*8,
                         pad='\0', padmode=pyDes.PAD_NORMAL)
    d = k.encrypt("SECRET")
    print base64.b64encode(d)
    

    It gives the same result as mcrypt.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?