libs/hashes.lua

Thu, 23 Mar 2023 18:56:32 +0000

author
Matthew Wild <mwild1@gmail.com>
date
Thu, 23 Mar 2023 18:56:32 +0000
changeset 485
c9a144591649
parent 484
5e2978489c95
permissions
-rw-r--r--

component: Avoid adding to the global stream metatable

This allows component and client connections to be made side-by-side.
Previous to this change, loading this connection module would break the
ability to make client connections, due to overriding stream methods such as
:reopen() and :reset().

A next step would be to share the methods that the two connection modules have
in common.


local function not_available(_, method_name)
	error("Hash method "..method_name.." not available", 2);
end

local _M = setmetatable({}, { __index = not_available });

local function with(mod, f)
	local ok, pkg = pcall(require, mod);
	if ok then f(pkg); end
end

local function to_hex(data)
	return (data:gsub(".", function (c)
		return ("%02x"):format(c:byte());
	end));
end

with("util.sha1", function (sha1)
	_M.sha1 = sha1.sha1;
end);

with("bgcrypto.md5", function (md5)
	_M.md5 = md5.digest;
	_M.hmac_md5 = md5.hmac.digest;
end);

with("bgcrypto.sha1", function (sha1)
	_M.sha1 = sha1.digest;
	_M.hmac_sha1 = sha1.hmac.digest;
	_M.scram_Hi_sha1 = function (p, s, i) return sha1.pbkdf2(p, s, i, 20); end;
end);

with("bgcrypto.sha256", function (sha256)
	_M.sha256 = sha256.digest;
	_M.hmac_sha256 = sha256.hmac.digest;
end);

with("bgcrypto.sha512", function (sha512)
	_M.sha512 = sha512.digest;
	_M.hmac_sha512 = sha512.hmac.digest;
end);

with("sha1", function (sha1)
	_M.sha1 = function (data, hex)
		if hex then
			return sha1.sha1(data);
		else
			return (sha1.binary(data));
		end
	end;
end);

with("openssl.digest", function (digest)
	local function make_digest_func(digest_name)
		return function (data, hex)
			local d = digest.new(digest_name):final(data);
			if hex then
				return to_hex(d);
			end
			return d;
		end;
	end
	_M.sha1 = make_digest_func("sha1");
end);

return _M;

mercurial