Henry Story
Henry Story

Reputation: 2156

Is there a way to get the components of an RSA key in the WebCrypto API?

I can create a rsa key like this using the WebCrypto API ( see the really useful set of examples here https://vibornoff.github.io/webcrypto-examples/index.html )

 window.crypto.subtle.generateKey({
         name: "RSASSA-PKCS1-v1_5",
         modulusLength: 2048,
         publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
         hash: {name: "SHA-256"},
        }, 
    true, 
  ["sign", "verify"])

How can I actually find the modulus of the generated public key?

Upvotes: 2

Views: 1048

Answers (1)

dlongley
dlongley

Reputation: 2096

The following code should give you the modulus and exponent as Uint8Arrays:

window.crypto.subtle.generateKey({
  name: "RSASSA-PKCS1-v1_5",
  modulusLength: 2048,
  publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
  hash: {
    name: "SHA-256"
  },
}, true, ["sign", "verify"]).then(function(keyPair) {
  window.crypto.subtle.exportKey("jwk", keyPair.publicKey).then(
    function(key) {
      // base64url-decode modulus
      var modulus = base64UrlDecode(key.n);

      // base64url-decode exponent
      var exponent = base64UrlDecode(key.e);

      // modulus and exponent are now Uint8Arrays
    });
});

function base64UrlDecode(str) {
  str = atob(str.replace(/-/g, '+').replace(/_/g, '/'));
  var buffer = new Uint8Array(str.length);
  for(var i = 0; i < str.length; ++i) {
    buffer[i] = str.charCodeAt(i);
  }
  return buffer;
}

Upvotes: 4

Related Questions