To access the RSA Public Key requires several items:
- The correct algorithm: RSA-OAEP
- Exporting the public in the correct format ("jwk", or "spki")
Note: Your example code expects the JWK format. Typically, public keys are exported in SPKI format. See the second example.
JWK format for exporting a public key:
const params = {
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256"
}
const keyPair = await crypto.subtle.generateKey(
params,
true,
["encrypt", "decrypt"]);
const pubKey = await crypto.subtle.exportKey(
"jwk",
keyPair.publicKey);
fetch('/', {
method: 'POST',
body: JSON.stringify(pubKey),
headers: {
'Content-Type': 'application/json'
},
})
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
SPKI format for exporting a public key:
const params = {
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256"
}
const keyPair = await crypto.subtle.generateKey(
params,
true,
["encrypt", "decrypt"]);
const pubKey = await crypto.subtle.exportKey(
"spki",
keyPair.publicKey);
const b64 = btoa(ab2str(pubKey));
var pem = `-----BEGIN PUBLIC KEY-----\n${b64}\n-----END PUBLIC KEY-----`;
key = {
"public_key": pem
}
fetch('/', {
method: 'POST',
body: JSON.stringify(key),
headers: {
'Content-Type': 'application/json'
},
})