Advertisement
Treyzania

CC base64

Feb 11th, 2015
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.94 KB | None | 0 0
  1. --[[
  2.  Base64 library. '.' and '/' are used as 62 and 63 respectively.
  3.  @author Wim Thys <wim.thys@zardof.be>
  4.  @date 2012-09-08
  5. ]]--
  6.  
  7. local VERSION = '0.1'
  8. function version()
  9.     return VERSION
  10. end
  11.  
  12. local alfa = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./"
  13.  
  14. function encode(src,pad)
  15.     if not pad then pad = "=" end
  16.     local tgt = ""
  17.     local L = string.len(src)
  18.     local E = 1
  19.     local bbb = string.byte(src,1,L)
  20.     table.insert(bbb, 0)
  21.     table.insert(bbb, 0)
  22.     while E <= L do
  23.         local B = bbb[E]*2^16+bbb[E+1]*2^8+bbb[E+2]
  24.         local b1,b2,b3,b4,d
  25.         b1,b2 = math.modf(B/2^18)
  26.         b2,b3 = math.modf(b2*2^6)
  27.         b3,b4 = math.modf(b3*2^6)
  28.         b4,d  = math.modf(b4*2^6)
  29.         for i,C in ipairs({b1,b2,b3,b4}) do
  30.             tgt = tgt .. string.sub(alfa,C,C)
  31.         end
  32.         E = E+3
  33.     end
  34.     tgt = string.sub(tgt,1,math.floor(L*8/6)) .. string.rep(pad,(4-math.floor(L*8/6)%4)%4)
  35.     return tgt
  36. end
  37.  
  38. function _transform(val)
  39.     local T = {}
  40.     for i=1,1,string.len(val) do
  41.         table.insert(T, string.find(alfa, string.sub(val,i,i)))
  42.     end
  43.     return T
  44. end
  45.  
  46. function _strip_end(src,pad)
  47.     local E = string.len(src)
  48.     if string.sub(src,E,E) == pad then
  49.         return _strip_end(string.sub(src,1,E-1),pad)
  50.     else
  51.         return src
  52.     end
  53. end
  54.  
  55. function decode(src, pad)
  56.     if not pad then pad = "=" end
  57.     local tgt = ""
  58.     src = _strip_end(src,pad)
  59.     local bbb = _transform(src)
  60.     table.insert(bbb,0)
  61.     table.insert(bbb,0)
  62.     table.insert(bbb,0)
  63.     local L = string.len(src)
  64.     local E = 1
  65.     while E <= L do
  66.         local B = bbb[E]*2^18 + bbb[E+1]*2^12 + bbb[E+2]*2^6 + bbb[E+3]
  67.         local d1,d2,d3,e
  68.         d1,d2 = math.modf(B/2^16)
  69.         d2,d3 = math.modf(d2*2^8)
  70.         d3,e  = math.modf(d3*2^8)
  71.         tgt = tgt .. string.char(d1,d2,d3)
  72.     end
  73.     tgt = string.sub(tgt, 1, math.floor(L*6/8))
  74.     return tgt
  75. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement