p_seal.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. #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. if (type) {
  23. EVP_CIPHER_CTX_reset(ctx);
  24. if (!EVP_EncryptInit_ex(ctx, type, NULL, NULL, NULL))
  25. return 0;
  26. }
  27. if ((npubk <= 0) || !pubk)
  28. return 1;
  29. if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0)
  30. return 0;
  31. if (EVP_CIPHER_CTX_iv_length(ctx)
  32. && RAND_bytes(iv, EVP_CIPHER_CTX_iv_length(ctx)) <= 0)
  33. return 0;
  34. if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
  35. return 0;
  36. for (i = 0; i < npubk; i++) {
  37. ekl[i] =
  38. EVP_PKEY_encrypt_old(ek[i], key, EVP_CIPHER_CTX_key_length(ctx),
  39. pubk[i]);
  40. if (ekl[i] <= 0)
  41. return -1;
  42. }
  43. return npubk;
  44. }
  45. int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
  46. {
  47. int i;
  48. i = EVP_EncryptFinal_ex(ctx, out, outl);
  49. if (i)
  50. i = EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL);
  51. return i;
  52. }