Created
May 25, 2017 23:18
-
-
Save BigNerd95/065288a3e91fca162456fd2c71daa830 to your computer and use it in GitHub Desktop.
Base64 encode implementation entirely in bash
This file contains hidden or 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 | |
| base64encode(){ | |
| local base64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" | |
| local res="" | |
| for i in $(seq 0 3 $((${#1}-1))) | |
| do | |
| local n1=$(printf '%d' "'${1:i+0:1}") | |
| local n2=$(printf '%d' "'${1:i+1:1}") | |
| local n3=$(printf '%d' "'${1:i+2:1}") | |
| local n=$(( (n1<<16) + (n2<<8) + (n3<<0) )) | |
| local c1=$(( (n >> 18) & 0x3F )) | |
| local c2=$(( (n >> 12) & 0x3F )) | |
| local c3=$(( (n >> 6) & 0x3F )) | |
| local c4=$(( (n >> 0) & 0x3F )) | |
| res="$res${base64chars:$c1:1}" | |
| res="$res${base64chars:$c2:1}" | |
| res="$res${base64chars:$c3:1}" | |
| res="$res${base64chars:$c4:1}" | |
| done | |
| local mod=$(( (3 - (${#1} % 3)) % 3 )) | |
| res=${res:0:${#res}-mod} | |
| while [[ $mod -gt 0 ]] | |
| do | |
| res="$res=" | |
| mod=$mod-1 | |
| done | |
| echo $res | |
| } | |
| base64encode $1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment