douti0687 2019-01-08 09:48
浏览 565
已采纳

为什么在Java中执行DES加密的结果与在PHP中执行的结果不同?

I ran the Trible DES Encryption in Java, with null IV (I have run cipher.getIV() method and indeed it's IV is null) and the same string ran the Triple DES Encryption in PHP with null IV, but I get a different result. Why is that?

Java Code:

private static final String model = "DESede/ECB/PKCS5Padding";
public static String desEncrypt(String message, String key) throws Exception {
    byte[] keyBytes = null;
    if(key.length() == 16){
        keyBytes = newInstance8Key(ByteUtil.convertHexString(key));
    } else if(key.length() == 32){
        keyBytes = newInstance16Key(ByteUtil.convertHexString(key));
    } else if(key.length() == 48){
        keyBytes = newInstance24Key(ByteUtil.convertHexString(key));
    }

    SecretKey deskey = new SecretKeySpec(keyBytes, "DESede");

    Cipher cipher = Cipher.getInstance(model);
    cipher.init(1, deskey);
    return ByteUtil.toHexString(cipher.doFinal(message.getBytes("UTF-8")));
}

PHP Code:

// composer require phpseclib/phpseclib
use phpseclib\Crypt\TripleDES;

function desEncrypt($str,$key){
    $cipher = new TripleDES();
    $cipher->setKey(hex2bin($key));

    $cryptText = $cipher->encrypt($str);

   return unpack("H*",$cryptText)[1];
}

I want to modify my PHP code to fit the Java Encryption Process,how should I do? where is the proplem?

Java Encrypt Result:

before: 622700300000
key: 0123456789ABCDEFFEDCBA98765432100123456789ABCDEF
after: c9aa8ebfcc12ce13e22a33b05d4c18cf

PHP Encrypt Result:

before: 622700300000
key: 0123456789ABCDEFFEDCBA98765432100123456789ABCDEF
after: a6e7a000d4ce79ac8b3db9f6acf73de3

Fixed PHP Code:

/**
 * Triple DES (ECB) Encryption Function
 * PKCS5Padding
 * 
 * @param string $message String needed to be encode
 * @param string $key Hex encoded key
 * @return string Hex Encoded
 */
function desEncrypt($message,$key){
    $cipher = new TripleDES(TripleDES::MODE_ECB);
    $cipher->setKey(hex2bin($key));

    $cryptText = $cipher->encrypt($message);

   return bin2hex($cryptText);
}
  • 写回答

1条回答 默认 最新

  • douxiang3978 2019-01-08 12:07
    关注

    You forgot to hex decode the key before using it. You're also using CBC mode instead of ECB mode, but as your IV is all zero's, that amounts to the same thing for the first block of data that is encrypted.

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵