Skip to content

Instantly share code, notes, and snippets.

@iconnor
Created May 31, 2023 23:39
Show Gist options
  • Save iconnor/a300a63639758eb7ef88294315fddc3d to your computer and use it in GitHub Desktop.
Save iconnor/a300a63639758eb7ef88294315fddc3d to your computer and use it in GitHub Desktop.
#!/bin/bash
# Function to sign a file
sign_file() {
# Check if file name and private key are provided
if [ $# -ne 2 ]
then
echo "Usage: $0 sign <file_to_sign> <private_key>"
exit 1
fi
# Convert the OpenSSH key to PEM format
ssh-keygen -p -m PEM -f $2
# Create a SHA256 hash of the file
openssl dgst -sha256 -binary $1 > hash
# Sign the hash with the private key and convert it to base64 format
openssl rsautl -sign -inkey $2 -keyform PEM -in hash | base64 > signature_base64
echo "The file has been signed. The base64-encoded signature is in the 'signature_base64' file."
}
# Function to verify a signature
verify_signature() {
# Check if file name, public key, and signature are provided
if [ $# -ne 3 ]
then
echo "Usage: $0 verify <file_to_check> <public_key> <signature_base64>"
exit 1
fi
# Create a SHA256 hash of the file
openssl dgst -sha256 -binary $1 > hash_check
# Decode the signature from base64 format and verify it using the public key
base64 -d $3 | openssl rsautl -verify -inkey $2 -pubin > hash_from_signature
# Compare the hashes
if cmp -s hash_check hash_from_signature
then
echo "The signature is valid."
else
echo "The signature is NOT valid."
fi
}
# Check if at least one argument is provided
if [ $# -lt 1 ]
then
echo "Usage: $0 <sign|verify> <arguments>"
exit 1
fi
# Call the appropriate function based on the first argument
if [ $1 = "sign" ]
then
sign_file "${@:2}"
elif [ $1 = "verify" ]
then
verify_signature "${@:2}"
else
echo "Invalid command. Usage: $0 <sign|verify> <arguments>"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment