I'm trying to understand how to use the AES of CryptoJS to encrypt some data. I made a simple HTML page with JavaScript to see CryptoJS AES in action.
At first I thought encryption/decryption was working perfectly. But then I tried to change the passphrase, salt, and IV. I found out that, given the same message, the resulting ciphertext is identical no matter how I change the passphrase, salt, and IV.
I downloaded aes.js
and pbkdf2.js
from v3.1.2 of https://code.google.com/archive/p/crypto-js/downloads and referred to https://github.com/mpetersen/aes-example
Here is my HTML in its entirety (since it is a really simple page I think it's okay to post the entire thing)
<!DOCTYPE html>
<head>
<title>Decryptor</title>
</head>
<body>
<input type="text" id="inputElement" />
<button id="decrypt">Decrypt!</button>
<br />
<p id="ciphertext">
Ciphertext
</p>
<p id="plaintext">
Plaintext
</p>
</body>
<script src="aes.js"></script>
<script src="pbkdf2.js"></script>
<script type="text/javascript">
function decrypt() {
var input = document.getElementById("inputElement").value;
var ciphertextElement = document.getElementById("ciphertext");
var plaintextElement = document.getElementById("plaintext");
var message = input;
var passphrase = "myPassphrase";
var salt = "mySalt";
var iv = "myIV";
var key = CryptoJS.PBKDF2(
passphrase,
CryptoJS.enc.Hex.parse(salt),
{ keySize: this.keySize, iterations: this.iterationCount }
);
var parsedIV = CryptoJS.enc.Hex.parse(iv);
var encrypted = CryptoJS.AES.encrypt(
message,
key,
{ iv: parsedIV }
);
var ciphertext = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
ciphertextElement.innerHTML = ciphertext;
var cipherParams = CryptoJS.lib.CipherParams.create(
{ ciphertext: CryptoJS.enc.Base64.parse(ciphertext) }
);
var decrypted = CryptoJS.AES.decrypt(
cipherParams,
key,
{ iv: parsedIV }
);
var plaintext = decrypted.toString(CryptoJS.enc.Utf8);
plaintextElement.innerHTML = plaintext;
}
var decryptionButton = document.getElementById("decrypt");
decryptionButton.onclick = decrypt;
</script>
</html>
I took the advice from @dandavis and @artjom-b.
Because my salt and iv are string, I parse them with Utf8:
CryptoJS.enc.Utf8.parse(salt);
CryptoJS.enc.Utf8.parse(iv);
And for key generation, I use static values:
var key = CryptoJS.PBKDF2(
passphrase,
CryptoJS.enc.Utf8.parse(salt),
{ keySize: 512/32, iterations: 1000 }
);
And now the ciphertext changes as I change the passphrase, salt, and iv values.