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.
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.
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.
echo 'data to sign' > data.txt openssl dgst -sha256 < data.txt > hash
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.
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.