#!/usr/bin/env bash set -eu usage() { echo "(!) THIS WAS MADE FOR TEST PURPOSE SO DON'T USE THIS SCRIPT FOR ENCRYPTION OF SENSITIVE FILE file-encrypter - Encrypts/Decrypts the file with AES-256 (for the file) and RSA (for the key). COMMANDS: file-encrypter enc Encrypts the input file. The output file name should be '.enc'. and must be a more 1024 bit of PKCS8 format. file-encrypter dec Decrypts the input file. The output file name should be dropped '.enc' extension from '' (i.e. The original file name before your encryption)." exit 1 } COMMAND=${1} RSA_KEY=${2} INPUT_FILE=${3} if [[ -z ${COMMAND} || -z ${INPUT_FILE} ]] || [[ ${COMMAND} != 'enc' && ${COMMAND} != 'dec' ]]; then usage fi if [[ ! -f ${RSA_KEY} ]]; then echo "No such input file: ${RSA_KEY}" exit 2 fi if [[ ! -f ${INPUT_FILE} ]]; then echo "No such input file: ${INPUT_FILE}" exit 2 fi WORKING_DIR=$(mktemp -d) TEMP_ENCRYPTED_FILE="${WORKING_DIR}/temp" RANDOM_KEY="${WORKING_DIR}/key.bin" RANDOM_KEY_ENCRYPTED="${WORKING_DIR}/key.enc" if [[ ${COMMAND} == 'enc' ]]; then OUTPUT_FILE="${3}.enc" openssl rand 32 -out ${RANDOM_KEY}; openssl rsautl -encrypt -inkey ${RSA_KEY} -pubin -in ${RANDOM_KEY} | base64 > ${OUTPUT_FILE} openssl enc -aes-256-cbc -salt -in ${INPUT_FILE} -pass file:${RANDOM_KEY} | base64 >> ${OUTPUT_FILE} echo "Encrypted into: ${OUTPUT_FILE}" else OUTPUT_FILE="${INPUT_FILE%.*}" if [[ -f ${OUTPUT_FILE} ]]; then echo "The output file already exists: ${OUTPUT_FILE}" exit 3 fi head -n 1 ${INPUT_FILE} | base64 -D | openssl rsautl -decrypt -inkey ${RSA_KEY} -out ${RANDOM_KEY} tail -n +2 ${INPUT_FILE} | base64 -D | openssl enc -d -aes-256-cbc -out ${OUTPUT_FILE} -pass file:${RANDOM_KEY} echo "Decrypted into: ${OUTPUT_FILE}" fi rm -fr ${WORKING_DIR} exit 0 `