I have used AES encryption with CryptoJS library on the Nodejs and everything works fine But finally I want to put the IV in first 16 byte then encrypted data into an array byte then base64 it But I don't know how to do it in nodejs
let secret = 'Hello';
var key = CryptoJS.enc.Base64.parse('QVNES0FVemFzZHVoMjM0MzIyNjlCNTIyRTcwNUQ0RjI=');
let ivByte= crypto.randomBytes(16);
let newIV= this.toCryptoJSWordArray(ivByte);
I will encrypt like this :
CryptoJS.AES.encrypt(secret, key, {iv: newIV, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
Every this is fine and result is :
console.log({
text:'Hello',
iv:CryptoJS.enc.Base64.stringify(newIV),
enc:CryptoJS.enc.Base64.stringify(e1.ciphertext),
})
Both output IV & encrypted text base64 correctly and as I expected
Now I want to combine these two into an array bytes (Like first 16byte is IV encrypted data (None are base64) and then convert them to base64 format, meaning u before base64 IV and Encrypted text combine them to one array then base64 them but I don't know how do it Expected output is : QVNES0FVemFzZHVoMjM0MzIyNjlCNTIyRTcwNUQ0RjI=
CodePudding user response:
CryptoJS provides concat()
for the concatenation of WordArrays: wa1.concat(wa2)
. This appends wa2
to wa1
.
If wa1
is not to be changed, it is to be duplicated with clone()
: wa1.clone().concat(wa2)
:
var ivWA = CryptoJS.enc.Base64.parse('J78xP3jq dhgwTJrXiQW9A==');
var ciphertextWA = CryptoJS.enc.Base64.parse('amBBgezSkW1SQamv8pnaQg==');
var ivCiphertextWA = ivWA.clone().concat(ciphertextWA);
console.log(ivWA.toString(CryptoJS.enc.Base64)); // J78xP3jq dhgwTJrXiQW9A==
console.log(ciphertextWA.toString(CryptoJS.enc.Base64)); // amBBgezSkW1SQamv8pnaQg==
console.log(ivCiphertextWA.toString(CryptoJS.enc.Base64)); // J78xP3jq dhgwTJrXiQW9GpgQYHs0pFtUkGpr/KZ2kI=
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>