Generating an RSA keypair in JavaScript

encryption, javascript, security

Solution

The question has been asked almost 10 years ago and since then lot of things has improved. Currently, most of the modern browsers feature Web Crypto API that provides the capability to generate strong random numbers and therefore allows a script to generate cryptographic keys, sign data, verify signatures, encrypt and decrypt data and other cryptographic operations.

Here is a sample code from the MDN mentioned above:

let keyPair = window.crypto.subtle.generateKey(
  {
    name: "RSA-OAEP",
    modulusLength: 4096,
    publicExponent: new Uint8Array([1, 0, 1]),
    hash: "SHA-256"
  },
  true,
  ["encrypt", "decrypt"]
);

Problem

I recently found this RSA JavaScript library: http://www.ohdave.com/rsa/. However, it requires that the key be pre-generated. Here are my questions/issues: I'd like to generate an RSA keypair in the JavaScript (so that I don't have to change the code every time I want a new keypair.) While I understand how this can be used to send secure data, if I'm not mistaken this library cannot be used for the client to receive secure data from the server (because the public and private exponents, and the modulus, are transmitted plain-text from the server). Am I mistaken? I'd love some discussion about this. I'm no security expert, but I have a pretty firm grasp on asymmetric encryption.

Original source