Last active
March 30, 2023 04:25
-
-
Save vinicius73/1c60b21c8a9ad67371cfe887794d0d65 to your computer and use it in GitHub Desktop.
Generate a SSH Key and encrypt it with gpg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -eu | |
DIR='./files/ssh' | |
OUTPUT_FILE='./files/ssh.tar.gz' | |
while getopts do: flag | |
do | |
case "${flag}" in | |
d) DIR=${OPTARG};; | |
o) OUTPUT_FILE=${OPTARG};; | |
esac | |
done | |
DIR=$(realpath $DIR); | |
OUTPUT_FILE=$(realpath $OUTPUT_FILE); | |
CONFIG_CONTENT=$(cat <<EOF | |
Host * | |
HashKnownHosts no | |
StrictHostKeyChecking yes | |
CheckHostIP no | |
Host github | |
HostName github.com | |
User git | |
Host bitbucket | |
Hostname bitbucket.org | |
User git | |
Host gitlab | |
Hostname gitlab.com | |
User git | |
EOF | |
) | |
echo "@> 🧰 Generating SSH keys in $DIR"; | |
if [ -d $DIR ]; then | |
read -p "@> ⚠️ Are you sure you want to delete $DIR? [y/N] " -n 1 -r | |
echo | |
if [[ ! $REPLY =~ ^[Yy]$ ]] | |
then | |
exit 1 | |
fi | |
echo "@> 🧹 Cleaning $DIR"; | |
rm -rf $DIR; | |
fi | |
mkdir -p $DIR; | |
cd $DIR; | |
ssh-keygen -t ed25519 -C "Espaco Dohler" -f $DIR/ed25519 -N ""; | |
echo "@> 📝 Generating config file"; | |
echo "$CONFIG_CONTENT" > $DIR/config; | |
# define correct permissions | |
chmod 600 $DIR/ed25519; | |
chmod 644 $DIR/ed25519.pub; | |
chmod 644 $DIR/config; | |
echo "@> 📦 Generating tarball"; | |
if [ -f "$OUTPUT_FILE.gpg" ]; then | |
read -p "@> ⚠️ Are you sure you want to delete $OUTPUT_FILE? [y/N] " -n 1 -r | |
echo | |
if [[ ! $REPLY =~ ^[Yy]$ ]] | |
then | |
exit 1 | |
fi | |
echo "@> 🧹 Cleaning $OUTPUT_FILE"; | |
rm -rf "$OUTPUT_FILE.gpg"; | |
fi | |
tar -C $DIR -czvf $OUTPUT_FILE *; | |
echo "@> 🔑 Encrypting tarball"; | |
gpg --symmetric --cipher-algo AES256 --batch --passphrase "$SSH_FILES_PASSPHRASE" $OUTPUT_FILE; | |
# to decrypt: | |
# echo "$SSH_FILES_PASSPHRASE" | gpg --batch --passphrase-fd 0 -o files/ssh.tar.gz --decrypt files/ssh.tar.gz.gpg | |
echo "@> 📝 Public key:"; | |
echo ""; | |
cat $DIR/ed25519.pub; | |
echo ""; | |
echo "@> 📦 Done!"; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment