53 lines
1.7 KiB
Lua
53 lines
1.7 KiB
Lua
local M = {}
|
|
|
|
-- Base64 字符集
|
|
local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
|
|
-- 创建 Base64 反向查找表
|
|
local b64lookup = {}
|
|
for i = 1, #b64chars do
|
|
b64lookup[string.sub(b64chars, i, i)] = i - 1
|
|
end
|
|
|
|
M.encode = function(input)
|
|
local output = {}
|
|
local len = #input
|
|
for i = 1, len, 3 do
|
|
local a, b, c = string.byte(input, i, i + 2)
|
|
local chunk = (a or 0) << 16 | (b or 0) << 8 | (c or 0)
|
|
|
|
output[#output + 1] = b64chars:sub(((chunk >> 18) & 0x3F) + 1, ((chunk >> 18) & 0x3F) + 1)
|
|
output[#output + 1] = b64chars:sub(((chunk >> 12) & 0x3F) + 1, ((chunk >> 12) & 0x3F) + 1)
|
|
output[#output + 1] = b and b64chars:sub(((chunk >> 6) & 0x3F) + 1, ((chunk >> 6) & 0x3F) + 1) or "="
|
|
output[#output + 1] = c and b64chars:sub((chunk & 0x3F) + 1, (chunk & 0x3F) + 1) or "="
|
|
end
|
|
return table.concat(output)
|
|
end
|
|
|
|
-- Base64 解码函数
|
|
M.decode = function(input)
|
|
input = input:gsub("%s", ""):gsub("=", "") -- 去除空白和填充符
|
|
local output = {}
|
|
for i = 1, #input, 4 do
|
|
local a, b, c, d = b64lookup[input:sub(i, i)], b64lookup[input:sub(i + 1, i + 1)],
|
|
b64lookup[input:sub(i + 2, i + 2)] or 0, b64lookup[input:sub(i + 3, i + 3)] or 0
|
|
local chunk = (a << 18) | (b << 12) | (c << 6) | d
|
|
|
|
output[#output + 1] = string.char((chunk >> 16) & 0xFF)
|
|
if input:sub(i + 2, i + 2) ~= "" then
|
|
output[#output + 1] = string.char((chunk >> 8) & 0xFF)
|
|
end
|
|
if input:sub(i + 3, i + 3) ~= "" then
|
|
output[#output + 1] = string.char(chunk & 0xFF)
|
|
end
|
|
end
|
|
return table.concat(output)
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
return M
|
|
|
|
|