1+ -- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de>
2+ -- licensed under the terms of the LGPL2
3+
4+ -- character table string
5+ local b = ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
6+
7+ -- encoding
8+
9+ local base64 = { }
10+
11+ function base64 .encode (data )
12+ return ((data :gsub (' .' , function (x )
13+ local r ,b = ' ' ,x :byte ()
14+ for i = 8 ,1 ,- 1 do r = r .. (b % 2 ^ i - b % 2 ^ (i - 1 )> 0 and ' 1' or ' 0' ) end
15+ return r ;
16+ end ).. ' 0000' ):gsub (' %d%d%d?%d?%d?%d?' , function (x )
17+ if (# x < 6 ) then return ' ' end
18+ local c = 0
19+ for i = 1 ,6 do c = c + (x :sub (i ,i )== ' 1' and 2 ^ (6 - i ) or 0 ) end
20+ return b :sub (c + 1 ,c + 1 )
21+ end ).. ({ ' ' , ' ==' , ' =' })[# data % 3 + 1 ])
22+ end
23+
24+ -- decoding
25+ function base64 .decode (data )
26+ data = string.gsub (data , ' [^' .. b .. ' =]' , ' ' )
27+ return (data :gsub (' .' , function (x )
28+ if (x == ' =' ) then return ' ' end
29+ local r ,f = ' ' ,(b :find (x )- 1 )
30+ for i = 6 ,1 ,- 1 do r = r .. (f % 2 ^ i - f % 2 ^ (i - 1 )> 0 and ' 1' or ' 0' ) end
31+ return r ;
32+ end ):gsub (' %d%d%d?%d?%d?%d?%d?%d?' , function (x )
33+ if (# x ~= 8 ) then return ' ' end
34+ local c = 0
35+ for i = 1 ,8 do c = c + (x :sub (i ,i )== ' 1' and 2 ^ (8 - i ) or 0 ) end
36+ return string.char (c )
37+ end ))
38+ end
39+
40+ return base64
0 commit comments