Skip to content

SubtleCrypto.supports example uses invalid AES-OCB IV length #63713

@davidebombelli

Description

@davidebombelli

Affected URL(s)

https://nodejs.org/api/webcrypto.html#checking-for-runtime-algorithm-support

Description of the problem

When running the following code in Node version 26.3.0:

const { SubtleCrypto, crypto } = globalThis;

const password = 'correct horse battery staple';
const derivationAlg =
  SubtleCrypto.supports?.('importKey', 'Argon2id') ?
    'Argon2id' :
    'PBKDF2';
const encryptionAlg =
  SubtleCrypto.supports?.('importKey', 'AES-OCB') ?
    'AES-OCB' :
    'AES-GCM';
const passwordKey = await crypto.subtle.importKey(
  derivationAlg === 'Argon2id' ? 'raw-secret' : 'raw',
  new TextEncoder().encode(password),
  derivationAlg,
  false,
  ['deriveKey'],
);
const nonce = crypto.getRandomValues(new Uint8Array(16));
const derivationParams =
  derivationAlg === 'Argon2id' ?
    {
      nonce,
      parallelism: 4,
      memory: 2 ** 21,
      passes: 1,
    } :
    {
      salt: nonce,
      iterations: 100_000,
      hash: 'SHA-256',
    };
const key = await crypto.subtle.deriveKey(
  {
    name: derivationAlg,
    ...derivationParams,
  },
  passwordKey,
  {
    name: encryptionAlg,
    length: 256,
  },
  false,
  ['encrypt', 'decrypt'],
);
const plaintext = 'Hello, world!';
const iv = crypto.getRandomValues(new Uint8Array(16));
const encrypted = await crypto.subtle.encrypt(
  { name: encryptionAlg, iv },
  key,
  new TextEncoder().encode(plaintext),
);
const decrypted = new TextDecoder().decode(await crypto.subtle.decrypt(
  { name: encryptionAlg, iv },
  key,
  encrypted,
));

an exception is thrown:

node:internal/crypto/webidl:486
                throw lazyDOMException(
                      ^

DOMException [OperationError]: AES-OCB algorithm.iv must be no more than 15 bytes
    at Object.validator (node:internal/crypto/webidl:486:23)
    at Object.AeadParams (node:internal/webidl:747:29)
    at normalizeAlgorithm (node:internal/crypto/util:594:61)
    at SubtleCrypto.encryptImpl (node:internal/crypto/webcrypto:1387:31)
    at callSubtleCryptoMethod (node:internal/crypto/webcrypto:95:20)
    at SubtleCrypto.encrypt (node:internal/crypto/webcrypto:1365:10)
    at file:///home/username/AES-OCB.mjs:48:39

Node.js v26.3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    docIssues and PRs related to the documentations.webcrypto

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions