Flags:
-f [path]: specify the password file to use.
-h: this help message.
+-p: the input file is plaintext, and we should encrypt it.
-s [pattern]: search for the given pattern
Environment variables:
trap "rm -rf ${TEMPDIR}; exit" EXIT
#chmod 007 "${TEMPDIR}" || die "failed to chmod ${TEMPDIR}"
+encrypt_new_file() {
+ echo
+ encrypt_file "${TEMPFILE}" "${PASSWORD_PATH}"
+ [[ $? -ne 0 ]] && die "Failed to encrypt ${PASSWORD_PATH}"
+ mv -f "${TEMPFILE}" "${PASSWORD_PATH}" || \
+ die "Failed to replace ${PASSWORD_PATH}"
+ exit 0
+}
+
+search_existing_file() {
+ echo
+ decrypt_file "${TEMPFILE}" "${PASSWORD_PATH}"
+ [[ $? -ne 0 ]] && \
+ die "Failed to decrypt ${PASSWORD_PATH}. Was the password correct?"
+ egrep ${SEARCH_PATTERN} "${TEMPFILE}"
+}
+
+edit_existing_file() {
+ echo
+ decrypt_file "${TEMPFILE}" "${PASSWORD_PATH}"
+ [[ $? -ne 0 ]] && \
+ die "Failed to decrypt ${PASSWORD_PATH}. Was the password correct?"
+ ${EDITOR} "${TEMPFILE}"
+ encrypt_file "${PASSWORD_PATH}" "${TEMPFILE}"
+ [[ $? -ne 0 ]] && \
+ die "failed to move ${TEMPFILE_ENC} to ${PASSWORD_PATH}: changes lost."
+ exit 0
+}
+
+encrypt_file() {
+ dest="${1}"
+ src="${2}"
+ openssl enc -aes-256-ecb -k "${PASSWORD}" -salt < "${src}" > "${dest}"
+}
+
+decrypt_file() {
+ dest="${1}"
+ src="${2}"
+ openssl enc -d -aes-256-ecb -k "${PASSWORD}" < "${src}" > "${dest}"
+}
+
SEARCH_PATTERN=""
-while getopts "f:hs:" flag; do
+PLAINTEXT=0
+while getopts "f:hps:" flag; do
case $flag in
f) PASSWORD_PATH="${OPTARG}";;
h) usage; exit 0;;
+ p) PLAINTEXT=1;;
s) SEARCH_PATTERN="${OPTARG}";;
*) echo; usage; exit 1;;
esac
if [[ -z ${PASSWORD} ]]; then
read -s -p "enter password: " PASSWORD
fi
-if openssl enc -d -aes-256-ecb -k "${PASSWORD}" \
- < "${PASSWORD_PATH}" > "${TEMPFILE}"; then
- if [[ -z ${SEARCH_PATTERN} ]]; then
- ${EDITOR} "${TEMPFILE}"
- openssl enc -aes-256-ecb -k "${PASSWORD}" -salt \
- < "${TEMPFILE}" > "${TEMPFILE_ENC}" ||
- die "Re-encryption failed. Changes lost."
- mv -f "${TEMPFILE_ENC}" "${PASSWORD_PATH}" || \
- die "failed to move ${TEMPFILE_ENC} to ${PASSWORD_PATH}: changes lost."
- else
- echo
- egrep ${SEARCH_PATTERN} "${TEMPFILE}"
+if [[ ${PLAINTEXT} -eq 1 ]]; then
+ if [[ ${SEARCH_PATTERN} != "" ]]; then
+ die "You may not specify both -s and -p."
fi
+ encrypt_new_file
+elif [[ ${SEARCH_PATTERN} != "" ]]; then
+ search_existing_file
else
- die "Failed to decrypt ${PASSWORD_PATH}. Was the password correct?"
+ edit_existing_file
fi
+