Advertisement
LBPHacker

Lua base64 API

Oct 8th, 2013
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.38 KB | None | 0 0
  1. local lookup_V2C = {}
  2. for ixChar = 65, 90 do lookup_V2C[ixChar - 65] = string.char(ixChar) end
  3. for ixChar = 97, 122 do lookup_V2C[ixChar - 71] = string.char(ixChar) end
  4. for ixChar = 48, 57 do lookup_V2C[ixChar + 4] = string.char(ixChar) end
  5. lookup_V2C[62] = "+"
  6. lookup_V2C[63] = "/"
  7. local lookup_C2V = {}
  8. for key, value in pairs(lookup_V2C) do lookup_C2V[value] = key end
  9.  
  10. function encode(data)
  11.     local result = ""
  12.     for ix = 1, #data, 3 do
  13.         local all24 = data:sub(ix, ix):byte() * 65536 + (data:sub(ix + 1, ix + 1):byte() or 0) * 256 + (data:sub(ix + 2, ix + 2):byte() or 0)
  14.         result = result .. lookup_V2C[bit.band(all24, 16515072) / 262144] .. lookup_V2C[bit.band(all24, 258048) / 4096] .. lookup_V2C[bit.band(all24, 4032) / 64] .. lookup_V2C[bit.band(all24, 63)]
  15.     end
  16.     local padding = (3 - data:len() % 3) % 3
  17.     return result:sub(1, result:len() - padding) .. string.rep("=", padding)
  18. end
  19.  
  20. function decode(data)
  21.     local result = ""
  22.     for ix = 1, #data, 4 do
  23.         local all24 = lookup_C2V[data:sub(ix, ix)] * 262144 + (lookup_C2V[data:sub(ix + 1, ix + 1)] or 0) * 4096 + (lookup_C2V[data:sub(ix + 2, ix + 2)] or 0) * 64 + (lookup_C2V[data:sub(ix + 3, ix + 3)] or 0)
  24.         result = result .. string.char(bit.band(all24, 16711680) / 65536) .. string.char(bit.band(all24, 65280) / 256) .. string.char(bit.band(all24, 255))
  25.     end
  26.     return result:sub(1, result:len() - #data:match("^.-(=*)$"))
  27. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement