-
Notifications
You must be signed in to change notification settings - Fork 29
/
base64.lua
91 lines (69 loc) · 2.45 KB
/
base64.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
-- Base64-encoding
-- Sourced from http://en.wikipedia.org/wiki/Base64
local __author__ = 'Daniel Lindsley'
local __version__ = 'scm-1'
local __license__ = 'BSD'
local index_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
function to_binary(integer)
local remaining = tonumber(integer)
local bin_bits = ''
for i = 7, 0, -1 do
local current_power = 2 ^ i
if remaining >= current_power then
bin_bits = bin_bits .. '1'
remaining = remaining - current_power
else
bin_bits = bin_bits .. '0'
end
end
return bin_bits
end
function from_binary(bin_bits)
return tonumber(bin_bits, 2)
end
function to_base64(to_encode)
local bit_pattern = ''
local encoded = ''
local trailing = ''
for i = 1, string.len(to_encode) do
bit_pattern = bit_pattern .. to_binary(string.byte(string.sub(to_encode, i, i)))
end
-- Check the number of bytes. If it's not evenly divisible by three,
-- zero-pad the ending & append on the correct number of ``=``s.
if string.len(bit_pattern) % 3 == 2 then
trailing = '=='
bit_pattern = bit_pattern .. '0000000000000000'
elseif string.len(bit_pattern) % 3 == 1 then
trailing = '='
bit_pattern = bit_pattern .. '00000000'
end
for i = 1, string.len(bit_pattern), 6 do
local byte = string.sub(bit_pattern, i, i+5)
local offset = tonumber(from_binary(byte))
encoded = encoded .. string.sub(index_table, offset+1, offset+1)
end
return string.sub(encoded, 1, -1 - string.len(trailing)) .. trailing
end
function from_base64(to_decode)
local padded = to_decode:gsub("%s", "")
local unpadded = padded:gsub("=", "")
local bit_pattern = ''
local decoded = ''
for i = 1, string.len(unpadded) do
local char = string.sub(to_decode, i, i)
local offset, _ = string.find(index_table, char)
if offset == nil then
error("Invalid character '" .. char .. "' found.")
end
bit_pattern = bit_pattern .. string.sub(to_binary(offset-1), 3)
end
for i = 1, string.len(bit_pattern), 8 do
local byte = string.sub(bit_pattern, i, i+7)
decoded = decoded .. string.char(from_binary(byte))
end
local padding_length = padded:len()-unpadded:len()
if (padding_length == 1 or padding_length == 2) then
decoded = decoded:sub(1,-2)
end
return decoded
end