Skip to content

Instantly share code, notes, and snippets.

@ppanyukov
Last active September 14, 2021 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ppanyukov/a803c0d417869f93311c541b1ed1233c to your computer and use it in GitHub Desktop.
Save ppanyukov/a803c0d417869f93311c541b1ed1233c to your computer and use it in GitHub Desktop.
Noddy script to encrypt/decrypt files using openssl private (ssh) key.
#!/usr/bin/env bash
set -eu
# Noddy script to encrypt/decrypt files using openssl private (ssh) key.
# Works with files and stdin.
# Results are stdout.
#
# Requirements:
# - openssl
# - ssh private key: ~/.ssh/id_rsa
# - certificate generated from private key: ~/.ssh/certificate.pem
#
# To generate private key:
# - ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
#
# To generate certificate:
# - openssl req -x509 -new -days 100000 -key ~/.ssh/id_rsa -out ~/.ssh/certificate.pem
#
# More info:
# - https://gist.github.com/dreikanter/c7e85598664901afae03fedff308736b
# - https://help.github.com/en/enterprise/2.15/user/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
#
declare key_private=~/.ssh/id_rsa
declare key_cert=~/.ssh/certificate.pem
function name {
echo $(basename ${BASH_SOURCE})
}
function log {
echo "$@" 1>&2
}
function usage {
log "Usage:"
log " encrypt: $(name) -e file"
log " decrypt: $(name) -d file"
log ""
log "If file is - then will assume stdin"
log ""
log "Requirements:"
log " - openssl"
log " - private key ${key_private} (for decrypt)"
log " - certificate ${key_private} (for encrypt)"
}
function encrypt {
file=${1:=""}
if test "" == "${file}" || test "-" == "${file}"
then
log "Using file: stdin"
(
set -x
openssl smime \
-encrypt \
-aes-256-cbc \
-outform DER \
"${key_cert}"
)
else
log "Using file: ${file}"
(
set -x
openssl smime \
-encrypt \
-aes-256-cbc \
-outform DER \
-in "${file}" \
"${key_cert}"
)
fi
}
function decrypt {
file=${1:=""}
if test "" == "${file}" || test "-" == "${file}"
then
log "Using file: stdin"
(
set -x
openssl smime \
-decrypt \
-inform DER \
-inkey "${key_private}"
)
else
log "Using file: ${file}"
(
set -x
openssl smime \
-decrypt \
-inform DER \
-inkey "${key_private}" \
-in "${file}"
)
fi
}
while getopts ":e:d:" arg; do
case "${arg}" in
e)
declare file=${OPTARG}
encrypt "${file}"
exit
;;
d)
declare file=${OPTARG}
decrypt "${file}"
exit
;;
esac
done
shift $((OPTIND-1))
log "ERROR: unknown command"
usage
exit -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment