Lua base64 encode and validating decode
Lua
local B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
local function encode(s) local out = {}
for i = 1, #s, 3 do
local a, b, c = s:byte(i, i + 2)
local n = (a or 0) << 16 | (b or 0) << 8 | (c or 0)
local chars, pad = {}, c and 0 or b and 1 or 2
for j = 1, 4 do local v = (n >> (6 * (4 - j))) & 63; chars[j] = j <= 4 - pad and B64:sub(v + 1, v + 1) or '=' end
out[#out + 1] = table.concat(chars)
end
return table.concat(out) end
local function decode(s) s = s:gsub('%s', '')
if #s % 4 ~= 0 or s:find('=[^=]') or #(s:match('(=*)$')) > 2 then return nil, 'malformed base64' end
local out, n = {}, 0
for i = 1, #s do
local c = s:sub(i, i)
local v = B64:find(c, 1, true) or (c == '=' and 1)
if not v then return nil, ('invalid base64 character %q at %d'):format(c, i) end
n = n * 64 + v - 1
if i % 4 == 0 then out[#out + 1] = string.char(n // 65536 % 256, n // 256 % 256, n % 256); n = 0 end
end
return (table.concat(out):sub(1, -1 - #(s:match('(=*)$')))) end
return { encode = encode, decode = decode }