Skip to content

Instantly share code, notes, and snippets.

@kepocnhh
Last active May 1, 2023 14:54
Show Gist options
  • Save kepocnhh/de0e0179e343c2d620d72874744d5c9a to your computer and use it in GitHub Desktop.
Save kepocnhh/de0e0179e343c2d620d72874744d5c9a to your computer and use it in GitHub Desktop.
Rewrite encrypted.
#!/usr/local/bin/bash
if test $# -ne 2; then
echo "Script needs 2 arguments: ENCRYPTED, KEY. But actual is $#!"; exit 1; fi
ENCRYPTED="$1"
KEY="$2"
for it in ENCRYPTED KEY; do
if test -z "${!it}"; then echo "Argument \"$it\" is empty!"; exit 1; fi; done
if [[ ! -f "$ENCRYPTED" ]]; then echo "File \"$ENCRYPTED\" does not exist!"; exit 1
elif [[ ! -s "$ENCRYPTED" ]]; then echo "File \"$ENCRYPTED\" is empty!"; exit 1; fi
echo "Enter password:"
read -rs PASSWORD
DECRYPTED="$(gpg --batch -qd --passphrase "$PASSWORD" "$ENCRYPTED")"
if test $? -ne 0; then echo "Decrypt \"$ENCRYPTED\" error!"; exit 1
elif test -z "$DECRYPTED"; then echo "Decrypted is empty!"; exit 1; fi
echo "Enter value:"
read -rs VALUE
VALUE="${VALUE//\"/\\\"}"
if test -z "$VALUE"; then echo "Value is empty!"; exit 1; fi
RESULT="$(echo "$DECRYPTED" | yq -rMe -o=json "${KEY}=\"${VALUE}\"")"
if test $? -ne 0; then echo "Parse decrypted error!"; exit 1
elif test -z "$RESULT"; then echo "Result is empty!"; exit 1; fi
cp "$ENCRYPTED" "/tmp/backup_$(date +%s).pgp"
echo "$RESULT" | gpg --batch --yes -qc \
--cipher-algo='AES-256' \
--digest-algo='SHA512' \
--passphrase "$PASSWORD" -o "$ENCRYPTED"
if test $? -ne 0; then
echo "Encrypt error!"; exit 1; fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment