Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple file/stream encryption using OpenSSL
#!/usr/bin/env bash
set -e
[ -n "$KEY_DIR" ] || KEY_DIR="$HOME/.keys"
read -r -a line
if [ "${line[0]}" = "key:" ] && [ -n "${line[1]}" ]; then
KEY_NAME="${line[1]}"
else
echo "decrypt: invalid input" >&2
exit 1
fi
KEY_FILE="${KEY_DIR%/}/$KEY_NAME"
[ -f "$KEY_FILE" ] || {
echo "decrypt: key file not found: $KEY_FILE" >&2
exit 2
}
openssl aes-256-cbc -d -a -pass file:"$KEY_FILE"
#!/usr/bin/env bash
set -e
[ -n "$KEY_DIR" ] || KEY_DIR="$HOME/.keys"
KEY_NAME="$1"
[ -n "$KEY_NAME" ] || {
echo "usage: encrypt <key-name>" >&2
exit 1
}
KEY_FILE="${KEY_DIR%/}/$KEY_NAME"
[ -f "$KEY_FILE" ] || {
echo "encrypt: key file not found: $KEY_FILE" >&2
exit 2
}
echo "key: $KEY_NAME"
openssl aes-256-cbc -a -salt -pass file:"$KEY_FILE"
#!/usr/bin/env bash
set -e
[ -n "$KEY_DIR" ] || KEY_DIR="$HOME/.keys"
mkdir -p "$KEY_DIR"
KEY_NAME="$1"
[ -n "$KEY_NAME" ] || {
echo "usage: mkkey <key-name>" >&2
exit 1
}
KEY_FILE="${KEY_DIR%/}/$KEY_NAME"
[ ! -f "$KEY_FILE" ] || {
echo "mkkey: file exists: $KEY_FILE" >&2
exit 2
}
openssl rand 512 > "$KEY_FILE"

Simple file/stream encryption using OpenSSL

Create and store a 512-byte random encryption key named secret:

$ mkkey secret

Encrypt the contents of file with the secret key and write it to file.enc:

$ encrypt secret < file > file.enc

Decrypt the contents of file.enc to standard output:

$ decrypt < file.enc

Keys are stored in ~/.keys by default. Set the KEY_DIR environment variable to specify a different location.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment