p_seal.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. #include <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include "internal/provider.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/evp.h>
  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. const OSSL_PROVIDER *prov;
  24. OSSL_LIB_CTX *libctx = NULL;
  25. EVP_PKEY_CTX *pctx = NULL;
  26. const EVP_CIPHER *cipher;
  27. int i, len;
  28. int rv = 0;
  29. if (type != NULL) {
  30. EVP_CIPHER_CTX_reset(ctx);
  31. if (!EVP_EncryptInit_ex(ctx, type, NULL, NULL, NULL))
  32. return 0;
  33. }
  34. if ((cipher = EVP_CIPHER_CTX_get0_cipher(ctx)) != NULL
  35. && (prov = EVP_CIPHER_get0_provider(cipher)) != NULL)
  36. libctx = ossl_provider_libctx(prov);
  37. if ((npubk <= 0) || !pubk)
  38. return 1;
  39. if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
  40. return 0;
  41. len = EVP_CIPHER_CTX_get_iv_length(ctx);
  42. if (len < 0 || RAND_priv_bytes_ex(libctx, iv, len, 0) <= 0)
  43. goto err;
  44. len = EVP_CIPHER_CTX_get_key_length(ctx);
  45. if (len < 0)
  46. goto err;
  47. if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
  48. goto err;
  49. for (i = 0; i < npubk; i++) {
  50. size_t keylen = len;
  51. pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pubk[i], NULL);
  52. if (pctx == NULL) {
  53. ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
  54. goto err;
  55. }
  56. if (EVP_PKEY_encrypt_init(pctx) <= 0
  57. || EVP_PKEY_encrypt(pctx, ek[i], &keylen, key, keylen) <= 0)
  58. goto err;
  59. ekl[i] = (int)keylen;
  60. EVP_PKEY_CTX_free(pctx);
  61. }
  62. pctx = NULL;
  63. rv = npubk;
  64. err:
  65. EVP_PKEY_CTX_free(pctx);
  66. OPENSSL_cleanse(key, sizeof(key));
  67. return rv;
  68. }
  69. int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
  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. }