09-11-2015 | Remy van Elst
This small guide will shows you how to use the OpenSSL Command Line to sign a file, and how to verify the signing of this file. You can do this to prove ownership of a key, or to prove that a file hasn't been modified since you signed it. This works both with small text files as well as huge photo's, documents or PDF files.
If you like this website and want to support it AND get $10 Digital Ocean credit (2 months free), use this link to order: https://www.digitalocean.com/?refcode=7435ae6b8212 (referral link).
We'll generate a new keypair for this. You can also use an exisiting one. Change the subject in the following command and execute it to generate a self signed keypair:
openssl req -nodes -x509 -sha256 -newkey rsa:4096 -keyout "$(whoami)s Sign Key.key" -out "$(whoami)s Sign Key.crt" -days 365 -subj "/C=NL/ST=Zuid Holland/L=Rotterdam/O=Sparkling Network/OU=IT Dept/CN=$(whoami)s Sign Key"
Also create a small text file to test the signing process on:
echo "Hello, World!" > sign.txt
Use the following command to sign the file. We actually take the sha256 hash of the file and sign that, all in one
openssl dgst -sha256 -sign "$(whoami)s Sign Key.key" -out sign.txt.sha256 sign.txt
This will result in a file
sign.txt with the contents, and the file
sign.txt.sha256 with the signed hash of this file.
You can place the file and the public key (
$(whoami)s Sign Key.crt) on the internet or anywhere you like. Keep the private key (
$(whoami)s Sign Key.key) very safe and private.
To verify the signature, you need the specific certificate's public key. We can get that from the certificate using the following command:
openssl x509 -in "$(whoami)s Sign Key.crt"
But that is quite a burden and we have a shell that can automate this away for us. The below command validates the file using the hashed signature:
openssl dgst -sha256 -verify <(openssl x509 -in "$(whoami)s Sign Key.crt" -pubkey -noout) -signature sign.txt.sha256 sign.txt
If the contents have not changed since the signing was done, the output is like below:
If the validation failed, that means the file hash doesn't correspond to the signed hash. The file has very likely been modified or tampered. The result of a failed validation looks like below:
To get a text version of the signature (the file contains binary content) you can use the
base64 command. The textual version is easier to public online with the file:
base64 sign.txt.sha256 > sign.txt.sha256.txt
To get this back into
openssl parsable output, use the
base64 -d command:
base64 -d sign.txt.sha256.txt > sign.txt.sha256