Publish the RAND_DRBG API
[openssl.git] / crypto / evp / p_seal.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 #include <openssl/rand_drbg.h>
18 #include "evp_locl.h"
19
20 int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
21                  unsigned char **ek, int *ekl, unsigned char *iv,
22                  EVP_PKEY **pubk, int npubk)
23 {
24     unsigned char key[EVP_MAX_KEY_LENGTH];
25     int i;
26
27     if (type) {
28         EVP_CIPHER_CTX_reset(ctx);
29         if (!EVP_EncryptInit_ex(ctx, type, NULL, NULL, NULL))
30             return 0;
31     }
32     if ((npubk <= 0) || !pubk)
33         return 1;
34     if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
35         return 0;
36     if (EVP_CIPHER_CTX_iv_length(ctx)) {
37         if (ctx->drbg) {
38             if (RAND_DRBG_bytes(ctx->drbg, iv, EVP_CIPHER_CTX_iv_length(ctx)) == 0)
39                 return 0;
40         } else if (RAND_bytes(iv, EVP_CIPHER_CTX_iv_length(ctx)) <= 0) {
41             return 0;
42         }
43     }
44
45     if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
46         return 0;
47
48     for (i = 0; i < npubk; i++) {
49         ekl[i] =
50             EVP_PKEY_encrypt_old(ek[i], key, EVP_CIPHER_CTX_key_length(ctx),
51                                  pubk[i]);
52         if (ekl[i] <= 0)
53             return -1;
54     }
55     return npubk;
56 }
57
58 int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
59 {
60     int i;
61     i = EVP_EncryptFinal_ex(ctx, out, outl);
62     if (i)
63         i = EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL);
64     return i;
65 }