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 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴