Skip to content

Instantly share code, notes, and snippets.

@kssi
Created March 22, 2018 14:53
Show Gist options
  • Save kssi/885046d55873512fd7ea4ca5fe5e225a to your computer and use it in GitHub Desktop.
Save kssi/885046d55873512fd7ea4ca5fe5e225a to your computer and use it in GitHub Desktop.
#!/bin/bash
# file base64_encode.sh
# author mknod @ freenode
# license none
# bash version 3.2+
# description a beautifully slow implementation of base64 encoding in pure Bash
# synopsis ./base64_encode.sh
# stdin raw data
# stdout base64 encoded data
# exit status 0
# variables
base64_table=({A..Z} {a..z} {0..9} "+" "/")
base64_padding_char="="
# routines
base64_encode() {
local d="" byte_rem="3" word="0" \
LC_CTYPE="C" IFS=""
while read -r -d "" -n 1; do
((byte_rem--))
printf -v d "%d" "'$REPLY"
((word |= (d < 0 ? 256+d : d) << byte_rem*8))
if ((byte_rem == 0)); then
printf '%s' "${base64_table[word >> 18]}" \
"${base64_table[word >> 12 & 0x3F]}" \
"${base64_table[word >> 6 & 0x3F]}" \
"${base64_table[word & 0x3F]}"
word="0" byte_rem="3"
fi
done
if ((byte_rem == 2)); then
printf '%s' "${base64_table[word >> 18]}" \
"${base64_table[word >> 12 & 0x3F]}" \
"$base64_padding_char" \
"$base64_padding_char"
elif ((byte_rem == 1)); then
printf '%s' "${base64_table[word >> 18]}" \
"${base64_table[word >> 12 & 0x3F]}" \
"${base64_table[word >> 6 & 0x3F]}" \
"$base64_padding_char"
fi
}
# main
base64_encode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment