Software /
code /
verse
Comparison
libs/hashes.lua @ 399:82ad158714e5
Merge with Zash
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Tue, 12 Jan 2016 13:14:36 +0000 |
parent | 398:b4ce2e524ed8 |
child | 414:2a5eff919f4a |
comparison
equal
deleted
inserted
replaced
378:6042c938e369 | 399:82ad158714e5 |
---|---|
1 local sha1 = require "util.sha1"; | 1 local have_luacrypto, crypto = pcall(require, "crypto"); |
2 | 2 |
3 return { sha1 = sha1.sha1 }; | 3 if have_luacrypto then |
4 local hashes = {}; | |
5 | |
6 local digest = crypto.digest; | |
7 local function gethash(algo) | |
8 return function (string, hex) | |
9 return digest(algo, string, not hex); | |
10 end | |
11 end | |
12 | |
13 local hmac = crypto.hmac.digest; | |
14 local function gethmac(algo) | |
15 return function (key, message, hex) | |
16 return hmac(algo, message, key, not hex); | |
17 end | |
18 end | |
19 | |
20 local hash_algos = { "md5", "sha1", "sha256", "sha512" }; | |
21 | |
22 for _, hash_algo in ipairs(hash_algos) do | |
23 hashes[hash_algo] = gethash(hash_algo); | |
24 hashes["hmac_"..hash_algo] = gethmac(hash_algo); | |
25 end | |
26 | |
27 return hashes; | |
28 else | |
29 local sha1 = require"util.sha1".sha1; | |
30 local bxor = require"bit".bxor; | |
31 | |
32 local s_rep = string.rep; | |
33 local s_char = string.char; | |
34 local s_byte = string.byte; | |
35 local t_concat = table.concat; | |
36 | |
37 local function hmac_sha1(key, message, hexres) | |
38 if #key > 64 then | |
39 key = sha1(key); | |
40 elseif #key < 64 then | |
41 key = key .. s_rep("\0", 64 - #key); | |
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 | |
54 return { | |
55 sha1 = sha1; | |
56 hmac_sha1 = hmac_sha1; | |
57 }; | |
58 end |