Path: blob/master/bench/other/boatbomber-HashLib/Base64.lua
2727 views
-- @original: https://gist.github.com/Reselim/40d62b17d138cc74335a1b0709e19ce21local Alphabet = {}2local Indexes = {}34-- A-Z5for Index = 65, 90 do6table.insert(Alphabet, Index)7end89-- a-z10for Index = 97, 122 do11table.insert(Alphabet, Index)12end1314-- 0-915for Index = 48, 57 do16table.insert(Alphabet, Index)17end1819table.insert(Alphabet, 43) -- +20table.insert(Alphabet, 47) -- /2122for Index, Character in ipairs(Alphabet) do23Indexes[Character] = Index24end2526local Base64 = {}2728local bit32_rshift = bit32.rshift29local bit32_lshift = bit32.lshift30local bit32_band = bit32.band3132--[[**33Encodes a string in Base64.34@param [t:string] Input The input string to encode.35@returns [t:string] The string encoded in Base64.36**--]]37function Base64.Encode(Input)38local Output = {}39local Length = 04041for Index = 1, #Input, 3 do42local C1, C2, C3 = string.byte(Input, Index, Index + 2)4344local A = bit32_rshift(C1, 2)45local B = bit32_lshift(bit32_band(C1, 3), 4) + bit32_rshift(C2 or 0, 4)46local C = bit32_lshift(bit32_band(C2 or 0, 15), 2) + bit32_rshift(C3 or 0, 6)47local D = bit32_band(C3 or 0, 63)4849Length = Length + 150Output[Length] = Alphabet[A + 1]5152Length = Length + 153Output[Length] = Alphabet[B + 1]5455Length = Length + 156Output[Length] = C2 and Alphabet[C + 1] or 615758Length = Length + 159Output[Length] = C3 and Alphabet[D + 1] or 6160end6162local NewOutput = {}63local NewLength = 064local IndexAdd4096Sub16566for Index = 1, Length, 4096 do67NewLength = NewLength + 168IndexAdd4096Sub1 = Index + 4096 - 16970NewOutput[NewLength] = string.char(71table.unpack(Output, Index, IndexAdd4096Sub1 > Length and Length or IndexAdd4096Sub1)72)73end7475return table.concat(NewOutput)76end7778--[[**79Decodes a string from Base64.80@param [t:string] Input The input string to decode.81@returns [t:string] The newly decoded string.82**--]]83function Base64.Decode(Input)84local Output = {}85local Length = 08687for Index = 1, #Input, 4 do88local C1, C2, C3, C4 = string.byte(Input, Index, Index + 3)8990local I1 = Indexes[C1] - 191local I2 = Indexes[C2] - 192local I3 = (Indexes[C3] or 1) - 193local I4 = (Indexes[C4] or 1) - 19495local A = bit32_lshift(I1, 2) + bit32_rshift(I2, 4)96local B = bit32_lshift(bit32_band(I2, 15), 4) + bit32_rshift(I3, 2)97local C = bit32_lshift(bit32_band(I3, 3), 6) + I49899Length = Length + 1100Output[Length] = A101102if C3 ~= 61 then103Length = Length + 1104Output[Length] = B105end106107if C4 ~= 61 then108Length = Length + 1109Output[Length] = C110end111end112113local NewOutput = {}114local NewLength = 0115local IndexAdd4096Sub1116117for Index = 1, Length, 4096 do118NewLength = NewLength + 1119IndexAdd4096Sub1 = Index + 4096 - 1120121NewOutput[NewLength] = string.char(122table.unpack(Output, Index, IndexAdd4096Sub1 > Length and Length or IndexAdd4096Sub1)123)124end125126return table.concat(NewOutput)127end128129return Base64130131132