diff --git a/src/openssl.c b/src/openssl.c index 3d370ad..b2bfbae 100644 --- a/src/openssl.c +++ b/src/openssl.c @@ -29,7 +29,7 @@ #include /* INT_MAX INT_MIN LLONG_MAX LLONG_MIN UCHAR_MAX ULLONG_MAX */ #include /* uintptr_t */ -#include /* memset(3) strerror_r(3) */ +#include /* memset(3) strerror_r(3) strlen(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) */ @@ -3947,7 +3947,20 @@ static int pk_toPEM(lua_State *L) { static int pk_getPrivateKey(lua_State *L) { - if (!PEM_write_bio_PrivateKey(getbio(L), checksimple(L, 1, PKEY_CLASS), 0, 0, 0, 0, 0)) + EVP_PKEY *key = checksimple(L, 1, PKEY_CLASS); + const char *cname; + const char *pass = NULL; + EVP_CIPHER *cipher = NULL; + + if (lua_gettop(L) > 1) { + cname = luaL_checkstring(L, 2); + pass = luaL_checkstring(L, 3); + cipher = EVP_get_cipherbyname(cname); + if (!cipher) + return luaL_error(L, "pkey:getPrivateKey: unknown cipher: %s", cname); + } + + if (!PEM_write_bio_PrivateKey(getbio(L), key, cipher, pass, pass ? strlen(pass) : 0, 0, 0)) return auxL_error(L, auxL_EOPENSSL, "pkey:getPrivateKey"); pushbiostring(L); return 1;