ref: 86630e1740fc9b7d9ebd5782b6730e3cb8992202
./x509crypt
#! /bin/bash
# Paolo Lulli 2014
CONFIG_DIR=$HOME/.x509crypt
CONFIG_CERT_NAME="certificate"
test -d $CONFIG_DIR || mkdir -p $CONFIG_DIR
profile_name="default"
read_profile(){
echo "Profile name:"
read profile_name
}
generate_keys(){
echo "GENERATE KEYS"
openssl genrsa -out $CONFIG_DIR/$profile_name/certs/$CONFIG_CERT_NAME.key 2048
openssl req -batch -new -key $CONFIG_DIR/$profile_name/certs/$CONFIG_CERT_NAME.key -out $CONFIG_DIR/$profile_name/certs/$CONFIG_CERT_NAME.csr -config $CONFIG_DIR/$profile_name/conf/$profile_name-config
openssl x509 -req -days 365 -in $CONFIG_DIR/$profile_name/certs/$CONFIG_CERT_NAME.csr -signkey $CONFIG_DIR/$profile_name/certs/$CONFIG_CERT_NAME.key -out $CONFIG_DIR/$profile_name/certs/$CONFIG_CERT_NAME.crt
}
export_key(){
echo "EXPORT PUBLIC KEY:[$CONFIG_CERT_NAME.key]"
cp $CONFIG_DIR/$profile_name/certs/$CONFIG_CERT_NAME.key .
}
setup_profile(){
echo "SETUP PROFILE"
test -d $CONFIG_DIR/$profile_name || mkdir -p $CONFIG_DIR/$profile_name
test -d $CONFIG_DIR/$profile_name/conf || mkdir -p $CONFIG_DIR/$profile_name/conf
test -d $CONFIG_DIR/$profile_name/certs || mkdir -p $CONFIG_DIR/$profile_name/certs
}
file_decrypt(){
echo "FILE DECRYPT: $1"
decrypted_file=$1".cleartext"
#openssl smime -decrypt -binary -in $1 -inform DER -out $decrypted_file -inkey $CONFIG_DIR/$profile_name/certs/$CONFIG_CERT_NAME.key -passin pass:your_password
openssl smime -decrypt -binary -in $1 -inform DER -out $decrypted_file -inkey $CONFIG_DIR/$profile_name/certs/$CONFIG_CERT_NAME.key
}
file_encrypt(){
echo "FILE ENCRYPT: $1"
encrypted_file=$1".enc"
openssl smime -encrypt -binary -aes-256-cbc -in $1 -out $encrypted_file -outform DER $CONFIG_DIR/$profile_name/certs/$CONFIG_CERT_NAME.crt
}
usage(){
echo "$0 -e : ENCRYPTS FILE"
echo "$0 -d : DECRYPTS FILE"
echo "$0 -g : GENERATE KEYS"
echo "$0 -p : SETUP PROFILE"
echo "$0 -x : EXPORT PUB KEY"
}
if [ "$#" -gt 2 ]; then
usage
exit
fi
if [ "$#" -eq 0 ]; then
usage
exit
fi
if [ "$#" -eq 1 ]; then
if [ "$1" == "-p" ]; then
setup_profile
exit
fi
if [ "$1" == "-g" ]; then
generate_keys
exit
fi
if [ "$1" == "-x" ]; then
export_key
exit
fi
usage
fi
if [ "$#" -eq 2 ]; then
input_file=$2
if [ "$1" == "-e" ]; then
file_encrypt $input_file
file_decrypt $input_file".enc"
diff $input_file $input_file".enc.cleartext" || echo "ERROR: BAD ENCRYPTION"
rm $input_file".enc.cleartext"
exit
fi
if [ "$1" == "-d" ]; then
file_decrypt $input_file
exit
fi
usage
fi
#read_profile
echo "You choose profile: [$profile_name]"