Jonah
Jonah

Reputation: 10091

WebCrypto:DataError when attempting to unwrapKey

I want to use one public key to wrap another public key. Almost everything works right up until the unwrapKey step. It throws an opaque DataError with no further information about what is wrong. What could the issue be here?

const {privateKey: unwrappingKey, publicKey: wrappingKey} =
  await window.crypto.subtle.generateKey(
    {name: 'RSA-OAEP', modulusLength: 2000, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256'},
    true, ['decrypt', 'wrapKey', 'unwrapKey']);

const {privateKey, publicKey} = await window.crypto.subtle.generateKey(
  {name: 'RSA-OAEP', modulusLength: 512, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256'},
  true, ['encrypt', 'decrypt']);

const wrappedKey = await window.crypto.subtle.wrapKey(
  'jwk', publicKey, wrappingKey,
  {name: 'RSA-OAEP', modulusLength: 512, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256'});

// vvvv This line throws `DataError`
const unwrappedKey = await window.crypto.subtle.unwrapKey(
  'spki', wrappedKey, unwrappingKey, {name: 'RSA-OAEP'},
  {name: 'RSA-OAEP', hash: 'SHA-256'},
  true, ['encrypt']);
console.log(unwrappedKey);

Upvotes: 0

Views: 30

Answers (1)

Jonah
Jonah

Reputation: 10091

Found the issue in my case. The code wraps the key with jwk format but was trying to unwrap with spki. The format must match for it to work.

Upvotes: 0

Related Questions