我在 Java 中运行了 Trible DES 加密,使用 null
IV(我运行了 cipher.getIV()
方法,实际上它的 IV 为 null)和相同的字符串使用 null
IV 在 PHP 中运行三重 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);
}
最佳答案
您忘记在使用前对 key 进行十六进制解码。您还使用了 CBC 模式而不是 ECB 模式,但由于您的 IV 全为零,因此对于加密的第一个数据 block 来说,这相当于相同的事情。
关于java - 为什么用Java执行DES加密的结果和用PHP执行的结果不一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54089115/