diff options
-rw-r--r-- | src/openssl.c | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/src/openssl.c b/src/openssl.c index c0fc6de..85c7503 100644 --- a/src/openssl.c +++ b/src/openssl.c | |||
@@ -3181,6 +3181,61 @@ static int pk_setPrivateKey(lua_State *L) { | |||
3181 | } /* pk_setPrivateKey() */ | 3181 | } /* pk_setPrivateKey() */ |
3182 | 3182 | ||
3183 | 3183 | ||
3184 | static int pk_decrypt(lua_State *L) { | ||
3185 | size_t outlen, inlen; | ||
3186 | EVP_PKEY *key = checksimple(L, 1, PKEY_CLASS); | ||
3187 | EVP_PKEY_CTX *ctx; | ||
3188 | const char *str = luaL_checklstring(L, 2, &inlen); | ||
3189 | BIO *bio; | ||
3190 | BUF_MEM *buf; | ||
3191 | int rsaPadding = RSA_PKCS1_PADDING; /* default for `openssl rsautl` */ | ||
3192 | int base_type = EVP_PKEY_base_id(key); | ||
3193 | |||
3194 | if (lua_istable(L, 3)) { | ||
3195 | if (base_type == EVP_PKEY_RSA) { | ||
3196 | lua_getfield(L, 3, "rsaPadding"); | ||
3197 | rsaPadding = luaL_optint(L, -1, rsaPadding); | ||
3198 | lua_pop(L, 1); | ||
3199 | } | ||
3200 | } | ||
3201 | |||
3202 | bio = getbio(L); | ||
3203 | BIO_get_mem_ptr(bio, &buf); | ||
3204 | |||
3205 | if (!(ctx = EVP_PKEY_CTX_new(key, NULL))) | ||
3206 | goto sslerr; | ||
3207 | |||
3208 | if (EVP_PKEY_decrypt_init(ctx) <= 0) | ||
3209 | goto sslerr; | ||
3210 | |||
3211 | if (base_type == EVP_PKEY_RSA && !EVP_PKEY_CTX_set_rsa_padding(ctx, rsaPadding)) | ||
3212 | goto sslerr; | ||
3213 | |||
3214 | if (EVP_PKEY_decrypt(ctx, NULL, &outlen, str, inlen) <= 0) | ||
3215 | goto sslerr; | ||
3216 | |||
3217 | if (!BUF_MEM_grow_clean(buf, outlen)) | ||
3218 | goto sslerr; | ||
3219 | |||
3220 | if (EVP_PKEY_decrypt(ctx, buf->data, &outlen, str, inlen) <= 0) | ||
3221 | goto sslerr; | ||
3222 | |||
3223 | EVP_PKEY_CTX_free(ctx); | ||
3224 | ctx = NULL; | ||
3225 | |||
3226 | lua_pushlstring(L, buf->data, outlen); | ||
3227 | |||
3228 | return 1; | ||
3229 | sslerr: | ||
3230 | if (ctx) { | ||
3231 | EVP_PKEY_CTX_free(ctx); | ||
3232 | ctx = NULL; | ||
3233 | } | ||
3234 | |||
3235 | return auxL_error(L, auxL_EOPENSSL, "pkey:decrypt"); | ||
3236 | } /* pk_decrypt() */ | ||
3237 | |||
3238 | |||
3184 | static int pk_encrypt(lua_State *L) { | 3239 | static int pk_encrypt(lua_State *L) { |
3185 | size_t outlen, inlen; | 3240 | size_t outlen, inlen; |
3186 | EVP_PKEY *key = checksimple(L, 1, PKEY_CLASS); | 3241 | EVP_PKEY *key = checksimple(L, 1, PKEY_CLASS); |
@@ -3962,6 +4017,7 @@ static const auxL_Reg pk_methods[] = { | |||
3962 | { "type", &pk_type }, | 4017 | { "type", &pk_type }, |
3963 | { "setPublicKey", &pk_setPublicKey }, | 4018 | { "setPublicKey", &pk_setPublicKey }, |
3964 | { "setPrivateKey", &pk_setPrivateKey }, | 4019 | { "setPrivateKey", &pk_setPrivateKey }, |
4020 | { "decrypt", &pk_decrypt }, | ||
3965 | { "encrypt", &pk_encrypt }, | 4021 | { "encrypt", &pk_encrypt }, |
3966 | { "sign", &pk_sign }, | 4022 | { "sign", &pk_sign }, |
3967 | { "verify", &pk_verify }, | 4023 | { "verify", &pk_verify }, |