接收含IV的Base64串,如何拆分CryptoJS WordArray提取IV解密?
CryptoJS拆分IV与密文及WordArray操作指南
问题描述
我收到一个Base64编码字符串,其前16字节为IV(初始化向量),需要在使用CryptoJS进行解密操作前提取该IV。目前无法从CryptoJS.enc.Base64.parse的返回结果中拆分出所需数据,同时对返回的WordArray对象类型的处理存在困惑,不清楚具体操作方式。需要补全以下代码:
/* * ivAndcipheredDataBase64: first 16 bytes are iv the rest is the cipheredData */ function decipherData(ivAndcipheredDataBase64, key) { var ivAndCipheredDataBytes = CryptoJS.enc.Base64.parse(ivAndcipheredDataBase64); var iv = // What do I put here to get cipheredIVAndDataBytes[0:16] var cipheredData = // What do I put here to get cipheredIVAndDataBytes[16:len(cipheredIVAndDataBytes)] var plainDataBytes = CryptoJS.AES.decrypt({ ciphertext: cipheredData }, key, { iv: iv }); return plainDataBytes.toString(CryptoJS.enc.Utf8) }
代码补全与解释
CryptoJS的WordArray对象内置了slice方法,可以直接按字节索引截取数据,补全后的代码如下:
/* * ivAndcipheredDataBase64: first 16 bytes are iv the rest is the cipheredData */ function decipherData(ivAndcipheredDataBase64, key) { var ivAndCipheredDataBytes = CryptoJS.enc.Base64.parse(ivAndcipheredDataBase64); // 提取前16字节作为IV var iv = ivAndCipheredDataBytes.slice(0, 16); // 提取从第16字节开始到末尾的密文数据 var cipheredData = ivAndCipheredDataBytes.slice(16); var plainDataBytes = CryptoJS.AES.decrypt({ ciphertext: cipheredData }, key, { iv: iv }); return plainDataBytes.toString(CryptoJS.enc.Utf8) }
WordArray对象操作说明
WordArray是CryptoJS专门用于处理二进制数据的核心对象,内部通过words数组存储数据(每个元素为32位整数,对应4个字节),sigBytes属性记录实际有效的字节总数,避免数组末尾无效数据干扰。- 常用操作:
slice(start, end):截取指定字节范围的子WordArray,end参数可省略,省略时默认截取到数据末尾。concat(otherWordArray):将当前WordArray与另一个WordArray合并。toString(encoder):通过指定编码器(如CryptoJS.enc.Utf8、CryptoJS.enc.Base64)转换为对应格式的字符串。CryptoJS.enc.Base64.parse(str):将Base64字符串转换为WordArray;CryptoJS.enc.Utf8.parse(str)则是将UTF8字符串转换为WordArray。
内容的提问来源于stack exchange,提问作者RudeusGreyrat
相关产品推荐
相关产品推荐

