I need to encrypt some data using RSA in JavaScript. All of the libraries around ask for an exponent and a modulus, yet I get a single public.key file from my opponent.
How do you retrieve the public exponent and modulus part from an RSA file?
It depends on the tools you can use. I doubt there is a JavaScript too that could do it directly within the browser. It also depends if it’s a one-off (always the same key) or whether you need to script it.
Command-line / OpenSSL
If you want to use something like OpenSSL on a unix command line, you can do something as follows.
I’m assuming you public.key file contains something like this:
Then, the commands would be:
Then, you can look into the ASN.1 structure:
This should give you something like this:
The modulus and public exponent are in the last BIT STRING, offset 19, so use
-strparse:This will give you the modulus and the public exponent, in hexadecimal (the two INTEGERs):
That’s probably fine if it’s always the same key, but this is probably not very convenient to put in a script.
Alternatively (and this might be easier to put into a script),
will return this:
Java
It depends on the input format. If it’s an X.509 certificate in a keystore, use
(RSAPublicKey)cert.getPublicKey(): this object has two getters for the modulus and the exponent.If it’s in the format as above, you might want to use BouncyCastle and its
PEMReaderto read it. I haven’t tried the following code, but this would look more or less like this:(You can use BouncyCastle similarly in C# too.)