我需要使用JavaScript实现AES加密。使用AES/CBC/NoPadding模式并创建一个方法来完成16长度的块。我已经使用Java解决了这个问题。它看起来像这样:
public static String encrypt(byte[] key, byte[] initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector);
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(completeBlocks(value));
return Base64.encodeBase64String(encrypted);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) {
System.out.println("Error: " + ex);
}
return null;
}
/**
* Completes 16 lenght blocks
*
* @param message
*
*
*/
static byte[] completeBlocks(String message) {
try {
int bytesLenght = message.getBytes("UTF-8").length;
if (bytesLenght % 16 != 0) {
byte[] newArray = new byte[bytesLenght + (16 - (bytesLenght % 16))];
System.arraycopy(message.getBytes(), 0, newArray, 0, bytesLenght);
return newArray;
}
return message.getBytes("UTF-8");
} catch (UnsupportedEncodingException ex) {
System.out.println("" + ex);
}
return null;
}
public static void main(String[] args) {
String key = "253D3FB468A0E24677C28A624BE0F939";
String strToEncrypt = "My Secret text";
final byte[] initVector = new byte[16];
String resultado = encrypt(new BigInteger(key, 16).toByteArray(), initVector, strToEncrypt.trim());
System.out.println("ENCRYPTED:");
System.out.println(resultado);
}
使用输入 key = 253D3FB468A0E24677C28A624BE0F939
,strToEncrypt = "My Secret text"
和零向量(IV)进行加密。它会产生如下输出:
7StScX3LnPUly/VNzBes0w==
我知道这是期望的输出结果,正确无误! 我尝试使用JavaScript复制此结果。我使用了CryptoJs库。但我无法生成与Java相同的输出结果。我已经尝试过:
var text = "My Secret text";
var key = CryptoJS.enc.Base64.parse("253D3FB468A0E24677C28A624BE0F939");
var iv = CryptoJS.enc.Base64.parse(" ");
var encrypted = CryptoJS.AES.encrypt(text, key, {iv: iv});
console.log(encrypted.toString());
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv});
console.log(decrypted.toString(CryptoJS.enc.Utf8));
使用相同的输入,我得到了
De+CvPVIyiBX2//EE6gXTg==
作为输出。我做错了什么?我怎样才能得到与Java相同的输出?非常感谢!