-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathbase64.lua
More file actions
43 lines (36 loc) · 814 Bytes
/
base64.lua
File metadata and controls
43 lines (36 loc) · 814 Bytes
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
--
-- base64.lua
--
-- URL safe base64 encoder/decoder
--
-- https://github.com/diegonehab/luasocket
local mime = require 'mime'
local _M = {}
--- base64 encoder
--
-- @param s String to encode (can be binary data)
-- @return Encoded string
function _M.encode(s)
local u
local padding_len = 2 - ((#s-1) % 3)
if padding_len > 0 then
u = mime.b64(s):sub(1, - padding_len - 1)
else
u = mime.b64(s)
end
if u then
return u:gsub('[+]', '-'):gsub('[/]', '_')
else
return nil
end
end
--- base64 decoder
--
-- @param s String to decode
-- @return Decoded string (can be binary data)
function _M.decode(s)
local e = s:gsub('[-]', '+'):gsub('[_]', '/')
local u, _ = mime.unb64(e .. string.rep('=', 3 - ((#s - 1) % 4)))
return u
end
return _M