diff --git a/vendor/resty/hmac.lua b/vendor/resty/hmac.lua index efb3b3b..1c4fa83 100644 --- a/vendor/resty/hmac.lua +++ b/vendor/resty/hmac.lua @@ -1,15 +1,17 @@ local str_util = require "resty.string" +local to_hex = str_util.to_hex local ffi = require "ffi" local ffi_new = ffi.new local ffi_str = ffi.string local ffi_gc = ffi.gc +local ffi_typeof = ffi.typeof local C = ffi.C local setmetatable = setmetatable local error = error -local _M = { _VERSION = '0.01' } +local _M = { _VERSION = '0.02' } local mt = { __index = _M } @@ -60,10 +62,15 @@ typedef struct hmac_ctx_st unsigned char key[128]; } HMAC_CTX; +//OpenSSL 1.0 void HMAC_CTX_init(HMAC_CTX *ctx); void HMAC_CTX_cleanup(HMAC_CTX *ctx); -int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int len,const EVP_MD *md, ENGINE *impl); +//OpenSSL 1.1 +HMAC_CTX *HMAC_CTX_new(void); +void HMAC_CTX_free(HMAC_CTX *ctx); + +int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int len, const EVP_MD *md, ENGINE *impl); int HMAC_Update(HMAC_CTX *ctx, const unsigned char *data, size_t len); int HMAC_Final(HMAC_CTX *ctx, unsigned char *md, unsigned int *len); @@ -75,7 +82,7 @@ const EVP_MD *EVP_sha512(void); local buf = ffi_new("unsigned char[64]") local res_len = ffi_new("unsigned int[1]") -local ctx_ptr_type = ffi.typeof("HMAC_CTX[1]") +local ctx_ptr_type = ffi_typeof("HMAC_CTX[1]") local hashes = { MD5 = C.EVP_md5(), SHA1 = C.EVP_sha1(), @@ -83,14 +90,35 @@ local hashes = { SHA512 = C.EVP_sha512() } +local ctx_new, ctx_free +local openssl11, e = pcall(function () + local ctx = C.HMAC_CTX_new() + C.HMAC_CTX_free(ctx) +end) +if openssl11 then + ctx_new = function () + return C.HMAC_CTX_new() + end + ctx_free = function (ctx) + C.HMAC_CTX_free(ctx) + end +else + ctx_new = function () + local ctx = ffi_new(ctx_ptr_type) + C.HMAC_CTX_init(ctx) + return ctx + end + ctx_free = function (ctx) + C.HMAC_CTX_cleanup(ctx) + end +end + _M.ALGOS = hashes function _M.new(self, key, hash_algo) - local ctx = ffi_new(ctx_ptr_type) - - C.HMAC_CTX_init(ctx) + local ctx = ctx_new() local _hash_algo = hash_algo or hashes.md5 @@ -98,7 +126,7 @@ function _M.new(self, key, hash_algo) return nil end - ffi_gc(ctx, C.HMAC_CTX_cleanup) + ffi_gc(ctx, ctx_free) return setmetatable({ _ctx = ctx }, mt) end @@ -119,7 +147,7 @@ function _M.final(self, s, hex_output) if C.HMAC_Final(self._ctx, buf, res_len) == 1 then if hex_output == true then - return str_util.to_hex(ffi_str(buf, res_len[0])) + return to_hex(ffi_str(buf, res_len[0])) end return ffi_str(buf, res_len[0]) end