#!/bin/ksh # # Low ASCII Base64 converter in Kornshell # # (c) Peter van Eerten november 2007 - GPL. # #---------------------------------------------------------------------------------------------- # Data needed for ASCII value of character set -A CHAR " " "!" "\"" "#" "$" "%" "&" "'" "(" ")" "*" "+" "," "-" "." "/" "0" "1" "2" \ "3" "4" "5" "6" "7" "8" "9" ":" ";" "<" "=" ">" "?" "@" "A" "B" "C" "D" "E" "F" \ "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" \ "[" "\"" "]" "^" "_" "\`" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" \ "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "{" "|" "}" "~" # This is the Base64 string set -A BASE64 "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" \ "U" "V" "W" "X" "Y" "Z" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" \ "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "0" "1" "2" "3" "4" "5" "6" "7" \ "8" "9" "+" "/" # Convert character to ASCII value function asc { typeset i=0 if [[ $1 = "¤" ]] then ASC=32 else while [[ $i -lt 95 ]] do if [[ $1 = "${CHAR[$i]}" ]] then break fi ((i+=1)) done if [[ $i -eq 95 ]] then ASC=128 else let ASC=$i+32 fi fi } # This is the main program if [[ $# -eq 0 ]] then read TOTAL?"Enter text to convert... " else TOTAL=$1 fi # First convert spaces to "¤" VAR="" for t in $TOTAL do VAR=$VAR$t"¤" done let NUM=${#VAR}-1 typeset -L${NUM} VAR="$VAR" # This variable will contain the result result="" # Start encoding while [[ ${#VAR} -gt 0 ]] do # Specify byte values if [[ ${#VAR} -eq 1 ]]; then typeset -L1 byte="$VAR" asc $byte byte1=$ASC byte2=0 byte3=0 fi if [[ ${#VAR} -eq 2 ]]; then typeset -L1 byte="$VAR" asc $byte byte1=$ASC let NUM=${#VAR}-1 typeset -R${NUM} TMP="$VAR" typeset -L1 byte="$TMP" asc $byte byte2=$ASC byte3=0 fi if [[ ${#VAR} -ge 3 ]]; then typeset -L1 byte="$VAR" asc $byte byte1=$ASC let LEN="${#VAR}"-1 typeset -R$LEN TMP="$VAR" typeset -L1 byte=$TMP asc $byte byte2=$ASC let LEN=${#TMP}-1 typeset -R$LEN TMP="$TMP" typeset -L1 byte=$TMP asc $byte byte3=$ASC fi # Create BASE64 values let base1=$((byte1>>2)) let base2=$(($((byte1&3))<<4))+$(($((byte2&240))>>4)) let base3=$(($((byte2&15))<<2))+$(($((byte3&192))>>6)) let base4=$((byte3&63)) # Compose BASE64 string if [[ ${#VAR} -eq 1 ]]; then result=$result${BASE64[$base1]} result=$result${BASE64[$base2]} result=$result"==" unset VAR fi if [[ ${#VAR} -eq 2 ]]; then result=$result${BASE64[$base1]} result=$result${BASE64[$base2]} result=$result${BASE64[$base3]} result=$result"=" unset VAR fi if [[ ${#VAR} -ge 3 ]]; then result=$result${BASE64[$base1]} result=$result${BASE64[$base2]} result=$result${BASE64[$base3]} result=$result${BASE64[$base4]} if [[ ${#VAR} -gt 3 ]] then let NUM=${#VAR}-3 typeset -R${NUM} VAR="${VAR}" else unset VAR fi fi done echo $result exit #----------------------------------------------------------------------------------------------