Home > database >  SubtleCrypto: "InvalidAccessError: The key is not of the expected type" when trying to exp
SubtleCrypto: "InvalidAccessError: The key is not of the expected type" when trying to exp

Time:04-12

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?

CodePudding user response:

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 of course the key value.

Note that some libraries may mistakenly allow you to perform this kind of encoding / decoding. Probably they will still convert to / from SubjectPublicKeyInfo, so "spki" is probably still the format you want.

  • Related