2

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.

Philipp Claßen
  • 41,306
  • 31
  • 146
  • 239
Kamil
  • 72
  • 1
  • 9

1 Answers1

5

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.

pedrofb
  • 37,271
  • 5
  • 94
  • 142
  • It helped with public key, but it failed while i was importing private key ;( I've used `spki` and `convertPemToBinary(pemKey)` and it threw a `Cannot create a key using the specified key usages.` message. – Kamil Jan 30 '18 at 14:38
  • 1
    `spk`i is not suitable for private keys. Use `pkcs8`, convert the key from PEM to pkcs8, and change 'encrypt' to 'decrypt'. I will look for a link to do the conversion – pedrofb Jan 30 '18 at 14:58
  • OK, so I generated new pkcs8 priv and public keys and imported them with correct args and... it works! Wow! Thank you for help! – Kamil Jan 30 '18 at 15:30