base64 encoding

Hi,

If anyone has the time and knows about base64 encoding, then can you please look through this script and see if I’m doing it right. The main part is not too long. I don’t know if you just add “=” characters at the end of the encoded string to get a multiple of 4. Also, am I suppose to add line feeds as the 76th character and multiples of 76 to keep lines less than 76 chars long.

property base64_chars : "ABCDEFGHIJKLMNOPQRSTUVWXYZ" & ¬
	"abcdefghijklmnopqrstuvwxyz0123456789+/"

---------- main
set t to "0123"
if t is "" then return
set tn to (length of t)
set r to (tn mod 3) -- number of odd 8 bit bytes
set b to TextToBits(t) -- get bit string for t
if r = 1 then -- append 4 zero bits
	set b to b & "0000"
else if r = 2 then -- append 2
	set b to b & "00"
end if
set bn to (length of b)
set num_bytes to (bn div 6) -- number of 6 bit bytes
set char_list to {}
repeat with i from 1 to num_bytes
	set start_bit to 6 * (i - 1) + 1
	set end_bit to 6 * i
	set the_byte to (text start_bit thru end_bit of b)
	set dec_num to BinToDec(the_byte)
	-- lookup char for dec_num
	set the_char to (character (dec_num + 1) of base64_chars)
	set end of char_list to the_char
end repeat
if r = 1 then -- append 2 "=" characters
	set char_list to char_list & {"=", "="}
else if r = 2 then -- append 1
	set end of char_list to "="
end if
set base64_string to char_list as string

---------- subroutines
-- returns decimal number from bit string
on BinToDec(b)
	set n to (length of b)
	set d to 0
	repeat with i from 1 to n
		set c to character -i of b
		set ci to c as integer
		set d to d + ci * (2 ^ (i - 1))
	end repeat
	return d
end BinToDec

-- converts text to bit string
-- uses DecToBin()
on TextToBits(t)
	set b_list to {}
	repeat with c in t
		set d to (ASCII number c)
		set b to DecToBin(d)
		set end of b_list to b
	end repeat
	return (b_list as string)
end TextToBits

-- returns 8 bit binary strings of decimal numbers less than 256
on DecToBin(dec_num)
	set b to {}
	repeat until dec_num is 0
		set r to dec_num mod 2
		set beginning of b to r
		set dec_num to dec_num div 2
	end repeat
	set b_string to text -8 thru -1 of ("00000000" & b)
	return (b_string)
end DecToBin

Thanks,

Do you need this routine complete just for fun?
If you don’t, you can use a shell script:

do shell script "openssl base64 < /path/to/file"

Or Smile’s command “encode64”.

Hi jj,

I didn’t get anywhere when I earlier searched the terminal, but the openssl worked! I had a feeling that there was some kind of encryption utility in unix but never could find it.

encode64 didn’t work. It must be in a newer version of Smile which I just downloaded.

The script seems to work on this short text and I can now test it to see if I’m getting the correct results.

Thanks a lot,