base64.lua 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. local M = {}
  2. -- Base64 字符集
  3. local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  4. -- 创建 Base64 反向查找表
  5. local b64lookup = {}
  6. for i = 1, #b64chars do
  7. b64lookup[string.sub(b64chars, i, i)] = i - 1
  8. end
  9. M.encode = function(input)
  10. local output = {}
  11. local len = #input
  12. for i = 1, len, 3 do
  13. local a, b, c = string.byte(input, i, i + 2)
  14. local chunk = (a or 0) << 16 | (b or 0) << 8 | (c or 0)
  15. output[#output + 1] = b64chars:sub(((chunk >> 18) & 0x3F) + 1, ((chunk >> 18) & 0x3F) + 1)
  16. output[#output + 1] = b64chars:sub(((chunk >> 12) & 0x3F) + 1, ((chunk >> 12) & 0x3F) + 1)
  17. output[#output + 1] = b and b64chars:sub(((chunk >> 6) & 0x3F) + 1, ((chunk >> 6) & 0x3F) + 1) or "="
  18. output[#output + 1] = c and b64chars:sub((chunk & 0x3F) + 1, (chunk & 0x3F) + 1) or "="
  19. end
  20. return table.concat(output)
  21. end
  22. -- Base64 解码函数
  23. M.decode = function(input)
  24. input = input:gsub("%s", ""):gsub("=", "") -- 去除空白和填充符
  25. local output = {}
  26. for i = 1, #input, 4 do
  27. local a, b, c, d = b64lookup[input:sub(i, i)], b64lookup[input:sub(i + 1, i + 1)],
  28. b64lookup[input:sub(i + 2, i + 2)] or 0, b64lookup[input:sub(i + 3, i + 3)] or 0
  29. local chunk = (a << 18) | (b << 12) | (c << 6) | d
  30. output[#output + 1] = string.char((chunk >> 16) & 0xFF)
  31. if input:sub(i + 2, i + 2) ~= "" then
  32. output[#output + 1] = string.char((chunk >> 8) & 0xFF)
  33. end
  34. if input:sub(i + 3, i + 3) ~= "" then
  35. output[#output + 1] = string.char(chunk & 0xFF)
  36. end
  37. end
  38. return table.concat(output)
  39. end
  40. return M