我想在AES中加密和解密“ ABCD1234”,但输出不相同。 要获得相同的结果我该怎么做?
使用crypto-js加密
function encrypt(string) {
const key = CryptoJS.enc.Utf8.parse("g@eNR@2H'9n/ZF8s");
const encrypted = CryptoJS.AES.encrypt(string, key, {
iv: CryptoJS.enc.Utf8.parse("Fa6Fy$F8.qRvHKU+"),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.NoPadding
});
return encrypted.toString()
}
document.getElementById("encrypted").innerHTML = encrypt("ABCD1234");
则输出为sRdk5O4U + WA =
当我尝试在Java中解密
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
class Main {
public static void main(String[] args) {
String data = "sRdk5O4U+WA=";
String key = "g@eNR@2H'9n/ZF8s";
String iv = "Fa6Fy$F8.qRvHKU+";
try
{
byte[] encrypted1 = Base64.getDecoder().decode(data);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] original = cipher.doFinal(encrypted1);
String decrypt = new String(original).trim();
System.out.println("decrypt "+decrypt);
} catch (Exception e)
{
System.out.println("e "+e.toString());
}
}
}
抛出异常javax.crypto.IllegalBlockSizeException:输入长度不是16个字节的倍数
java代码:https://repl.it/repls/NoxiousWavyMp3
javascript代码:https://codepen.io/anon/pen/ydEpZB