Guest User

b64-api

a guest
Mar 28th, 2015
929
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.06 KB | None | 0 0
  1. -- Base64
  2.  
  3. -- Characters
  4. local b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  5.  
  6. -- Encoding
  7. function encode(data)
  8.     return ((data:gsub('.', function(x)
  9.         local r,b='',x:byte()
  10.         for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
  11.         return r;
  12.     end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
  13.         if (#x < 6) then return '' end
  14.         local c=0
  15.         for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
  16.         return b:sub(c+1,c+1)
  17.     end)..({ '', '==', '=' })[#data%3+1])
  18. end
  19.  
  20. -- Decoding
  21. function decode(data)
  22.     data = string.gsub(data, '[^'..b..'=]', '')
  23.     return (data:gsub('.', function(x)
  24.         if (x == '=') then return '' end
  25.         local r,f='',(b:find(x)-1)
  26.         for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
  27.         return r;
  28.     end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
  29.         if (#x ~= 8) then return '' end
  30.         local c=0
  31.         for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
  32.         return string.char(c)
  33.     end))
  34. end
Advertisement
Add Comment
Please, Sign In to add comment