Skip to content

Commit 081d2fa

Browse files
wzxjohnzhuizhuhaomeng
authored andcommitted
feat: add AAD support in aes gcm
1 parent 86aada5 commit 081d2fa

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

lib/resty/aes.lua

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ function _M.new(self, key, salt, _cipher, _hash, hash_rounds, iv_len, enable_pad
224224
end
225225

226226

227-
function _M.encrypt(self, s)
227+
function _M.encrypt(self, s, aad)
228228
local typ = type(self)
229229
if typ ~= "table" then
230230
error("bad argument #1 self: table expected, got " .. typ, 2)
@@ -241,6 +241,12 @@ function _M.encrypt(self, s)
241241
return nil, "EVP_EncryptInit_ex failed"
242242
end
243243

244+
if self._cipher == "gcm" and aad ~= nil then
245+
if C.EVP_EncryptUpdate(ctx, nil, tmp_len, aad, #aad) == 0 then
246+
return nil, "C.EVP_EncryptUpdate failed"
247+
end
248+
end
249+
244250
if C.EVP_EncryptUpdate(ctx, buf, out_len, s, s_len) == 0 then
245251
return nil, "EVP_EncryptUpdate failed"
246252
end
@@ -267,7 +273,7 @@ function _M.encrypt(self, s)
267273
end
268274

269275

270-
function _M.decrypt(self, s, tag)
276+
function _M.decrypt(self, s, tag, aad)
271277
local typ = type(self)
272278
if typ ~= "table" then
273279
error("bad argument #1 self: table expected, got " .. typ, 2)
@@ -284,6 +290,12 @@ function _M.decrypt(self, s, tag)
284290
return nil, "EVP_DecryptInit_ex failed"
285291
end
286292

293+
if self._cipher == "gcm" and aad ~= nil then
294+
if C.EVP_DecryptUpdate(ctx, nil, tmp_len, aad, #aad) == 0 then
295+
return nil, "C.EVP_DecryptUpdate failed"
296+
end
297+
end
298+
287299
if C.EVP_DecryptUpdate(ctx, buf, out_len, s, s_len) == 0 then
288300
return nil, "EVP_DecryptUpdate failed"
289301
end

t/aes.t

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -561,3 +561,29 @@ AES-256 CBC (custom keygen, without user padding, enable padding) HEX: 794617717
561561
true
562562
--- no_error_log
563563
[error]
564+
565+
566+
567+
=== TEST 18: AES-256 GCM sha256 no salt with AAD
568+
--- http_config eval: $::HttpConfig
569+
--- config
570+
location /t {
571+
content_by_lua_block {
572+
local aes = require "resty.aes"
573+
local str = require "resty.string"
574+
local aes_default = aes:new("secret",nil,
575+
aes.cipher(256,"gcm"), aes.hash.sha256, 1, 12)
576+
local encrypted = aes_default:encrypt("hello", "aad")
577+
ngx.say("AES-256 GCM: ", str.to_hex(encrypted[1]),
578+
" tag: ", str.to_hex(encrypted[2]))
579+
local decrypted, err = aes_default:decrypt(encrypted[1], encrypted[2], "aad")
580+
ngx.say(decrypted == "hello")
581+
}
582+
}
583+
--- request
584+
GET /t
585+
--- response_body
586+
AES-256 GCM: 4acef84443 tag: 46f4f3ca65395568407e15768b7526d9
587+
true
588+
--- no_error_log
589+
[error]

0 commit comments

Comments
 (0)