Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add the ability to directly encrypt a specified FILE into OUTPUT in the current directory #299

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions pkgs/agenix.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ function show_help () {
echo '-h, --help show help'
# shellcheck disable=SC2016
echo '-e, --edit FILE edits FILE using $EDITOR'
echo '-f, --encrypt FILE OUTPUT encrypts a given FILE to OUTPUT'
echo '-r, --rekey re-encrypts all secrets with specified recipients'
echo '-d, --decrypt FILE decrypts FILE to STDOUT'
echo '-i, --identity identity to use when decrypting'
Expand Down Expand Up @@ -47,6 +48,7 @@ test $# -eq 0 && (show_help && exit 1)

REKEY=0
DECRYPT_ONLY=0
ENCRYPT_FILE=0
DEFAULT_DECRYPT=(--decrypt)

while test $# -gt 0; do
Expand All @@ -65,6 +67,24 @@ while test $# -gt 0; do
fi
shift
;;
-f|--encrypt)
shift
ENCRYPT_FILE=1
if test $# -gt 0; then
export FILE=$1
else
echo "no FILE specified"
exit 1
fi
shift
if test $# -gt 0; then
export OUTPUT=$1
else
echo "no OUTPUT specified"
exit 1
fi
shift
;;
-i|--identity)
shift
if test $# -gt 0; then
Expand Down Expand Up @@ -188,6 +208,29 @@ function edit {
mv -f "$REENCRYPTED_FILE" "$FILE"
}

function encrypt {
FILE=$1
OUTPUT=$2
KEYS=$(keys "$OUTPUT") || exit 1

if [ ! -f "$FILE" ]
then
warn "$FILE does not exist."
return
fi

ENCRYPT=()
while IFS= read -r key
do
if [ -n "$key" ]; then
ENCRYPT+=(--recipient "$key")
fi
done <<< "$KEYS"

ENCRYPT+=(-o "$OUTPUT")
@ageBin@ "${ENCRYPT[@]}" <"$FILE" || exit 1
}

function rekey {
FILES=$( (@nixInstantiate@ --json --eval -E "(let rules = import $RULES; in builtins.attrNames rules)" | @jqBin@ -r .[]) || exit 1)

Expand All @@ -201,4 +244,5 @@ function rekey {

[ $REKEY -eq 1 ] && rekey && exit 0
[ $DECRYPT_ONLY -eq 1 ] && DEFAULT_DECRYPT+=("-o" "-") && decrypt "${FILE}" "$(keys "$FILE")" && exit 0
[ $ENCRYPT_FILE -eq 1 ] && encrypt "$FILE" "$OUTPUT" && exit 0
edit "$FILE" && cleanup && exit 0
Loading