【发布时间】:2019-06-02 23:41:34
【问题描述】:
我在 Java 中使用 null IV 运行了 Trible DES 加密(我已经运行了 cipher.getIV() 方法,实际上它的 IV 为空),并且相同的字符串在 PHP 中使用 null IV 运行了三重 DES 加密,但是我得到不同的结果。这是为什么呢?
Java 代码:
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 代码:
// 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];
}
我想修改我的 PHP 代码以适应 Java 加密过程,我应该怎么做?问题在哪里?
Java 加密结果:
before: 622700300000
key: 0123456789ABCDEFFEDCBA98765432100123456789ABCDEF
after: c9aa8ebfcc12ce13e22a33b05d4c18cf
PHP 加密结果:
before: 622700300000
key: 0123456789ABCDEFFEDCBA98765432100123456789ABCDEF
after: a6e7a000d4ce79ac8b3db9f6acf73de3
固定的 PHP 代码:
/**
* 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);
}
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
标签: java php encryption des 3des