From 2764dbb5fcd30084b2aa0be40e7a5e4f4733d94e Mon Sep 17 00:00:00 2001 From: Wangchong Zhou Date: Mon, 6 Nov 2023 18:18:25 +0800 Subject: [PATCH] fix(jwk) return error if exporting private key from public key --- lib/resty/openssl/auxiliary/jwk.lua | 4 ++++ t/openssl/aux/jwk.t | 37 ++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/lib/resty/openssl/auxiliary/jwk.lua b/lib/resty/openssl/auxiliary/jwk.lua index 5a505a93..a6518cda 100644 --- a/lib/resty/openssl/auxiliary/jwk.lua +++ b/lib/resty/openssl/auxiliary/jwk.lua @@ -202,6 +202,10 @@ end function _M.dump_jwk(pkey, is_priv) local jwk + if is_priv and not pkey:is_private() then + return nil, "jwk.dump_jwk: could not dump public key as private key" + end + if pkey.key_type == evp_macro.EVP_PKEY_RSA then local param_keys = { "n" , "e" } if is_priv then diff --git a/t/openssl/aux/jwk.t b/t/openssl/aux/jwk.t index 63346fe5..d7077927 100644 --- a/t/openssl/aux/jwk.t +++ b/t/openssl/aux/jwk.t @@ -225,4 +225,39 @@ true 'pkey.new:load_key: failed to construct OKP key from JWK: at least "x" or "d" parameter is required ' --- no_error_log -[error] \ No newline at end of file +[error] + +=== TEST 4: Errors if tries to export privkey using pubkey +--- http_config eval: $e:HttpConfig +--- config + location =/t { + content_by_lua_block { + local privkey, err = require("resty.openssl.pkey").new({ type = 'EC', curve = 'prime256v1'}) + if err then + ngx.log(ngx.ERR, err) + return + end + + local pem, err = privkey:tostring("public") + if err then + ngx.log(ngx.ERR, err) + return + end + + local pubkey, err = require("resty.openssl.pkey").new(pem) + if err then + ngx.log(ngx.ERR, err) + return + end + + local _, err = pubkey:tostring("private", "JWK") + print(err) + } + } +--- request + GET /t +--- response_body eval +'jwk.dump_jwk: could not dump public key as private key +' +--- no_error_log +[error]