openssl_file_encryption/crypter.sh

87 lines
2.0 KiB
Bash
Raw Normal View History

2024-02-02 15:49:55 +01:00
#!/bin/bash
2024-02-02 16:02:44 +01:00
# Author: F. Bischof (info@meer-web.nl)
2024-02-21 11:56:53 +01:00
# URL: https://github.com/Meer-Web/openssl_file_encryption
2024-02-02 15:49:55 +01:00
# Check for input file
if [ -n "$2" ]
then
INPUT=$2
if [ ! -e "$INPUT" ];
then
echo "Input file does not exist!"
exit 2
fi
else
2024-02-21 11:29:21 +01:00
echo "Usage: ./crypter.sh -[e/d] [inputfile]";
2024-02-02 15:49:55 +01:00
exit 1
fi
2024-02-23 09:25:16 +01:00
# Check if algos are set
if [ ! -f ~/.crypter/.algos ]
2024-02-21 11:50:25 +01:00
then
mkdir -p ~/.crypter
2024-02-23 09:25:16 +01:00
echo "ALGOS=\"-des-ede3-cbc -pbkdf2\"" > ~/.crypter/.algos
2024-02-21 11:50:25 +01:00
fi
2024-02-23 09:25:16 +01:00
source ~/.crypter/.algos
2024-02-21 11:29:21 +01:00
2024-02-21 10:29:45 +01:00
# Check method
case "$1" in
"-e")
2024-02-21 11:29:21 +01:00
echo "Encrypting file ${INPUT}"
2024-02-23 09:25:16 +01:00
HASH=$(sha256sum $INPUT | awk '{ print $1 }')
OUTPUT="${INPUT}.${HASH}.crypto"
openssl enc $ALGOS -salt -in ${INPUT} -out ${OUTPUT}.temp
2024-02-02 15:49:55 +01:00
base64 ${OUTPUT}.temp > ${OUTPUT}
rm -f ${OUTPUT}.temp
2024-02-21 11:29:21 +01:00
if [ "`stat ${OUTPUT} | grep Size | awk '{ print $2}'`" != 0 ]
then
# OK - safe to delete the original input file
2024-02-21 11:45:50 +01:00
echo "OK - Deleting file ${INPUT}"
2024-02-21 11:29:21 +01:00
rm -f ${INPUT}
exit 0
else
# NOK - remove empty output file
2024-02-21 11:45:50 +01:00
echo "CRITICAL - Output file ${OUTPUT} is 0 bytes! Not removing the source file ${INPUT}"
2024-02-21 11:29:21 +01:00
rm -f ${OUTPUT}
exit 2
fi
2024-02-02 15:49:55 +01:00
;;
2024-02-21 11:29:21 +01:00
"-d")
echo "Decrypting file ${INPUT}";
2024-02-23 09:25:16 +01:00
OUTPUT=$(echo $INPUT | sed 's/\.crypto//')
HASH=$(echo $OUTPUT | sed 's/^.*\.//')
2024-02-02 15:49:55 +01:00
base64 -d ${INPUT} > ${INPUT}.temp
2024-02-23 09:25:16 +01:00
openssl enc -d $ALGOS -in ${INPUT}.temp -out ${OUTPUT}
2024-02-02 15:49:55 +01:00
rm -f ${INPUT}.temp
2024-02-21 11:29:21 +01:00
if [ "`stat ${OUTPUT} | grep Size | awk '{ print $2}'`" != 0 ]
then
2024-02-23 09:25:16 +01:00
# SHA256SUM CHECK
CUR_HASH=$(sha256sum ${OUTPUT} | awk '{ print $1 }')
if [ "${HASH}" != "${CUR_HASH}" ]
then
# NOK - Hash mismatch
echo "CRITICAL - Hashes mismatching!"
rm -f ${OUTPUT}
exit 2
else
# OK - safe to delete the original input file
echo "OK - Hashes matching, deleting input file"
rm -f ${INPUT}
mv ${OUTPUT} $(echo $OUTPUT | sed 's/\..*//')
exit 0
fi
2024-02-21 11:29:21 +01:00
else
# NOK - remove empty output file
2024-02-23 09:25:16 +01:00
echo "CRITICAL - Output file is 0 bytes! Not removing the input file"
2024-02-21 11:29:21 +01:00
rm -f ${OUTPUT}
exit 2
fi
2024-02-02 15:49:55 +01:00
exit 0
;;
2024-02-21 11:29:21 +01:00
*)
echo "Usage: ./crypter.sh -[e/d] [inputfile]";
exit 1
;;
2024-02-02 15:49:55 +01:00
esac
exit 3