Search code examples
javascriptopensslrsawebcrypto-api

Web Crypto API cannot import openssl keys


Right now, I am testing Web Crypto API by doing simple test. So, I have user's public key (as a string) and I want to let him pass his private key (also as a string), so my app could do some encrypting/decrypting. And so, I try to import his keys int Web Crypto API by doing:

var textEncoder = new TextEncoder();
var alg = {
    name: "RSA-OAEP",
    hash: {name: "SHA-256"}
}
window.crypto.subtle.importKey('raw', textEncoder.encode(myPublicKey), alg, false, ['encrypt'])

Keys are generateded by

openssl genrsa -out mykey.pem 4096
openssl rsa -in mykey.pem -pubout > mykey.pub

WCAPI throws

Unsupported import key format for algorithm

I tried other hashes in alg, but still, no success.

A help with an example would be nice.


Solution

  • You have some errors:

    • Change raw to spki (pointed by James K Polk)

    • TextEncoder.encode() is not suitable for binary keys. See TextEncoder

      Returns a Uint8Array containing utf-8 encoded text.

    • Convert the PEM key generated by OpenSSL to binary ArrayBuffer. Use convertPemToBinary(pemKey) from here https://stackoverflow.com/a/34995761/6371459.