p_seal.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright 1995-2018 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. ekl[i] =
  39. EVP_PKEY_encrypt_old(ek[i], key, EVP_CIPHER_CTX_key_length(ctx),
  40. pubk[i]);
  41. if (ekl[i] <= 0) {
  42. rv = -1;
  43. goto err;
  44. }
  45. }
  46. rv = npubk;
  47. err:
  48. OPENSSL_cleanse(key, sizeof(key));
  49. return rv;
  50. }
  51. int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
  52. {
  53. int i;
  54. i = EVP_EncryptFinal_ex(ctx, out, outl);
  55. if (i)
  56. i = EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, NULL);
  57. return i;
  58. }