Created
March 22, 2018 14:53
-
-
Save kssi/885046d55873512fd7ea4ca5fe5e225a to your computer and use it in GitHub Desktop.
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 | |
# 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