p_seal.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #include <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include <openssl/rand.h>
  12. #include <openssl/rsa.h>
  13. #include <openssl/evp.h>
  14. #include <openssl/objects.h>
  15. #include <openssl/x509.h>
  16. int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
  17. unsigned char **ek, int *ekl, unsigned char *iv,
  18. EVP_PKEY **pubk, int npubk)
  19. {
  20. unsigned char key[EVP_MAX_KEY_LENGTH];
  21. int i;
  22. int rv = 0;
  23. if (type) {
  24. EVP_CIPHER_CTX_reset(ctx);
  25. if (!EVP_EncryptInit_ex(ctx, type, NULL, NULL, NULL))
  26. return 0;
  27. }
  28. if ((npubk <= 0) || !pubk)
  29. return 1;
  30. if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
  31. return 0;
  32. if (EVP_CIPHER_CTX_iv_length(ctx)
  33. && RAND_bytes(iv, EVP_CIPHER_CTX_iv_length(ctx)) <= 0)
  34. goto err;
  35. if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
  36. goto err;
  37. for (i = 0; i < npubk; i++) {
  38. size_t keylen = EVP_CIPHER_CTX_key_length(ctx);
  39. EVP_PKEY_CTX *pctx = NULL;
  40. if ((pctx = EVP_PKEY_CTX_new(pubk[i], NULL)) == NULL) {
  41. ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
  42. goto err;
  43. }
  44. if (EVP_PKEY_encrypt_init(pctx) <= 0
  45. || EVP_PKEY_encrypt(pctx, ek[i], &keylen, key, keylen) <= 0)
  46. goto err;
  47. ekl[i] = (int)keylen;
  48. EVP_PKEY_CTX_free(pctx);
  49. }
  50. rv = npubk;
  51. err:
  52. OPENSSL_cleanse(key, sizeof(key));
  53. return rv;
  54. }
  55. int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
  56. {
  57. int i;
  58. i = EVP_EncryptFinal_ex(ctx, out, outl);
  59. if (i)
  60. i = EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL);
  61. return i;
  62. }