How to sign and verify a file using OpenSSL

Detached file signatures let someone prove a file came from the holder of a private key without encrypting the file itself. OpenSSL can create that signature beside the file and later verify it with the matching public key, which fits release artifacts, checksums, and handoff files that should remain readable.

An RSA signing key with openssl dgst -sha256 works with ordinary files and produces a detached signature that can travel with the artifact. The private key signs the file, and the public key verifies the signature without exposing the private key.

Keep the private key restricted and distribute only the public key to verifiers. Verification succeeds only when the signature, public key, and file bytes match; even a small content change causes OpenSSL to return a verification failure.

Steps to sign and verify a file with OpenSSL:

  1. Create a small file to sign.
    $ printf 'Release notes for version 1.0\n' > release-notes.txt
  2. Generate a private RSA key for signing.
    $ openssl genpkey -quiet -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out release-signing.key

    Keep release-signing.key private. Anyone who can read the private key can create signatures that verify against the matching public key.

  3. Extract the public verification key.
    $ openssl pkey -in release-signing.key -pubout -out release-signing.pub

    Share release-signing.pub with verifiers. Do not send the private key with the signed file.

  4. Sign the file and write the detached signature.
    $ openssl dgst -sha256 -sign release-signing.key -out release-notes.sig release-notes.txt

    The signature file is binary data. Keep it unchanged and send it beside the file it signs.

  5. Verify the signature against the original file.
    $ openssl dgst -sha256 -verify release-signing.pub -signature release-notes.sig release-notes.txt
    Verified OK
  6. Create a changed copy of the signed content.
    $ printf 'Release notes for version 1.0\nInjected change\n' > release-notes-tampered.txt
  7. Confirm that the same signature fails against the changed file.
    $ openssl dgst -sha256 -verify release-signing.pub -signature release-notes.sig release-notes-tampered.txt
    Verification failure

    OpenSSL exits with a nonzero status when verification fails, so scripts can stop a release or handoff when the file bytes no longer match the signature.

  8. Remove the sample files when testing is finished.
    $ rm release-notes.txt release-notes-tampered.txt release-notes.sig release-signing.key release-signing.pub

    Do not delete a real signing key unless the key has been retired and backed up according to the signing policy.