xref: /openssl/crypto/evp/p_seal.c (revision e077455e)
1 /*
2  * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include "internal/provider.h"
13 #include <openssl/rand.h>
14 #include <openssl/rsa.h>
15 #include <openssl/evp.h>
16 #include <openssl/objects.h>
17 #include <openssl/x509.h>
18 
EVP_SealInit(EVP_CIPHER_CTX * ctx,const EVP_CIPHER * type,unsigned char ** ek,int * ekl,unsigned char * iv,EVP_PKEY ** pubk,int npubk)19 int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
20                  unsigned char **ek, int *ekl, unsigned char *iv,
21                  EVP_PKEY **pubk, int npubk)
22 {
23     unsigned char key[EVP_MAX_KEY_LENGTH];
24     const OSSL_PROVIDER *prov;
25     OSSL_LIB_CTX *libctx = NULL;
26     EVP_PKEY_CTX *pctx = NULL;
27     const EVP_CIPHER *cipher;
28     int i, len;
29     int rv = 0;
30 
31     if (type != NULL) {
32         EVP_CIPHER_CTX_reset(ctx);
33         if (!EVP_EncryptInit_ex(ctx, type, NULL, NULL, NULL))
34             return 0;
35     }
36     if ((cipher = EVP_CIPHER_CTX_get0_cipher(ctx)) != NULL
37             && (prov = EVP_CIPHER_get0_provider(cipher)) != NULL)
38         libctx = ossl_provider_libctx(prov);
39     if ((npubk <= 0) || !pubk)
40         return 1;
41 
42     if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
43         return 0;
44 
45     len = EVP_CIPHER_CTX_get_iv_length(ctx);
46     if (len < 0 || RAND_priv_bytes_ex(libctx, iv, len, 0) <= 0)
47         goto err;
48 
49     len = EVP_CIPHER_CTX_get_key_length(ctx);
50     if (len < 0)
51         goto err;
52 
53     if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
54         goto err;
55 
56     for (i = 0; i < npubk; i++) {
57         size_t keylen = len;
58 
59         pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pubk[i], NULL);
60         if (pctx == NULL) {
61             ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB);
62             goto err;
63         }
64 
65         if (EVP_PKEY_encrypt_init(pctx) <= 0
66             || EVP_PKEY_encrypt(pctx, ek[i], &keylen, key, keylen) <= 0)
67             goto err;
68         ekl[i] = (int)keylen;
69         EVP_PKEY_CTX_free(pctx);
70     }
71     pctx = NULL;
72     rv = npubk;
73 err:
74     EVP_PKEY_CTX_free(pctx);
75     OPENSSL_cleanse(key, sizeof(key));
76     return rv;
77 }
78 
EVP_SealFinal(EVP_CIPHER_CTX * ctx,unsigned char * out,int * outl)79 int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
80 {
81     int i;
82     i = EVP_EncryptFinal_ex(ctx, out, outl);
83     if (i)
84         i = EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL);
85     return i;
86 }
87