Comparison

util/jwt.lua @ 11561:d2f33b8fdc96

util.jwt: Use constant-time comparison with expected signature
author Matthew Wild <mwild1@gmail.com>
date Thu, 13 May 2021 14:13:07 +0100
parent 10660:c4ded3be7cc0
child 12696:27a72982e331
comparison
equal deleted inserted replaced
11560:3bbb1af92514 11561:d2f33b8fdc96
1 local s_gsub = string.gsub; 1 local s_gsub = string.gsub;
2 local json = require "util.json"; 2 local json = require "util.json";
3 local hashes = require "util.hashes"; 3 local hashes = require "util.hashes";
4 local base64_encode = require "util.encodings".base64.encode; 4 local base64_encode = require "util.encodings".base64.encode;
5 local base64_decode = require "util.encodings".base64.decode; 5 local base64_decode = require "util.encodings".base64.decode;
6 local secure_equals = require "util.hashes".equals;
6 7
7 local b64url_rep = { ["+"] = "-", ["/"] = "_", ["="] = "", ["-"] = "+", ["_"] = "/" }; 8 local b64url_rep = { ["+"] = "-", ["/"] = "_", ["="] = "", ["-"] = "+", ["_"] = "/" };
8 local function b64url(data) 9 local function b64url(data)
9 return (s_gsub(base64_encode(data), "[+/=]", b64url_rep)); 10 return (s_gsub(base64_encode(data), "[+/=]", b64url_rep));
10 end 11 end
31 if not header or type(header) ~= "table" then 32 if not header or type(header) ~= "table" then
32 return nil, "invalid-header"; 33 return nil, "invalid-header";
33 elseif header.alg ~= "HS256" then 34 elseif header.alg ~= "HS256" then
34 return nil, "unsupported-algorithm"; 35 return nil, "unsupported-algorithm";
35 end 36 end
36 if b64url(hashes.hmac_sha256(key, signed)) ~= signature then 37 if not secure_equals(b64url(hashes.hmac_sha256(key, signed)), signature) then
37 return false, "signature-mismatch"; 38 return false, "signature-mismatch";
38 end 39 end
39 local payload, err = json.decode(unb64url(bpayload)); 40 local payload, err = json.decode(unb64url(bpayload));
40 if err ~= nil then 41 if err ~= nil then
41 return nil, "json-decode-error"; 42 return nil, "json-decode-error";