gpt4 book ai didi

javascript - Webcrypto AES-CBC 解密 : Operation Error - The operation failed for an operation-specific reason

转载 作者:行者123 更新时间:2023-11-30 06:24:44 40 4
gpt4 key购买 nike

我有以下代码使用 Javascript Webcrypto-API 解密 AES 加密数据,但它会导致“OperationError”并显示消息“操作因操作特定原因而失败”:

function loadHexToArrybuffer(hex)
{
return new Uint8Array(hex.match(/[\da-f]{2}/gi).map(h => parseInt(h, 16)));
}

var iv = loadHexToArrybuffer("47b79d24e3ec47c528abdaed8f3fafde");
var rawKey = loadHexToArrybuffer("8af4d72873e4016cd73a1d5b851e9cb2");
var encryptedData = loadHexToArrybuffer("2bb7a12a7e59f9fa3c3d4ff0eb502cde3187338cc3137af785995b364fc5b3fe9c208f225c7472bb3de55de18a665863f63030d652b870c4610a70bc771e8bc584df7c3bd2ce3fc1940115e556178e740891f7cac450204a4959916ac9c9cd5aedd92cc7e74a7a581a6d47a6c29fb46eee13ffd3f70616844f8e2bb929c60ad9")

async function test()
{
var algorithm = {name: "AES-CBC", iv: iv};
var key = await window.crypto.subtle.importKey("raw", rawKey, algorithm, false, ["decrypt"]);

try
{
var decrypted = await window.crypto.subtle.decrypt(algorithm, key, encryptedData);
}
catch (e)
{
console.log(e); // OperationError: The operation failed for an operation-specific reason
}
}

test();

有人可以帮我吗?先谢谢了!

最佳答案

您没有说明您使用的是什么浏览器和版本,每个版本都支持一组不同的算法。

如果您想快速测试每种支持的内容,请参阅:https://peculiarventures.github.io/pv-webcrypto-tests/

话虽如此,我的第一个想法是除非需要与仅使用 CBC 的现有系统进行互操作,否则我不会使用 CBC。您应该改为查看 AES-GCM,它是一种经过身份验证的加密模式,可以保护普通 CBC 不会受到某些攻击,并且在使用时不易出错。

这是一个 GCM 的加密示例:

window.crypto.subtle.encrypt(
{
name: "AES-GCM",

//Don't re-use initialization vectors!
//Always generate a new iv every time your encrypt!
//Recommended to use 12 bytes length
iv: window.crypto.getRandomValues(new Uint8Array(12)),

//Additional authentication data (optional)
additionalData: ArrayBuffer,

//Tag length (optional)
tagLength: 128, //can be 32, 64, 96, 104, 112, 120 or 128 (default)
},
key, //from generateKey or importKey above
data //ArrayBuffer of data you want to encrypt
)
.then(function(encrypted){
//returns an ArrayBuffer containing the encrypted data
console.log(new Uint8Array(encrypted));
})
.catch(function(err){
console.error(err);
});

如果您需要使用 CBC,这里有一些很好的用法示例:https://github.com/diafygi/webcrypto-examples#aes-cbc

关于javascript - Webcrypto AES-CBC 解密 : Operation Error - The operation failed for an operation-specific reason,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51172513/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com