英文:
Combine two result from CryptoJS
问题
我已使用CryptoJS库在Nodejs上进行了AES加密,一切正常。
但最后,我想将IV放在前16个字节,然后将加密数据放入一个字节数组中,然后进行Base64编码,但我不知道如何在Nodejs中实现这一点。
以下是我将进行加密的代码:
let secret = 'Hello';
var key = CryptoJS.enc.Base64.parse('QVNES0FVemFzZHVoMjM0MzIyNjlCNTIyRTcwNUQ0RjI=');
let ivByte = crypto.randomBytes(16);
let newIV = this.toCryptoJSWordArray(ivByte);
CryptoJS.AES.encrypt(secret, key, { iv: newIV, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
一切正常,结果如下:
console.log({
text: 'Hello',
iv: CryptoJS.enc.Base64.stringify(newIV),
enc: CryptoJS.enc.Base64.stringify(e1.ciphertext),
})
输出的IV和加密文本都以Base64格式正确且符合我的预期。
现在,我想将这两者合并为一个字节数组(就像前16字节是IV + 加密数据(都不是Base64),然后将它们转换为Base64格式),但我不知道如何做。
预期的输出是:
QVNES0FVemFzZHVoMjM0MzIyNjlCNTIyRTcwNUQ0RjI=
英文:
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=
答案1
得分: 1
CryptoJS提供了concat()
用于连接WordArrays:wa1.concat(wa2)
。这会将wa2
附加到wa1
。
如果不想更改wa1
,可以使用clone()
来复制它:wa1.clone().concat(wa2)
。
英文:
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)
:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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=
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论