| 1 | local function not_available(_, method_name) |
| 2 | error("Hash method "..method_name.." not available", 2); |
| 3 | end |
| 4 | |
| 5 | local _M = setmetatable({}, { __index = not_available }); |
| 6 | |
| 7 | local function with(mod, f) |
| 8 | local ok, pkg = pcall(require, mod); |
| 9 | if ok then f(pkg); end |
| 10 | end |
| 11 | |
| 12 | local function to_hex(data) |
| 13 | return (data:gsub(".", function (c) |
| 14 | return ("%02x"):format(c:byte()); |
| 15 | end)); |
| 16 | end |
| 17 | |
| 18 | with("prosody.util.sha1", function (sha1) |
| 19 | _M.sha1 = sha1.sha1; |
| 20 | end); |
| 21 | |
| 22 | with("bgcrypto.md5", function (md5) |
| 23 | _M.md5 = md5.digest; |
| 24 | _M.hmac_md5 = md5.hmac.digest; |
| 25 | end); |
| 26 | |
| 27 | with("bgcrypto.sha1", function (sha1) |
| 28 | _M.sha1 = sha1.digest; |
| 29 | _M.hmac_sha1 = sha1.hmac.digest; |
| 30 | _M.scram_Hi_sha1 = function (p, s, i) return sha1.pbkdf2(p, s, i, 20); end; |
| 31 | end); |
| 32 | |
| 33 | with("bgcrypto.sha256", function (sha256) |
| 34 | _M.sha256 = sha256.digest; |
| 35 | _M.hmac_sha256 = sha256.hmac.digest; |
| 36 | end); |
| 37 | |
| 38 | with("bgcrypto.sha512", function (sha512) |
| 39 | _M.sha512 = sha512.digest; |
| 40 | _M.hmac_sha512 = sha512.hmac.digest; |
| 41 | end); |
| 42 | |
| 43 | with("sha1", function (sha1) |
| 44 | _M.sha1 = function (data, hex) |
| 45 | if hex then |
| 46 | return sha1.sha1(data); |
| 47 | else |
| 48 | return (sha1.binary(data)); |
| 49 | end |
| 50 | end; |
| 51 | end); |
| 52 | |
| 53 | with("openssl.digest", function (digest) |
| 54 | local function make_digest_func(digest_name) |
| 55 | return function (data, hex) |
| 56 | local d = digest.new(digest_name):final(data); |
| 57 | if hex then |
| 58 | return to_hex(d); |
| 59 | end |
| 60 | return d; |
| 61 | end; |
| 62 | end |
| 63 | _M.sha1 = make_digest_func("sha1"); |
| 64 | end); |
| 65 | |
| 66 | return _M; |