javascriptencryptionrsajsbn

Could JSBN/Forge be used to generate RSA private/public key pair?


Looking at JSBN, RSAGenerate(B,E) takes the bit length B and the public key E as arguments. Does that mean it the public key can only be generated separately and be provided as an argument? Does that also mean Forge can't generate the key pair like BigInt http://www.leemon.com/crypto/BigInt.html?

Thanks


Solution

  • RSAGenerate doesn't take a public key, but a public key exponent in hex. Note that you have to choose this carefully because it has to be coprime to φ(n). A good value is 10001 (in hex) for compatibility with other implementations.

    The public key can be created from the private key by setting n and e:

    var pubkey = new RSAKey();
    pubkey.n = privKey.n;
    pubkey.e = privKey.e;
    

    The forge docs contain three different examples how an RSA key pairs are generated with the same public exponent as above:

    // generate an RSA key pair synchronously
    var keypair = rsa.generateKeyPair({bits: 2048, e: 0x10001});
    
    // generate an RSA key pair asynchronously (uses web workers if available)
    // use workers: -1 to run a fast core estimator to optimize # of workers
    rsa.generateKeyPair({bits: 2048, workers: 2}, function(err, keypair) {
      // keypair.privateKey, keypair.publicKey
    });
    
    // generate an RSA key pair in steps that attempt to run for a specified period
    // of time on the main JS thread
    var state = rsa.createKeyPairGenerationState(2048, 0x10001);
    var step = function() {
      // run for 100 ms
      if(!rsa.stepKeyPairGenerationState(state, 100)) {
        setTimeout(step, 1);
      }
      else {
        // done, turn off progress indicator, use state.keys
      }
    };
    // turn on progress indicator, schedule generation to run
    setTimeout(step);