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 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改