Skip to content

Instantly share code, notes, and snippets.

@Reselim
Last active April 3, 2021 22:05
Show Gist options
  • Save Reselim/400331834b34c576556cb2e0bc272dbc to your computer and use it in GitHub Desktop.
Save Reselim/400331834b34c576556cb2e0bc272dbc to your computer and use it in GitHub Desktop.
local Base64 = {
Filler = "=",
Indexes = {},
Alphabet = {
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"
}
}
for index, character in pairs(Base64.Alphabet) do
Base64.Indexes[character] = index
end
function Base64:Encode(input)
local output = ""
for chunk in string.gmatch(input, "(..?.?)") do
local octets = {
string.byte(chunk:sub(1, 1)),
string.byte(chunk:sub(2, 2)) or 0,
string.byte(chunk:sub(3, 3)) or 0
}
local A = bit.rshift(octets[1], 2)
local B = bit.lshift(bit.band(octets[1], 3), 4) + bit.rshift(octets[2] or 0, 4)
local C = bit.lshift(bit.band(octets[2] or 0, 15), 2) + bit.rshift(octets[3] or 0, 6)
local D = bit.band(octets[3] or 0, 63)
output = output ..
Base64.Alphabet[A + 1] ..
Base64.Alphabet[B + 1] ..
(#chunk >= 2 and Base64.Alphabet[C + 1] or Base64.Filler) ..
(#chunk == 3 and Base64.Alphabet[D + 1] or Base64.Filler)
end
return output
end
function Base64:Decode(input)
local output = ""
for chunk in string.gmatch(input, "(....)") do
local indexes = {
Base64.Indexes[chunk:sub(1, 1)] - 1,
Base64.Indexes[chunk:sub(2, 2)] - 1,
(Base64.Indexes[chunk:sub(3, 3)] or 1) - 1,
(Base64.Indexes[chunk:sub(4, 4)] or 1) - 1
}
local A = bit.lshift(indexes[1], 2) + bit.rshift(indexes[2], 4)
local B = bit.lshift(bit.band(indexes[2], 15), 4) + bit.rshift(indexes[3], 2)
local C = bit.lshift(bit.band(indexes[3], 3), 6) + indexes[4]
output = output .. string.char(A)
if chunk:sub(3, 3) ~= Base64.Filler then output = output .. string.char(B) end
if chunk:sub(4, 4) ~= Base64.Filler then output = output .. string.char(C) end
end
return output
end
return Base64
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment