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 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝