我在使用零填充且没有IV加密的AES128时,java和php方法之间有不同的结果。
这里是PHP代码:
<?php
$ptaDataString = "secretdata";
$ptaDataString = encryptData($ptaDataString);
$ptaDataString = base64_encode($ptaDataString);
function encryptData($input) {
$ptaKey = 'secret';
$iv = "\0";
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $ptaKey, $input, MCRYPT_MODE_CBC, $iv);
return $encrypted;
}
echo $ptaDataString;
?>
这是java代码:
public static String encrypt() throws Exception {
try {
String data = "secretdata";
String key = "secret0000000000";
String iv = "0000000000000000";
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return new sun.misc.BASE64Encoder().encode(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
php结果:kjgE5p / 3qrum6ghdjiVIoA ==
Java结果:zLKhVMksRRr1VHQigmPQ2Q ==
任何帮助将不胜感激, 感谢
答案 0 :(得分:3)
在Java中,表示为字符串的零字节为"\0"
而非"0"
。如果您按如下方式更正示例,则结果匹配:
String data = "secretdata";
String key = "secret\0\0\0\0\0\0\0\0\0\0";
String iv = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
对于IV,它可能更容易编写:
byte[] iv = new byte[<block size>];
在代码的最后一行,您可以访问sun.misc.BASE64Encoder()
。访问以sun.*
开头的任何内容都是不受欢迎的,因为这些是内部类。请考虑使用:
return DatatypeConverter.printBase64Binary(encrypted);