dongyong2906 2014-01-29 21:51
浏览 845

DES加密字符串并转换为十六进制

I am trying to find a way in PHP that can encrypt a string in hex using DES algorithm. The result I need should be exactly like this page.

All PHP codes that I tried gave different results than what I got in that page. I tried this code for example:

<?php
function Encrypt($data, $key)
{    
  $encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
  return $encData;
}
echo strtoupper(bin2hex(Encrypt("12341234", "1100000120140129")));
?>

The result was: 0D54E1C0B08DCB90. While in this link, the result is: 4DC7D8B78F0F33A3.

Note that 31313030303030313230313430313239 is 1100000120140129 in hex and 3132333431323334 is 12341234 in hex.

  • 写回答

2条回答 默认 最新

  • duanchensou8685 2014-01-30 09:24
    关注

    This problem seems to be caused by the way PHP reads keys and data when you supply them as strings. Solve this problem by using code such as the following:

    $key = pack('H*', "0123456789abcdef"); // this correctly maps hex to bytes
    $data = pack('H*', "0123456789abcdef");
    echo bin2hex(mcrypt_encrypt(MCRYPT_DES, $key, $data, MCRYPT_MODE_ECB));
    

    This outputs 56cc09e7cfdc4cef which matches the DES calculator (proof).


    For those interested, I also used the following Java code to deduce what was going on. This prints the same result as the PHP:

    SecretKey key = new SecretKeySpec(new byte[8], "DES");
    
    Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    
    System.out.println(DatatypeConverter.printHexBinary(cipher
        .doFinal(new byte[8])));
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!