Use the openssl dgst command and utility to output the hash of a given file. The output will be in hexadecimal, and the default hash function is sha256, although this can be overridden. md5 and sha1 are both common digest functions that are still routinely found in practice and can be specified in the command if need be.
The openssl dgst command and utility can also be used to generate and verify digital signatures. Read further for openssl dgst examples.
Computing hash values with openssl dgst
To create the message digest or hash of a given file, run the following command:
openssl dgst example.txt
Where example.txt
is the given file to be hashed. The default hashing algorithm in this case is sha256. Again, with openssl dgst sha256 is the default.
To use openssl to compute the fingerprint of a certificate, things are a bit different. The fingerprint of an X.509 certificate is derived from the certificate in binary form, so running openssl dgst on the pem formatted certificate will not give you the intended value.
To compute the fingerprint of a pem formatted or encoded certificate, run the following command:
openssl x509 -in cert.pem -outform der | openssl dgst
Note that we are piping the output from the pem to der conversion into the openssl dgst command. Pretty cool, right?
Signing a file with openssl dgst
To sign a file and output in binary format with the openssl dgst utility, run the following command:
openssl dgst -sha256 -sign key.pem -out example.txt.sign example.txt
Where -sha256
is the signature algorithm, -sign key.pem
means to sign with the given private key, and -out example.txt.sign example.txt
is the signature file followed by the file to be signed.
To recap this example, use openssl to sign a file with the dgst command and by default, sha256 is the signature algorithm.
Verify a signature with openssl dgst
To verify a signature with the openssl dgst utility, run the following command:
openssl dgst -sha256 -verify pubkey.pem -signature example.sign example.txt
Where -sha256
is the signature algorithm, -verify pubkey.pem
means to verify the signature with the given public key, example.sign
is the signature file, and example.txt
is the file that was signed.
A successful signature verification will show Verified OK
.
This will also work with digitally signing PDFs and then verifying the digital signature on the PDF. To clarify, the digital signature is in the .sign
file, and not embedded in the file that was signed, so both files are necessary to sign and verify with openssl.
For an additional utility that supports PDF signatures on Linux, check out the pdfsig utility.
If you would like to see more examples of using this utility, please leave a comment or suggestion below.
Leave a Reply