Skip to content

Instantly share code, notes, and snippets.

@socketz
Last active September 23, 2018 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save socketz/d293561d1bea34e4efb01a760303ea15 to your computer and use it in GitHub Desktop.
Save socketz/d293561d1bea34e4efb01a760303ea15 to your computer and use it in GitHub Desktop.
Bash Base64 encoding / decoding functions with rotation (rotXX / rot13)
#!/bin/bash
function rot_base64_e(){
USAGE="\nrot_base64_e <input_file_or_string> <rotation> [<output> empty for print]\nUsage example: rot_base64_e file.txt 13 output.txt\n"
if [ -f "$1" ]; then
CONTENT=$(cat $1)
elif [ -n "$1" ]; then
CONTENT=$1
else
printf "$USAGE"
echo "Invalid file or string input"
return
fi
if [[ $2 =~ ^-?[0-9]+$ ]]; then
ROT=$2
else
printf "$USAGE"
echo "Invalid integer rotation"
return
fi
for (( i = 0; i < $ROT; i++ )); do
CONTENT=$(echo "$CONTENT" | base64 -w 0)
done
if [ -z "$3" ]; then
echo $CONTENT
else
OUTPUT=$3
echo $CONTENT > $OUTPUT
fi
}
function rot_base64_d(){
USAGE="\nrot_base64_d <input_file_or_string> <rotation> [<output> empty for print]\nUsage example: rot_base64_d file.txt 13 output.txt\n"
if [ -f "$1" ]; then
CONTENT=$(cat $1)
elif [ -n "$1" ]; then
CONTENT=$1
else
printf "$USAGE"
echo "Invalid file or string input"
return
fi
if [[ $2 =~ ^-?[0-9]+$ ]]; then
ROT=$2
else
printf "$USAGE"
echo "Invalid integer rotation"
return
fi
for (( i = 0; i < $ROT; i++ )); do
CONTENT=$(echo "$CONTENT" | base64 -w 0 -d)
done
if [ -z "$3" ]; then
echo $CONTENT
else
OUTPUT=$3
echo $CONTENT > $OUTPUT
fi
}
# Example
echo "This is a encoded text" > test.txt
# Encodes a text 4 times in base64
rot_base64_e test.txt 4 out.txt
# Shows Base64 encoding results
cat out.txt
# Decodes Base64 encoding with rotation of 4 (this example without output file)
rot_base64_d out.txt 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment