Skip to content

Commit 40ec44e

Browse files
committed
WIP: Re-use cipher contexts for SMGR-level encryption
1 parent 699a167 commit 40ec44e

1 file changed

Lines changed: 20 additions & 12 deletions

File tree

src/encryption/enc_aes.c

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ static const EVP_CIPHER *cipher_cbc_256 = NULL;
4040
static const EVP_CIPHER *cipher_gcm_256 = NULL;
4141
static const EVP_CIPHER *cipher_ctr_ecb_256 = NULL;
4242

43+
static EVP_CIPHER_CTX *ctx_cbc_128 = NULL;
44+
static EVP_CIPHER_CTX *ctx_cbc_256 = NULL;
45+
4346
void
4447
AesInit(void)
4548
{
@@ -52,6 +55,18 @@ AesInit(void)
5255
cipher_cbc_256 = EVP_aes_256_cbc();
5356
cipher_gcm_256 = EVP_aes_256_gcm();
5457
cipher_ctr_ecb_256 = EVP_aes_256_ecb();
58+
59+
ctx_cbc_128 = EVP_CIPHER_CTX_new();
60+
if (EVP_CipherInit_ex(ctx_cbc_128, cipher_cbc_128, NULL, NULL, NULL, 1) == 0)
61+
ereport(ERROR,
62+
errmsg("EVP_CipherInit_ex failed. OpenSSL error: %s", ERR_error_string(ERR_get_error(), NULL)));
63+
EVP_CIPHER_CTX_set_padding(ctx_cbc_128, 0);
64+
65+
ctx_cbc_256 = EVP_CIPHER_CTX_new();
66+
if (EVP_CipherInit_ex(ctx_cbc_256, cipher_cbc_256, NULL, NULL, NULL, 1) == 0)
67+
ereport(ERROR,
68+
errmsg("EVP_CipherInit_ex failed. OpenSSL error: %s", ERR_error_string(ERR_get_error(), NULL)));
69+
EVP_CIPHER_CTX_set_padding(ctx_cbc_256, 0);
5570
}
5671

5772
static void
@@ -94,23 +109,18 @@ AesRunCbc(int enc, const unsigned char *key, int key_len, const unsigned char *i
94109
{
95110
int out_len;
96111
int out_len_final;
97-
EVP_CIPHER_CTX *ctx = NULL;
98-
const EVP_CIPHER *cipher;
112+
EVP_CIPHER_CTX *ctx;
99113

100114
Assert(key_len == 16 || key_len == 32);
101-
cipher = key_len == 32 ? cipher_cbc_256 : cipher_cbc_128;
102-
103-
Assert(cipher != NULL);
104-
Assert(in_len % EVP_CIPHER_block_size(cipher) == 0);
115+
ctx = key_len == 32 ? ctx_cbc_128 : ctx_cbc_128;
105116

106-
ctx = EVP_CIPHER_CTX_new();
117+
Assert(ctx != NULL);
118+
Assert(in_len % EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ctx)) == 0);
107119

108-
if (EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc) == 0)
120+
if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc) == 0)
109121
ereport(ERROR,
110122
errmsg("EVP_CipherInit_ex failed. OpenSSL error: %s", ERR_error_string(ERR_get_error(), NULL)));
111123

112-
EVP_CIPHER_CTX_set_padding(ctx, 0);
113-
114124
if (EVP_CipherUpdate(ctx, out, &out_len, in, in_len) == 0)
115125
ereport(ERROR,
116126
errmsg("EVP_CipherUpdate failed. OpenSSL error: %s", ERR_error_string(ERR_get_error(), NULL)));
@@ -125,8 +135,6 @@ AesRunCbc(int enc, const unsigned char *key, int key_len, const unsigned char *i
125135
*/
126136
out_len += out_len_final;
127137
Assert(in_len == out_len);
128-
129-
EVP_CIPHER_CTX_free(ctx);
130138
}
131139

132140
void

0 commit comments

Comments
 (0)