b64.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/local/bin/lua
  2. -- Based on http://lua-users.org/wiki/BaseSixtyFour by Alex Kloss
  3. -- compatible with lua 5.1
  4. -- http://www.it-rfc.de
  5. -- licensed under the terms of the LGPL2
  6. b64 = {}
  7. -- bitshift functions (<<, >> equivalent)
  8. -- shift left
  9. local function lsh(value,shift)
  10. return (value*(2^shift)) % 256
  11. end
  12. -- shift right
  13. local function rsh(value,shift)
  14. -- Lua builds with no floating point don't define math.
  15. if math then return math.floor(value/2^shift) % 256 end
  16. return (value/2^shift) % 256
  17. end
  18. -- return single bit (for OR)
  19. local function bit(x,b)
  20. return (x % 2^b - x % 2^(b-1) > 0)
  21. end
  22. -- logic OR for number values
  23. local function lor(x,y)
  24. result = 0
  25. for p=1,8 do result = result + (((bit(x,p) or bit(y,p)) == true) and 2^(p-1) or 0) end
  26. return result
  27. end
  28. -- Character decoding table
  29. local function toBase64Byte(char)
  30. ascii = string.byte(char, 1)
  31. if ascii >= string.byte('A', 1) and ascii <= string.byte('Z', 1) then return ascii - string.byte('A', 1)
  32. elseif ascii >= string.byte('a', 1) and ascii <= string.byte('z', 1) then return ascii - string.byte('a', 1) + 26
  33. elseif ascii >= string.byte('0', 1) and ascii <= string.byte('9', 1) then return ascii + 4
  34. elseif ascii == string.byte('-', 1) then return 62
  35. elseif ascii == string.byte('_', 1) then return 63
  36. elseif ascii == string.byte('=', 1) then return nil
  37. else return nil, "ERROR! Char is invalid for Base64 encoding: "..char end
  38. end
  39. -- function decode
  40. -- decode base64 input to string
  41. function b64.decode(data)
  42. local chars = {}
  43. local result=""
  44. for dpos=0,string.len(data)-1,4 do
  45. for char=1,4 do chars[char] = toBase64Byte((string.sub(data,(dpos+char),(dpos+char)) or "=")) end
  46. result = string.format(
  47. '%s%s%s%s',
  48. result,
  49. string.char(lor(lsh(chars[1],2), rsh(chars[2],4))),
  50. (chars[3] ~= nil) and string.char(lor(lsh(chars[2],4),
  51. rsh(chars[3],2))) or "",
  52. (chars[4] ~= nil) and string.char(lor(lsh(chars[3],6) % 192,
  53. (chars[4]))) or ""
  54. )
  55. end
  56. return result
  57. end
  58. return b64