SubtleCrypto解密报错:参数2非CryptoKey类型该如何解决?
问题原因
- 核心报错原因是传入的密钥参数不符合API要求:
SubtleCrypto.decrypt的第二个参数要求必须是CryptoKey类型实例,你直接传入原始密钥字符串"1234567890123456"当然会触发类型错误,必须先把原始密钥字节数据通过crypto.subtle.importKey方法转换成合规的CryptoKey对象才能使用。 - 同时还存在其他几个不符合API要求的问题:
- AES-CBC模式要求iv必须是16字节长度的
Uint8Array类型,不能传入空字符串,而且要和加密时使用的iv完全一致 - 待解密的密文不能直接传入base64格式字符串,需要先把base64解码为
ArrayBuffer类型 - 原始密钥字符串也需要先转成
Uint8Array类型才能用于导入CryptoKey SubtleCrypto所有方法都是异步的,不能直接同步调用拿结果
- AES-CBC模式要求iv必须是16字节长度的
正确实现示例
// 工具函数:base64转Uint8Array function base64ToUint8Array(base64) { const binaryStr = atob(base64); const len = binaryStr.length; const bytes = new Uint8Array(len); for (let i = 0; i < len; i++) { bytes[i] = binaryStr.charCodeAt(i); } return bytes; } // 工具函数:ArrayBuffer转明文 function arrayBufferToString(buf) { return new TextDecoder().decode(buf); } async function decryptAesData() { // 准备参数:iv请替换为你加密时实际使用的16字节iv,此处仅为示例 const rawKey = new TextEncoder().encode("1234567890123456"); const iv = new TextEncoder().encode("replace_your_16byte_iv"); const ciphertext = base64ToUint8Array("i4+WxNH8XYMnAm7RsRkfOw=="); // 导入原始密钥为CryptoKey对象 const cryptoKey = await crypto.subtle.importKey( "raw", rawKey, { name: "AES-CBC" }, false, ["decrypt"] ); // 执行解密 const decryptedBuf = await crypto.subtle.decrypt( { name: "AES-CBC", iv: iv }, cryptoKey, ciphertext ); // 输出明文 console.log(arrayBufferToString(decryptedBuf)); } decryptAesData();
额外注意事项
- 解密用的iv必须和加密时生成的iv完全一致,否则无法解密出正确结果
- SubtleCrypto默认自动处理PKCS7填充,不需要额外配置
内容的提问来源于stack exchange,提问作者GFL
相关产品推荐
相关产品推荐

