Skip to content

Add RS256 support #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions luajwt.lua
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,28 @@ local alg_sign = {
['HS256'] = function(data, key) return crypto.hmac.digest('sha256', data, key, true) end,
['HS384'] = function(data, key) return crypto.hmac.digest('sha384', data, key, true) end,
['HS512'] = function(data, key) return crypto.hmac.digest('sha512', data, key, true) end,
['RS256'] = function(data, key)
local privkey = crypto.pkey.from_pem(key, true)
if privkey == nil then
return nil, "Not a private PEM key"
else
return crypto.sign("sha256", data, privkey)
end
end
}

local alg_verify = {
['HS256'] = function(data, signature, key) return signature == alg_sign['HS256'](data, key) end,
['HS384'] = function(data, signature, key) return signature == alg_sign['HS384'](data, key) end,
['HS512'] = function(data, signature, key) return signature == alg_sign['HS512'](data, key) end,
['RS256'] = function(data, signature, key)
local pubkey = crypto.pkey.from_pem(key)
if pubkey == nil then
return nil, "Not a public PEM key"
else
return crypto.verify("sha256", data, signature, pubkey)
end
end
}

local function b64_encode(input)
Expand Down Expand Up @@ -77,8 +93,10 @@ function M.encode(data, key, alg)
}

local signing_input = table.concat(segments, ".")

local signature = alg_sign[alg](signing_input, key)
local signature, error = alg_sign[alg](signing_input, key)
if signature == nil then
return nil, error
end

segments[#segments+1] = b64_encode(signature)

Expand Down Expand Up @@ -131,7 +149,11 @@ function M.decode(data, key, verify)
return nil, "Algorithm not supported"
end

if not alg_verify[header.alg](headerb64 .. "." .. bodyb64, sig, key) then
local verify_result, error
= alg_verify[header.alg](headerb64 .. "." .. bodyb64, sig, key);
if verify_result == nil then
return nil, error
elseif verify_result == false then
return nil, "Invalid signature"
end

Expand Down