1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
|
#!/bin/bash
base64_charset=( {A..Z} {a..z} {0..9} + / = )
text_width=64
function display_base64_char {
printf "${base64_charset[$1]}"; (( width++ ))
(( width % text_width == 0 )) && printf "\n"
}
function encode_base64 {
declare -a -i c8 c6
c8=( $(printf "ibase=16; ${1:0:2}\n${1:2:2}\n${1:4:2}\n" | bc) )
(( c6[0] = c8[0] >> 2 ))
(( c6[1] = ((c8[0] & 3) << 4) | (c8[1] >> 4) ))
case ${#c8[*]} in
3) (( c6[2] = ((c8[1] & 15) << 2) | (c8[2] >> 6) ))
(( c6[3] = c8[2] & 63 )) ;;
2) (( c6[2] = (c8[1] & 15) << 2 ))
(( c6[3] = 64 )) ;;
1) (( c6[2] = c6[3] = 64 )) ;;
esac
for char in ${c6[@]}; do
display_base64_char ${char}
done
}
function decode_base64 {
declare -a -i c8 c6
for current_char in ${1:0:1} ${1:1:1} ${1:2:1} ${1:3:1}; do
[ "${current_char}" = "=" ] && break
position=0
while [ "${current_char}" != "${base64_charset[${position}]}" ]; do
(( position++ ))
done
c6=( ${c6[*]} ${position} )
done
(( c8[0] = (c6[0] << 2) | (c6[1] >> 4) ))
case ${#c6[*]} in
3) (( c8[1] = ( (c6[1] & 15) << 4) | (c6[2] >> 2) ))
(( c8[2] = (c6[2] & 3) << 6 )); unset c8[2] ;;
4) (( c8[1] = ( (c6[1] & 15) << 4) | (c6[2] >> 2) ))
(( c8[2] = ( (c6[2] & 3) << 6) | c6[3] )) ;;
esac
for char in ${c8[*]}; do
printf "\x$(printf "%x" ${char})"
done
}
if [ "$1" = "-d" ]; then
content=$(cat - | tr -d "\n" | sed -r "s/(.{4})/\1 /g")
for chars in ${content}; do decode_base64 ${chars}; done
else
content=$(cat - | xxd -ps -u | sed -r "s/(\w{6})/\1 /g" |
tr -d "\n")
for chars in ${content}; do encode_base64 ${chars}; done
echo
fi
|