openssl: Sign a file and verify it.


openssl can be used to create signature of a file and check the file against the signature to prevent unauthorized changes.

You need an private key with its associated public key. If you havn’t one create a key

michael@debdev ~ # openssl genrsa -aes256 -passout pass:mySecret -out my.key 2048

Or get an prompt for the password

michael@debdev ~ # openssl genrsa -aes256 -out my.key 2048

Create the associated public key (PKCS#8) from the private key

michael@debdev ~ # openssl rsa -in my.key -passin pass:mySecret -pubout -out my.pem

or in PKCS#1 format (Only rsa keys)

michael@debdev ~ # oopenssl rsa -in my.key -passin pass:mySecret -RSAPublicKey_out -out my_rsa.pem

If you want to use the pubkey in C# Applications by RSACryptoServiceProvider -> ImportCspBlob the output format must “MS PRIVATEKEYBLOB”

michael@debdev ~ # openssl rsa -in my.key -passin pass:mySecret -RSAPublicKey_out -outform "MS PRIVATEKEYBLOB" -out my_rsa.pem

Let’s sign a file. For example ImportendData.txt.

michael@debdev ~ # cat Very importend data!!! > ImportendData.txt
michael@debdev ~ # openssl dgst -sha256 -sign my.key -out ImportendData.txt.sign ImportendData.txt

This creates signature of ImportendData.txt signed by the private my.key
For simple exchange/transport the signature file can exported as Base64 sequence

michael@debdev ~ # openssl base64 -in ImportendData.txt.sign -out ImportendData.txt.sign.base64

Or print base64 signature to console

michael@debdev ~ # openssl base64 -in ImportendData.txt.sign 

To convert it back to ImportendData.txt.sign use

michael@debdev ~ # openssl base64 -d -in ImportendData.txt.sign.base64 -out ImportendData.txt.sign

To verify the ImportendData.txt integrity use the public key and the signature file.

michael@debdev ~ # openssl dgst -sha256 -verify my.pem -signature ImportendData.txt.sign ImportendData.txt
Verified OK

Here is a C# code snipped to verify a file.


Advertisment to support

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.