b64.lua 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. --module('b64', package.seeall)
  7. b64 = {}
  8. -- bitshift functions (<<, >> equivalent)
  9. -- shift left
  10. local function lsh(value,shift)
  11. return (value*(2^shift)) % 256
  12. end
  13. -- shift right
  14. local function rsh(value,shift)
  15. return math.floor(value/2^shift) % 256
  16. end
  17. -- return single bit (for OR)
  18. local function bit(x,b)
  19. return (x % 2^b - x % 2^(b-1) > 0)
  20. end
  21. -- logic OR for number values
  22. local function lor(x,y)
  23. result = 0
  24. for p=1,8 do result = result + (((bit(x,p) or bit(y,p)) == true) and 2^(p-1) or 0) end
  25. return result
  26. end
  27. -- Character decoding table
  28. local function toBase64Byte(char)
  29. ascii = string.byte(char, 1)
  30. if ascii >= string.byte('A', 1) and ascii <= string.byte('Z', 1) then return ascii - string.byte('A', 1)
  31. elseif ascii >= string.byte('a', 1) and ascii <= string.byte('z', 1) then return ascii - string.byte('a', 1) + 26
  32. elseif ascii >= string.byte('0', 1) and ascii <= string.byte('9', 1) then return ascii + 4
  33. elseif ascii == string.byte('-', 1) then return 62
  34. elseif ascii == string.byte('_', 1) then return 63
  35. elseif ascii == string.byte('=', 1) then return nil
  36. else return nil, "ERROR! Char is invalid for Base64 encoding: "..char end
  37. end
  38. -- function decode
  39. -- decode base64 input to string
  40. function b64.decode(data)
  41. local chars = {}
  42. local result=""
  43. for dpos=0,string.len(data)-1,4 do
  44. for char=1,4 do chars[char] = toBase64Byte((string.sub(data,(dpos+char),(dpos+char)) or "=")) end
  45. result = string.format(
  46. '%s%s%s%s',
  47. result,
  48. string.char(lor(lsh(chars[1],2), rsh(chars[2],4))),
  49. (chars[3] ~= nil) and string.char(lor(lsh(chars[2],4),
  50. rsh(chars[3],2))) or "",
  51. (chars[4] ~= nil) and string.char(lor(lsh(chars[3],6) % 192,
  52. (chars[4]))) or ""
  53. )
  54. end
  55. return result
  56. end
  57. return b64