hmac: NGINX模块Lua和LuaJIT的HMAC函数
安装
如果您尚未设置RPM仓库订阅,请 注册。然后您可以继续以下步骤。
CentOS/RHEL 7或Amazon Linux 2
yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install lua-resty-hmac
CentOS/RHEL 8+、Fedora Linux、Amazon Linux 2023
dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install lua5.1-resty-hmac
要在NGINX中使用此Lua库,请确保已安装 nginx-module-lua。
本文档描述了lua-resty-hmac v0.6,于2023年5月31日发布。
该库需要一个带有OpenSSL的nginx构建, ngx_lua模块 和 LuaJIT 2.0。
概述
# nginx.conf:
server {
location = /test {
content_by_lua_file conf/test.lua;
}
}
-- conf/test.lua:
local hmac = require "resty.hmac"
local hmac_sha1 = hmac:new("secret_key", hmac.ALGOS.SHA1)
if not hmac_sha1 then
ngx.say("创建hmac_sha1对象失败")
return
end
local ok = hmac_sha1:update("he")
if not ok then
ngx.say("添加数据失败")
return
end
ok = hmac_sha1:update("llo")
if not ok then
ngx.say("添加数据失败")
return
end
local mac = hmac_sha1:final() -- 二进制mac
local str = require "resty.string"
ngx.say("hmac_sha1: ", str.to_hex(mac))
-- 输出: "hmac_sha1: aee4b890b574ea8fa4f6a66aed96c3e590e5925a"
-- 最后调用后不要忘记重置!
if not hmac_sha1:reset() then
ngx.say("重置hmac_sha1失败")
return
end
-- 简短版本
ngx.say("hmac_sha1: ", hmac_sha1:final("world", true))
-- 输出: "hmac_sha1: 4e9538f1efbe565c522acfb72fce6092ea6b15e0"
方法
要加载此库,
- 您需要在ngx_lua的 lua_package_path 指令中指定此库的路径。例如,
lua_package_path "/path/to/lua-resty-hmac/lib/?.lua;;";。 - 您使用
require将库加载到一个本地Lua变量中:
local hmac = require "resty.hmac"
new
语法: local hmac_sha256 = hmac:new(key [, hash_algorithm])
创建一个新的hmac实例。如果失败,返回 nil。
key 参数指定在计算消息认证码(MAC)时使用的密钥。key 是一个Lua字符串,可以包含可打印字符或二进制数据。
hash_algorithm 参数指定要使用的哈希算法(hmac.ALGOS.MD5、hmac.ALGOS.SHA1、hmac.ALGOS.SHA256、hmac.ALGOS.SHA512)。默认值为 hmac.ALGOS.MD5。
update
语法: hmac_sha256:update(data)
更新MAC计算以包含新数据。如果失败,返回 false。
data 参数指定要包含在MAC中的附加数据。data 是一个Lua字符串,可以包含可打印字符或二进制数据。
final
语法: local mac = hmac_sha256:final([data, output_hex])
完成MAC计算并返回最终的MAC值。如果失败,返回 nil。当 output_hex 不是 true 时,返回一个包含原始二进制MAC的Lua字符串。当 output_hex 是 true 时,返回一个包含MAC的十六进制表示的Lua字符串。
data 参数指定在完成计算之前要包含在MAC中的附加数据。默认值为 nil。
output_hex 参数指定MAC是否应以十六进制或二进制形式返回。如果为 true,则MAC将以十六进制形式返回。默认值为 false。
reset
语法: hmac_sha256:reset()
重置内部hmac上下文,以便可以重新使用它计算新的MAC。如果失败,返回 false。如果成功,key 和 hash_algorithm 保持不变,但所有其他信息将被清除。
这必须在 hmac_sha256:final() 之后调用,以便使用相同的hmac实例计算新的MAC。
先决条件
- LuaJIT 2.0+
- ngx_lua模块
- lua-resty-string 0.8+
- OpenSSL 1.0.0+
另见
- ngx_lua模块: http://wiki.nginx.org/HttpLuaModule
GitHub
您可以在 nginx-module-hmac的GitHub仓库中找到此模块的其他配置提示和文档。