emstol
emstol

Reputation: 6216

Creating a rsa public key from its modulus and exponent

I want to verify a RSA signature. I have data to verify, the signature and a public key in a form of modulus and exponent. I'd like to do the verification using openssl. Is it possible? I know I can use openssl rsautl -verify -in sig -inkey key.pem but I don't know how (using openssl) to create a public key having just it's modulus and exponent.

Maybe other ideas how to check this signature (except writing some programs)?

Upvotes: 15

Views: 16902

Answers (2)

oliv
oliv

Reputation: 13259

In order to generate a RSA public key in PEM format to be used with openssl, you can follow these steps.

Create an ASN1 definition file

Modify the following template to include your modulus and exponent

# Start with a SEQUENCE
asn1=SEQUENCE:pubkeyinfo

# pubkeyinfo contains an algorithm identifier and the public key wrapped
# in a BIT STRING
[pubkeyinfo]
algorithm=SEQUENCE:rsa_alg
pubkey=BITWRAP,SEQUENCE:rsapubkey

# algorithm ID for RSA is just an OID and a NULL
[rsa_alg]
algorithm=OID:rsaEncryption
parameter=NULL

# Actual public key: modulus and exponent
[rsapubkey]
n=INTEGER:0x%%MODULUS%%

e=INTEGER:0x%%EXPONENT%%

Instead of editing, you also may want to script this using sed

sed -i "s/%%MODULUS%%/$(xxd -ps -c 256 mymodulus.bin)/" def.asn1

Note the -c 256 should be chosen according to your key length in bytes.

You can use a similar command for the exponent.

Generate your RSA key

Use the following openssl command. This will give you a DER encoded RSA key.

openssl asn1parse -genconf def.asn1 -out pubkey.der -noout

Then convert it into a PEM key

openssl rsa -in pubkey.der -inform der -pubin -out pubkey.pem

Verify using your key

You can use either openssl dgst -verify or openssl rsautl -verify

Upvotes: 20

Dirk-Willem van Gulik
Dirk-Willem van Gulik

Reputation: 7706

Checking the man pages should give you below

 # generate private key
 openssl genrsa > key.priv

 # use it to sign something
 echo "Dirk should be given $10" | openssl rsautl -inkey key.priv -sign > msg.sig

 # create a pub key (modules, exp) from the private key
 openssl rsa -pubout < key.priv > key.pub

 # use that to verify the signature.
 openssl rsautl -in msg.sig -verify -inkey key.pub -pubin

all this assuming you want raw keys. If I understand your comment below right - it seems that you do not have modules/exp in a normal format. So you will first have to package it in ASN.1 in order to use it with the usual tools.

You'll have to write some c/java/etc code for this. An easy way to do this is to use the openssl library; and fill out the RSA * structure.

Upvotes: -5

Related Questions