xx

# OpenSSL RSA sign and verify howto

Openssl provides an easy way for signing data using the RSA algorithm. RSA signing provides a robust way to ensure the integrity and authenticity of data.

## About OpenSSL

## The RSA signing algorithm

Rather than signing the whole data, we will create a one-way hash of the data using a hash algorithm (e.g SHA256), sign the hash (generates the actual signature), then send the data along with the the signature.

The receiving end will compute the hash on the data (using the same hash algorithm), then verify the signature using the public key (see Signing messages with RSA)

The following are the detailed steps for signing and verifying a data using the RSA algorithm.

## Signing data with the RSA algorithm

### Step1. Create private/public keypair (optional)

openssl genrsa -out private.pem 1024

This creates a key file called private.pem. This file actually have both the private and public keys, so you should extract the public one from this file:

openssl rsa -in private.pem -out public.pem -outform PEM -pubout

You'll now have public.pem containing just your public key, you can freely share this with 3rd parties.

### Step2. Create a hash of the data

echo 'data to sign' > data.txt openssl dgst -sha256 < data.txt > hash

### Step3. Sign the hash using the private key

openssl rsautl -sign -inkey private.pem -keyform PEM -in hash > signature

The file 'signature' and the actual data 'data.txt' can now be communicated to the receiving end. The hash algorithm (in our case SHA256) as well as the public key must also be known to the receiving end.

## Authenticate data using the public key

### Step4. Create a hash of the data (same as Step 2)

### Step5. Verify the signature

openssl rsautl -verify -inkey public.pem -keyform PEM -pubin -in signature > verified

diff -s verified hash

If the result of the above command 'verified' matches the hash generated in Step 3.1 (in which case you the result of the diff command would be 'Files verified and hash are identical') then the signature is considered authentic and the integrity/authenticity of the data is proven.

## Related articles

**PKI SSL certificate management with OpenSSL**

Labels: security, unix |

~~DISCUSSION~~