fred_
fred_

Reputation: 1696

JavaScript WebCrypto importKey error : AES key data must be 128 or 256 bits

I m trying to import an existing key but what ever I do I get : "AES key data must be 128 or 256 bits"

I have an ArrayBuffer of 128 int from 0 to 255, and it's not working even I wrap it with Uint8Array. Even an new Uint8Array(128) returns the same error.

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

        }).catch(err => {
            console.log(err);
            });

Upvotes: 7

Views: 5738

Answers (1)

Pointy
Pointy

Reputation: 413709

The error is pretty clear; the key buffer you're using is too big (1024 bits). If you use a 16 or 32 element Uint8 array, it works:

  • An 8 bit array with 16 elements = 128 bits.
  • An 8 bit array with 32 elements = 256 bits.
const cryptoKey = await crypto.subtle.importKey("raw", new Uint8Array(16), { name: "AES-CBC" }, true, ["encrypt", "decrypt"])
console.log(cryptoKey);

Upvotes: 12

Related Questions