Advertisement
osmarks

lua base64

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