aboutsummaryrefslogtreecommitdiffstats
path: root/server/resty/session/encoders/base64.lua
blob: ddaf4e82f96b9445d74f53cc82545565f2655522 (plain)
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
local encode_base64 = ngx.encode_base64
local decode_base64 = ngx.decode_base64

local gsub = string.gsub

local ENCODE_CHARS = {
    ["+"] = "-",
    ["/"] = "_",
}

local DECODE_CHARS = {
    ["-"] = "+",
    ["_"] = "/",
}

local encoder = {}

function encoder.encode(value)
    if not value then
        return nil, "unable to base64 encode value"
    end

    local encoded = encode_base64(value, true)
    if not encoded then
        return nil, "unable to base64 encode value"
    end

    return gsub(encoded, "[+/]", ENCODE_CHARS)
end

function encoder.decode(value)
    if not value then
        return nil, "unable to base64 decode value"
    end

    return decode_base64((gsub(value, "[-_]", DECODE_CHARS)))
end

return encoder