@@ -9,6 +9,12 @@ Export encode
99const alphabet= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
1010const padding= "="
1111
12+ dim index( 128 )
13+ for i = 0 to 63
14+ index(asc(mid(alphabet, i + 1 , 1 ))) = i
15+ next i
16+ index(asc(padding)) = 0
17+
1218func encode(message)
1319 local result= ""
1420 local in_len = len(message)
@@ -47,9 +53,25 @@ func encode(message)
4753 wend
4854 encode = result
4955end
50-
56+
5157func decode(message)
5258 local result = ""
59+ local in_len = len(message)
60+ local i, b_a, b_b, b_c, b_d
61+
62+ if (in_len % 4 != 0 ) then
63+ throw "Invalid base64 message length"
64+ endif
65+
66+ for i = 1 to in_len step 4
67+ b_a = index(asc(mid(message, i, 1 )))
68+ b_b = index(asc(mid(message, i + 1 , 1 )))
69+ b_c = index(asc(mid(message, i + 2 , 1 )))
70+ b_d = index(asc(mid(message, i + 3 , 1 )))
71+ result += chr(((b_a lshift 2 ) + (b_b rshift 4 )))
72+ result += chr(((b_b band 0 xf) lshift 4 ) + (b_c rshift 2 ))
73+ result += chr(((b_c band 0 x3) lshift 6 ) + b_d)
74+ next offset
5375 decode = result
5476end
5577
@@ -66,9 +88,15 @@ sub test
6688 if (encode( "This result will end with two equals." ) != "VGhpcyByZXN1bHQgd2lsbCBlbmQgd2l0aCB0d28gZXF1YWxzLg==" ) then
6789 throw "base64 encoding error 3"
6890 endif
69- ' if (base64_dec("Zm9vYmEy") != "foobar") then
70- ' throw "base64 encoding error"
71- ' endif
91+ if (decode( "Zm9vYmFy" ) != "foobar" ) then
92+ throw "base64 encoding error 4"
93+ endif
94+ if (decode( "VGhpcyBpcyBhIGxvbmdlciBzdHJpbmc=" ) != "This is a longer string" ) then
95+ throw "base64 encoding error 5"
96+ endif
97+ if (decode( "VGhpcyByZXN1bHQgd2lsbCBlbmQgd2l0aCB0d28gZXF1YWxzLg==" ) != "This result will end with two equals." ) then
98+ throw "base64 encoding error 6"
99+ endif
72100end
73101
74102test
0 commit comments