Software / code / verse
Comparison
libs/hashes.lua @ 389:bf3a4fcdcb76
libs.hashes: Wrap LuaCrypto with fallback to util.sha1
| author | Kim Alvefur <zash@zash.se> |
|---|---|
| date | Tue, 25 Aug 2015 15:45:23 +0200 |
| parent | 129:c0be31a5ff55 |
| child | 398:b4ce2e524ed8 |
comparison
equal
deleted
inserted
replaced
| 388:d963c8a5d89c | 389:bf3a4fcdcb76 |
|---|---|
| 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 > 20 then | |
| 39 key = sha1(key); | |
| 40 elseif #key < 20 then | |
| 41 key = key .. s_rep("\0", 20 - #key); | |
| 42 end | |
| 43 local o_key_pad, i_key_pad = {}, {} | |
| 44 for i = 1, 20 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 |