31 lines
817 B
Bash
Executable file
31 lines
817 B
Bash
Executable file
#!/usr/bin/env bash
|
|
|
|
b64_encode() {
|
|
local idx=0 numerics table_idxs table_idx encoded
|
|
local table=( {A..Z} {a..z} {0..9} + / )
|
|
|
|
for (( ; idx < ${#1}; idx+=3 )); do
|
|
read -ra numerics < <(
|
|
printf '%d %d %d\n' "'${1:idx:1}" "'${1:idx+1:1}" "'${1:idx+2:1}"
|
|
)
|
|
|
|
(( table_idxs[0] = numerics[0] >> 2 ))
|
|
(( table_idxs[1] = (( (numerics[0] & 0x03) << 6) | (numerics[1] & 0xF0) >> 2) >> 2 ))
|
|
(( table_idxs[2] = (( (numerics[1] & 0x0F) << 4) | (numerics[2] & 0xC0) >> 4) >> 2 ))
|
|
(( table_idxs[3] = numerics[2] & 0x3F ))
|
|
|
|
for table_idx in "${table_idxs[@]}"; do
|
|
encoded+=${table[$table_idx]}
|
|
done
|
|
done
|
|
|
|
if (( ${#1} % 3 == 1 )); then
|
|
encoded=${encoded::-2}==
|
|
elif (( ${#1} % 3 == 2 )); then
|
|
encoded=${encoded::-1}=
|
|
fi
|
|
|
|
printf '%s\n' "$encoded"
|
|
}
|
|
|
|
b64_encode "$1"
|