3131
3232#include <limits.h> /* INT_MAX INT_MIN LLONG_MAX LLONG_MIN UCHAR_MAX ULLONG_MAX */
3333#include <stdint.h> /* uintptr_t */
34- #include <string.h> /* memset(3) strerror_r(3) strlen(3) */
34+ #include <string.h> /* memset(3) strerror_r(3) strlen(3) strncpy(3) */
3535#include <math.h> /* INFINITY fabs(3) floor(3) frexp(3) fmod(3) round(3) isfinite(3) */
3636#include <time.h> /* struct tm time_t strptime(3) time(2) */
3737#include <ctype.h> /* isdigit(3), isxdigit(3), tolower(3) */
@@ -4062,6 +4062,15 @@ static BIO *getbio(lua_State *L) {
40624062} /* getbio() */
40634063
40644064
4065+ static int pem_pw_cb (char * buf , int size , int rwflag , void * u ) {
4066+ if (!u )
4067+ return 0 ;
4068+ char * pass = (char * ) u ;
4069+ strncpy (buf , pass , size );
4070+ return MIN (strlen (pass ), (unsigned int ) size );
4071+ } /* pem_pw_cb() */
4072+
4073+
40654074static int pk_new (lua_State * L ) {
40664075 EVP_PKEY * * ud ;
40674076
@@ -4301,7 +4310,7 @@ static int pk_new(lua_State *L) {
43014310 } else if (lua_isstring (L , 1 )) {
43024311 int format ;
43034312 int pubonly = 0 , prvtonly = 0 ;
4304- const char * type , * data ;
4313+ const char * type , * data , * pass ;
43054314 size_t len ;
43064315 BIO * bio ;
43074316 EVP_PKEY * pub = NULL , * prvt = NULL ;
@@ -4311,10 +4320,12 @@ static int pk_new(lua_State *L) {
43114320 lua_pop (L , 1 );
43124321 lua_getfield (L , 2 , "format" );
43134322 lua_getfield (L , 2 , "type" );
4323+ lua_getfield (L , 2 , "password" );
43144324 lua_remove (L , 2 );
4315- }
4325+ } else
4326+ lua_pushnil (L );
43164327
4317- /* #1 key, #2 format, #3 type */
4328+ /* #1 key, #2 format, #3 type, #4 password or callback */
43184329
43194330 data = luaL_checklstring (L , 1 , & len );
43204331 format = optencoding (L , 2 , "*" , X509_ANY |X509_PEM |X509_DER );
@@ -4330,6 +4341,13 @@ static int pk_new(lua_State *L) {
43304341 }
43314342 }
43324343
4344+ pass = luaL_optstring (L , 4 , NULL );
4345+ if (pass ) {
4346+ if (format == X509_DER )
4347+ return luaL_error (L , "decryption supported only for PEM keys" );
4348+ else format = X509_PEM ;
4349+ }
4350+
43334351 ud = prepsimple (L , PKEY_CLASS );
43344352
43354353 if (!(bio = BIO_new_mem_buf ((void * )data , len )))
@@ -4344,14 +4362,14 @@ static int pk_new(lua_State *L) {
43444362 */
43454363 BIO_reset (bio );
43464364
4347- if (!(pub = PEM_read_bio_PUBKEY (bio , NULL , 0 , "" )))
4365+ if (!(pub = PEM_read_bio_PUBKEY (bio , NULL , pem_pw_cb , pass )))
43484366 goterr = 1 ;
43494367 }
43504368
43514369 if (!pubonly && !prvt ) {
43524370 BIO_reset (bio );
43534371
4354- if (!(prvt = PEM_read_bio_PrivateKey (bio , NULL , 0 , "" )))
4372+ if (!(prvt = PEM_read_bio_PrivateKey (bio , NULL , pem_pw_cb , pass )))
43554373 goterr = 1 ;
43564374 }
43574375 }
0 commit comments