OpenSSL RSA sign and verify howto

来源:互联网 发布:java loader.getparent 编辑:程序博客网 时间:2024/06/05 15:33

http://www.codealias.info/technotes/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

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 (seeSigning 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.txtopenssl 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.


0 0