我用null
IV(我已经运行过cipher.getIV()
方法并且确实是IV为空)在Java中运行了Trible DES加密,而同一字符串在{{{ 1}} IV,但是得到了不同的结果。为什么会这样?
Java代码:
null
PHP代码:
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代码以适合Java加密过程,该怎么办?问题在哪里?
Java加密结果:
// 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加密结果:
before: 622700300000
key: 0123456789ABCDEFFEDCBA98765432100123456789ABCDEF
after: c9aa8ebfcc12ce13e22a33b05d4c18cf
固定的PHP代码:
before: 622700300000
key: 0123456789ABCDEFFEDCBA98765432100123456789ABCDEF
after: a6e7a000d4ce79ac8b3db9f6acf73de3
答案 0 :(得分:1)
您忘记了在使用密钥之前对密钥进行十六进制解码。您还使用了CBC模式而不是ECB模式,但是由于IV均为零,因此对于第一个加密数据块 来说,这是相同的事情。