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])));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效