]> git.ipfire.org Git - thirdparty/openssl.git/blame - crypto/evp/p_seal.c
hmac: fix coverity 1484888 negative integer to size_t conversion
[thirdparty/openssl.git] / crypto / evp / p_seal.c
CommitLineData
aa6bb135 1/*
33388b44 2 * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
d02b48c6 3 *
4a8b0c55 4 * Licensed under the Apache License 2.0 (the "License"). You may not use
aa6bb135
RS
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
d02b48c6
RE
8 */
9
10#include <stdio.h>
b39fc560 11#include "internal/cryptlib.h"
ec577822 12#include <openssl/rand.h>
3c27208f 13#include <openssl/rsa.h>
ec577822
BM
14#include <openssl/evp.h>
15#include <openssl/objects.h>
16#include <openssl/x509.h>
d02b48c6 17
0f113f3e
MC
18int 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];
3c184592 23 int i, len;
2eb2b4f3 24 int rv = 0;
0f113f3e
MC
25
26 if (type) {
846ec07d 27 EVP_CIPHER_CTX_reset(ctx);
0f113f3e
MC
28 if (!EVP_EncryptInit_ex(ctx, type, NULL, NULL, NULL))
29 return 0;
30 }
31 if ((npubk <= 0) || !pubk)
32 return 1;
9420b403 33
0f113f3e
MC
34 if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
35 return 0;
2eb2b4f3 36
3c184592
P
37 len = EVP_CIPHER_CTX_iv_length(ctx);
38 if (len < 0 || RAND_bytes(iv, len) <= 0)
39 goto err;
40
41 len = EVP_CIPHER_CTX_key_length(ctx);
42 if (len < 0)
2eb2b4f3 43 goto err;
d02b48c6 44
0f113f3e 45 if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
2eb2b4f3 46 goto err;
58964a49 47
0f113f3e 48 for (i = 0; i < npubk; i++) {
3c184592 49 size_t keylen = len;
9420b403
RL
50 EVP_PKEY_CTX *pctx = NULL;
51
52 if ((pctx = EVP_PKEY_CTX_new(pubk[i], NULL)) == NULL) {
53 ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
2eb2b4f3
SL
54 goto err;
55 }
9420b403
RL
56
57 if (EVP_PKEY_encrypt_init(pctx) <= 0
58 || EVP_PKEY_encrypt(pctx, ek[i], &keylen, key, keylen) <= 0)
59 goto err;
60 ekl[i] = (int)keylen;
61 EVP_PKEY_CTX_free(pctx);
0f113f3e 62 }
2eb2b4f3
SL
63 rv = npubk;
64err:
65 OPENSSL_cleanse(key, sizeof(key));
66 return rv;
0f113f3e 67}
d02b48c6 68
e9ba6963 69int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
0f113f3e
MC
70{
71 int i;
72 i = EVP_EncryptFinal_ex(ctx, out, outl);
73 if (i)
74 i = EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL);
75 return i;
76}