JavaScript WebCrypto importKey 错误:AES 密钥数据必须为 128 或 256 位

fre*_*ed_ 1 javascript encryption cryptography aes webcrypto-api

我正在尝试导入现有的密钥,但无论我做什么,我都会得到:“AES 密钥数据必须是 128 位或 256 位”

我有一个从 0 到 255 的 128 个 int ArrayBuffer,即使我用 Uint8Array 包装它也不起作用。即使是新的 Uint8Array(128) 也会返回相同的错误。

crypto.subtle.importKey("raw", new Uint8Array(128), { name: "AES-CBC" }, true, ["encrypt", "decrypt"]).then(cryptoKey => {
            console.log(cryptoKey);

        }).catch(err => {
            console.log(err);
            });
Run Code Online (Sandbox Code Playgroud)

Poi*_*nty 5

错误很明显;您使用的密钥缓冲区太大(1024 位)。如果您使用 16 或 32 个元素的Uint8数组,它可以工作:

crypto.subtle.importKey("raw", new Uint8Array(16), { name: "AES-CBC" }, true, ["encrypt", "decrypt"]).then(cryptoKey => {
    console.log(cryptoKey);

}).catch(err => {
    console.log(err);
});
Run Code Online (Sandbox Code Playgroud)