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) */
@@ -3403,11 +3403,20 @@ static BIO *getbio(lua_State *L) {
34033403} /* getbio() */
34043404
34053405
3406+ static int pem_pw_cb (char * buf , int size , int rwflag , void * u ) {
3407+ if (!u )
3408+ return 0 ;
3409+ char * pass = (char * ) u ;
3410+ strncpy (buf , pass , size );
3411+ return MIN (strlen (pass ), (unsigned int ) size );
3412+ } /* pem_password_cb() */
3413+
3414+
34063415static int pk_new (lua_State * L ) {
34073416 EVP_PKEY * * ud ;
34083417
3409- /* #1 table or key; if key, #2 format and #3 type */
3410- lua_settop (L , 3 );
3418+ /* #1 table or key; if key, #2 format, #3 type and #4 password */
3419+ lua_settop (L , 4 );
34113420
34123421 if (lua_istable (L , 1 ) || lua_isnil (L , 1 )) {
34133422 int type = EVP_PKEY_RSA ;
@@ -3613,7 +3622,7 @@ static int pk_new(lua_State *L) {
36133622 } else if (lua_isstring (L , 1 )) {
36143623 int type = optencoding (L , 2 , "*" , X509_ANY |X509_PEM |X509_DER );
36153624 int pubonly = 0 , prvtonly = 0 ;
3616- const char * opt , * data ;
3625+ const char * opt , * data , * pass ;
36173626 size_t len ;
36183627 BIO * bio ;
36193628 EVP_PKEY * pub = NULL , * prvt = NULL ;
@@ -3631,6 +3640,7 @@ static int pk_new(lua_State *L) {
36313640 }
36323641
36333642 data = luaL_checklstring (L , 1 , & len );
3643+ pass = luaL_optstring (L , 4 , NULL );
36343644
36353645 ud = prepsimple (L , PKEY_CLASS );
36363646
@@ -3646,14 +3656,14 @@ static int pk_new(lua_State *L) {
36463656 */
36473657 BIO_reset (bio );
36483658
3649- if (!(pub = PEM_read_bio_PUBKEY (bio , NULL , 0 , "" )))
3659+ if (!(pub = PEM_read_bio_PUBKEY (bio , NULL , pem_pw_cb , pass )))
36503660 goterr = 1 ;
36513661 }
36523662
36533663 if (!pubonly && !prvt ) {
36543664 BIO_reset (bio );
36553665
3656- if (!(prvt = PEM_read_bio_PrivateKey (bio , NULL , 0 , "" )))
3666+ if (!(prvt = PEM_read_bio_PrivateKey (bio , NULL , pem_pw_cb , pass )))
36573667 goterr = 1 ;
36583668 }
36593669 }
0 commit comments