| 1 | From 2f246ccfaba1c7a83274157ef917c0c169810d49 Mon Sep 17 00:00:00 2001
|
| 2 | From: Kaarle Ritvanen <[email protected]>
|
| 3 | Date: Mon, 30 Apr 2018 13:26:16 +0300
|
| 4 | Subject: [PATCH 3/9] pkey.toPEM: private key encryption
|
| 5 |
|
| 6 | ---
|
| 7 | src/openssl.c | 25 +++++++++++++++++++------
|
| 8 | 1 file changed, 19 insertions(+), 6 deletions(-)
|
| 9 |
|
| 10 | diff --git a/src/openssl.c b/src/openssl.c
|
| 11 | index 6df0a17..9432407 100644
|
| 12 | |
| 13 | |
| 14 | @@ -31,7 +31,7 @@
|
| 15 |
|
| 16 | #include <limits.h> /* INT_MAX INT_MIN LLONG_MAX LLONG_MIN UCHAR_MAX ULLONG_MAX */
|
| 17 | #include <stdint.h> /* uintptr_t */
|
| 18 | -#include <string.h> /* memset(3) strerror_r(3) */
|
| 19 | +#include <string.h> /* memset(3) strerror_r(3) strlen(3) */
|
| 20 | #include <math.h> /* INFINITY fabs(3) floor(3) frexp(3) fmod(3) round(3) isfinite(3) */
|
| 21 | #include <time.h> /* struct tm time_t strptime(3) time(2) */
|
| 22 | #include <ctype.h> /* isdigit(3), isxdigit(3), tolower(3) */
|
| 23 | @@ -4682,11 +4682,16 @@ static int pk_toPEM(lua_State *L) {
|
| 24 | NULL,
|
| 25 | };
|
| 26 | int type;
|
| 27 | -
|
| 28 | - if (!lua_istable(L, i))
|
| 29 | + const char *cname = NULL;
|
| 30 | + const EVP_CIPHER *cipher = NULL;
|
| 31 | + const char *pass = NULL;
|
| 32 | +
|
| 33 | + if (lua_istable(L, i)) {
|
| 34 | + loadfield(L, i, "cipher", LUA_TSTRING, &cname);
|
| 35 | + if (!getfield(L, i, "type"))
|
| 36 | + lua_pushstring(L, cname ? "private" : "public");
|
| 37 | + } else
|
| 38 | lua_pushvalue(L, i);
|
| 39 | - else if (!getfield(L, i, "type"))
|
| 40 | - lua_pushliteral(L, "public");
|
| 41 |
|
| 42 | type = auxL_checkoption(L, -1, NULL, types, 1);
|
| 43 | lua_pop(L, 1);
|
| 44 | @@ -4702,7 +4707,15 @@ static int pk_toPEM(lua_State *L) {
|
| 45 |
|
| 46 | break;
|
| 47 | case 2: case 3: /* private, PrivateKey */
|
| 48 | - if (!PEM_write_bio_PrivateKey(bio, key, 0, 0, 0, 0, 0))
|
| 49 | + if (cname) {
|
| 50 | + cipher = EVP_get_cipherbyname(cname);
|
| 51 | + if (!cipher)
|
| 52 | + return luaL_error(L, "pkey:toPEM: unknown cipher: %s", cname);
|
| 53 | + if (!loadfield(L, i, "password", LUA_TSTRING, &pass))
|
| 54 | + return luaL_error(L, "pkey:toPEM: password not defined");
|
| 55 | + }
|
| 56 | +
|
| 57 | + if (!PEM_write_bio_PrivateKey(bio, key, cipher, pass, pass ? strlen(pass) : 0, 0, 0))
|
| 58 | return auxL_error(L, auxL_EOPENSSL, "pkey:__tostring");
|
| 59 |
|
| 60 | len = BIO_get_mem_data(bio, &pem);
|
| 61 | --
|
| 62 | 2.48.1
|
| 63 |
|