rfl890
rfl890

Reputation: 102

SubtleCrypto: "InvalidAccessError: The key is not of the expected type" when trying to export CryptoKeyPair.publicKey

I'm trying to create a web application to generate RSA public/private key pairs and I'm testing my code.

(async function() {
    const subtle = crypto.subtle;
    const keyConfig = {
        name: "RSA-OAEP",
        modulusLength: 2048,
        publicExponent: new Uint8Array([1,0,1]),
        hash: "SHA-256"
    }
    const key = await subtle.generateKey(keyConfig, true, ["encrypt", "decrypt"]);
    const public = key.publicKey;
    const private = key.privateKey;

    const exported_public = subtle.exportKey("pkcs8", public)
        .then(arr => {
            alert(arr) // I know it's an ArrayBuffer
        })
        .catch(err => {
            alert(err)
        });
})();

In this case the .catch statement is alerting the error "InvalidAccessError: The key is not of the expected type". I did a quick google search and nothing came up. How do I fix this?

Upvotes: 2

Views: 1119

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 93988

You cannot export public keys as "pkcs8", because PKCS#8 - the " Private-Key Information Syntax Specification" is used for plaintext or - sometimes - encrypted private keys.

For public keys you'd use "spki", which is short for SubjectPublicKeyInfo as defined in the X509v3 certificate specifications. It is a structure similar to (unencrypted) PKCS#8. Both contain the key type (using an OID) and the key value.

Note that some libraries may mistakenly allow you to perform "PKCS#8" encoding / decoding for public keys. In that case they will probably convert to/from the SubjectPublicKeyInfo structure, so "spki" is probably still the format you want.

Upvotes: 2

Related Questions