]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/evp/p_seal.c
Update copyright year
[thirdparty/openssl.git] / crypto / evp / p_seal.c
1 /*
2 * Copyright 1995-2020 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 <openssl/rand.h>
13 #include <openssl/rsa.h>
14 #include <openssl/evp.h>
15 #include <openssl/objects.h>
16 #include <openssl/x509.h>
17
18 int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
19 unsigned char **ek, int *ekl, unsigned char *iv,
20 EVP_PKEY **pubk, int npubk)
21 {
22 unsigned char key[EVP_MAX_KEY_LENGTH];
23 int i;
24 int rv = 0;
25
26 if (type) {
27 EVP_CIPHER_CTX_reset(ctx);
28 if (!EVP_EncryptInit_ex(ctx, type, NULL, NULL, NULL))
29 return 0;
30 }
31 if ((npubk <= 0) || !pubk)
32 return 1;
33
34 if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
35 return 0;
36
37 if (EVP_CIPHER_CTX_iv_length(ctx)
38 && RAND_bytes(iv, EVP_CIPHER_CTX_iv_length(ctx)) <= 0)
39 goto err;
40
41 if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
42 goto err;
43
44 for (i = 0; i < npubk; i++) {
45 size_t keylen = EVP_CIPHER_CTX_key_length(ctx);
46 EVP_PKEY_CTX *pctx = NULL;
47
48 if ((pctx = EVP_PKEY_CTX_new(pubk[i], NULL)) == NULL) {
49 ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
50 goto err;
51 }
52
53 if (EVP_PKEY_encrypt_init(pctx) <= 0
54 || EVP_PKEY_encrypt(pctx, ek[i], &keylen, key, keylen) <= 0)
55 goto err;
56 ekl[i] = (int)keylen;
57 EVP_PKEY_CTX_free(pctx);
58 }
59 rv = npubk;
60 err:
61 OPENSSL_cleanse(key, sizeof(key));
62 return rv;
63 }
64
65 int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
66 {
67 int i;
68 i = EVP_EncryptFinal_ex(ctx, out, outl);
69 if (i)
70 i = EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL);
71 return i;
72 }