1 local have_luacrypto, crypto = pcall(require, "crypto"); |
|
2 |
1 |
3 if have_luacrypto then |
2 local function not_available() |
4 local hashes = {}; |
3 error("not available", 2); |
|
4 end |
5 |
5 |
6 local digest = crypto.digest; |
6 local _M = { |
7 local function gethash(algo) |
7 md5 = not_available; |
8 return function (string, hex) |
8 hmac_md5 = not_available; |
9 return digest(algo, string, not hex); |
|
10 end |
|
11 end |
|
12 |
9 |
13 local hmac = crypto.hmac.digest; |
10 sha1 = not_available; |
14 local function gethmac(algo) |
11 hmac_sha1 = not_available; |
15 return function (key, message, hex) |
12 scram_Hi_sha1 = not_available; |
16 return hmac(algo, message, key, not hex); |
|
17 end |
|
18 end |
|
19 |
13 |
20 local hash_algos = { "md5", "sha1", "sha256", "sha512" }; |
14 sha256 = not_available; |
|
15 hmac_sha256 = not_available; |
21 |
16 |
22 for _, hash_algo in ipairs(hash_algos) do |
17 sha512 = not_available; |
23 hashes[hash_algo] = gethash(hash_algo); |
18 hmac_sha512 = not_available; |
24 hashes["hmac_"..hash_algo] = gethmac(hash_algo); |
19 }; |
25 end |
|
26 |
20 |
27 return hashes; |
21 local function with(mod, f) |
28 else |
22 local ok, pkg = pcall(require, mod); |
29 local sha1 = require"util.sha1".sha1; |
23 if ok then f(pkg); end |
30 local bxor = require"bit".bxor; |
24 end |
31 |
25 |
32 local s_rep = string.rep; |
26 with("bgcrypto.md5", function (md5) |
33 local s_char = string.char; |
27 _M.md5 = md5.digest; |
34 local s_byte = string.byte; |
28 _M.hmac_md5 = md5.hmac.digest; |
35 local t_concat = table.concat; |
29 end); |
36 |
30 |
37 local function hmac_sha1(key, message, hexres) |
31 with("bgcrypto.sha1", function (sha1) |
38 if #key > 64 then |
32 _M.sha1 = sha1.digest; |
39 key = sha1(key); |
33 _M.hmac_sha1 = sha1.hmac.digest; |
40 elseif #key < 64 then |
34 _M.scram_Hi_sha1 = function (p, s, i) return sha1.pbkdf2(p, s, i, 20); end; |
41 key = key .. s_rep("\0", 64 - #key); |
35 end); |
42 end |
|
43 local o_key_pad, i_key_pad = {}, {} |
|
44 for i = 1, 64 do |
|
45 local b = s_byte(key, i) |
|
46 o_key_pad[i] = s_char(bxor(b, 0x5c)); |
|
47 i_key_pad[i] = s_char(bxor(b, 0x36)); |
|
48 end |
|
49 o_key_pad = t_concat(o_key_pad); |
|
50 i_key_pad = t_concat(i_key_pad); |
|
51 return sha1(o_key_pad .. sha1(i_key_pad .. message), hexres); |
|
52 end |
|
53 |
36 |
54 return { |
37 with("bgcrypto.sha256", function (sha256) |
55 sha1 = sha1; |
38 _M.sha256 = sha256.digest; |
56 hmac_sha1 = hmac_sha1; |
39 _M.hmac_sha256 = sha256.hmac.digest; |
57 }; |
40 end); |
58 end |
41 |
|
42 with("bgcrypto.sha512", function (sha512) |
|
43 _M.sha512 = sha512.digest; |
|
44 _M.hmac_sha512 = sha512.hmac.digest; |
|
45 end); |
|
46 |
|
47 return _M; |