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