From a97094ecf78bdc8ae2cadeaa877b23689e873342 Mon Sep 17 00:00:00 2001 From: Kaarle Ritvanen Date: Mon, 30 Apr 2018 13:49:57 +0300 Subject: [PATCH 3/5] pkey.new: decryption --- src/openssl.c | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/openssl.c b/src/openssl.c index a32dd1a..2e6d802 100644 --- a/src/openssl.c +++ b/src/openssl.c @@ -31,7 +31,7 @@ #include /* INT_MAX INT_MIN LLONG_MAX LLONG_MIN UCHAR_MAX ULLONG_MAX */ #include /* uintptr_t */ -#include /* memset(3) strerror_r(3) strlen(3) */ +#include /* memset(3) strerror_r(3) strlen(3) strncpy(3) */ #include /* INFINITY fabs(3) floor(3) frexp(3) fmod(3) round(3) isfinite(3) */ #include /* struct tm time_t strptime(3) time(2) */ #include /* isdigit(3), isxdigit(3), tolower(3) */ @@ -3427,11 +3427,20 @@ static BIO *getbio(lua_State *L) { } /* getbio() */ +static int pem_pw_cb(char *buf, int size, int rwflag, void *u) { + if (!u) + return 0; + char *pass = (char *) u; + strncpy(buf, pass, size); + return MIN(strlen(pass), (unsigned int) size); +} /* pem_pw_cb() */ + + static int pk_new(lua_State *L) { EVP_PKEY **ud; - /* #1 table or key; if key, #2 format and #3 type */ - lua_settop(L, 3); + /* #1 table or key; if key, #2 format, #3 type and #4 password */ + lua_settop(L, 4); if (lua_istable(L, 1) || lua_isnil(L, 1)) { int type = EVP_PKEY_RSA; @@ -3637,7 +3646,7 @@ static int pk_new(lua_State *L) { } else if (lua_isstring(L, 1)) { int type = optencoding(L, 2, "*", X509_ANY|X509_PEM|X509_DER); int pubonly = 0, prvtonly = 0; - const char *opt, *data; + const char *opt, *data, *pass; size_t len; BIO *bio; EVP_PKEY *pub = NULL, *prvt = NULL; @@ -3655,6 +3664,7 @@ static int pk_new(lua_State *L) { } data = luaL_checklstring(L, 1, &len); + pass = luaL_optstring(L, 4, NULL); ud = prepsimple(L, PKEY_CLASS); @@ -3670,14 +3680,14 @@ static int pk_new(lua_State *L) { */ BIO_reset(bio); - if (!(pub = PEM_read_bio_PUBKEY(bio, NULL, 0, ""))) + if (!(pub = PEM_read_bio_PUBKEY(bio, NULL, pem_pw_cb, pass))) goterr = 1; } if (!pubonly && !prvt) { BIO_reset(bio); - if (!(prvt = PEM_read_bio_PrivateKey(bio, NULL, 0, ""))) + if (!(prvt = PEM_read_bio_PrivateKey(bio, NULL, pem_pw_cb, pass))) goterr = 1; } } -- 2.18.0