Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 36 additions & 8 deletions vendor/resty/hmac.lua
Original file line number Diff line number Diff line change
@@ -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 }

Expand Down Expand Up @@ -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);

Expand All @@ -75,30 +82,51 @@ 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(),
SHA256 = C.EVP_sha256(),
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

if C.HMAC_Init_ex(ctx, key, #key, _hash_algo, nil) == 0 then
return nil
end

ffi_gc(ctx, C.HMAC_CTX_cleanup)
ffi_gc(ctx, ctx_free)

return setmetatable({ _ctx = ctx }, mt)
end
Expand All @@ -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
Expand Down