p_seal.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
  18. unsigned char **ek, int *ekl, unsigned char *iv,
  19. EVP_PKEY **pubk, int npubk)
  20. {
  21. unsigned char key[EVP_MAX_KEY_LENGTH];
  22. const OSSL_PROVIDER *prov;
  23. OSSL_LIB_CTX *libctx = NULL;
  24. EVP_PKEY_CTX *pctx = NULL;
  25. const EVP_CIPHER *cipher;
  26. int i, len;
  27. int rv = 0;
  28. if (type != NULL) {
  29. EVP_CIPHER_CTX_reset(ctx);
  30. if (!EVP_EncryptInit_ex(ctx, type, NULL, NULL, NULL))
  31. return 0;
  32. }
  33. if ((cipher = EVP_CIPHER_CTX_get0_cipher(ctx)) != NULL
  34. && (prov = EVP_CIPHER_get0_provider(cipher)) != NULL)
  35. libctx = ossl_provider_libctx(prov);
  36. if ((npubk <= 0) || !pubk)
  37. return 1;
  38. if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
  39. return 0;
  40. len = EVP_CIPHER_CTX_get_iv_length(ctx);
  41. if (len < 0 || RAND_priv_bytes_ex(libctx, iv, len, 0) <= 0)
  42. goto err;
  43. len = EVP_CIPHER_CTX_get_key_length(ctx);
  44. if (len < 0)
  45. goto err;
  46. if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
  47. goto err;
  48. for (i = 0; i < npubk; i++) {
  49. size_t keylen = len;
  50. pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pubk[i], NULL);
  51. if (pctx == NULL) {
  52. ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB);
  53. goto err;
  54. }
  55. if (EVP_PKEY_encrypt_init(pctx) <= 0
  56. || EVP_PKEY_encrypt(pctx, ek[i], &keylen, key, keylen) <= 0)
  57. goto err;
  58. ekl[i] = (int)keylen;
  59. EVP_PKEY_CTX_free(pctx);
  60. }
  61. pctx = NULL;
  62. rv = npubk;
  63. err:
  64. EVP_PKEY_CTX_free(pctx);
  65. OPENSSL_cleanse(key, sizeof(key));
  66. return rv;
  67. }
  68. int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
  69. {
  70. int i;
  71. i = EVP_EncryptFinal_ex(ctx, out, outl);
  72. if (i)
  73. i = EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL);
  74. return i;
  75. }