psycholyzern

http://lua-users.org/wiki/BaseSixtyFour

Mar 19th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.54 KB | None | 0 0
  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.  
  5. -- character table string
  6. local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  7.  
  8. -- encoding
  9. function enc(data)
  10.     return ((data:gsub('.', function(x)
  11.         local r,b='',x:byte()
  12.         for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
  13.         return r;
  14.     end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
  15.         if (#x < 6) then return '' end
  16.         local c=0
  17.         for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
  18.         return b:sub(c+1,c+1)
  19.     end)..({ '', '==', '=' })[#data%3+1])
  20. end
  21.  
  22. -- decoding
  23. function dec(data)
  24.     data = string.gsub(data, '[^'..b..'=]', '')
  25.     return (data:gsub('.', function(x)
  26.         if (x == '=') then return '' end
  27.         local r,f='',(b:find(x)-1)
  28.         for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
  29.         return r;
  30.     end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
  31.         if (#x ~= 8) then return '' end
  32.         local c=0
  33.         for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
  34.         return string.char(c)
  35.     end))
  36. end
  37.  
  38. -- command line if not called as library
  39. if (arg ~= nil) then
  40.     local func = 'enc'
  41.     for n,v in ipairs(arg) do
  42.         if (n > 0) then
  43.             if (v == "-h") then print "base64.lua [-e] [-d] text/data" break
  44.             elseif (v == "-e") then func = 'enc'
  45.             elseif (v == "-d") then func = 'dec'
  46.             else print(_G[func](v)) end
  47.         end
  48.     end
  49. else
  50.     module('base64',package.seeall)
  51. end
Add Comment
Please, Sign In to add comment