WiseWins
WiseWins

Reputation: 69

RSA private key from modulus and private exponent in JavaScript

I have a modulus and private exponent. How can I generate an RSA private Key in JavaScript from that?

Or if these values are not enough to generate a RSA private Key. What are the other values that I might possibly need.

RSAPrivateKeySpec in Java 7 is able to generate RSA private key with mod and private Exp. I'm looking for a equivalent in JavaScript.

I also tried npm ursa module which unfortunately didn't work out.

Upvotes: 1

Views: 2222

Answers (2)

Stuart P. Bentley
Stuart P. Bentley

Reputation: 10675

The modulus and private exponent are, technically, enough to generate an RSA private key, abstractly; they're only insufficient to generate an RSA private key with its inputs, as used to optimize decryption using the Chinese remainder theorem. (As Artjom B.'s answer notes, some implementations are able to perform this non-optimized decryption; however, some are not.)

To create a full RSA private key, with its inputs as used for optimization, you need the original primes p and q. There's no simple, deterministic way to obtain these from the modulus and private exponent, but methods exist to search for them in a space small enough to be tractable. See the answers to this question: Calculate primes p and q from private exponent (d), public exponent (e) and the modulus (n)

Upvotes: 1

Artjom B.
Artjom B.

Reputation: 61892

JSBN is able to create an RSA private key which can decrypt.

var sk = new RSAKey();
sk.setPrivate("<modulus hex>", "<public exponent hex>", "<private exponent hex>");
var plaintext = sk.decrypt("<ciphertext hex>");

The public exponent is not used during decryption, so you can simply pass some garbage hex into it, but it's either "03" (3), "11" (17) or "010001" (65537).

You'd need to include jsbn.js, jsbn2.js, rsa.js, and rsa2.js. Keep in mind that decryption will be 4 times slower than with a full RSA key, because the Chinese Remainder Theorem cannot be used.

Upvotes: 2

Related Questions