p_open.c 1.8 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 "internal/cryptlib.h"
  10. #include <stdio.h>
  11. #include <openssl/evp.h>
  12. #include <openssl/objects.h>
  13. #include <openssl/x509.h>
  14. #include <openssl/rsa.h>
  15. int EVP_OpenInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
  16. const unsigned char *ek, int ekl, const unsigned char *iv,
  17. EVP_PKEY *priv)
  18. {
  19. unsigned char *key = NULL;
  20. size_t keylen = 0;
  21. int ret = 0;
  22. EVP_PKEY_CTX *pctx = NULL;
  23. if (type) {
  24. EVP_CIPHER_CTX_reset(ctx);
  25. if (!EVP_DecryptInit_ex(ctx, type, NULL, NULL, NULL))
  26. goto err;
  27. }
  28. if (priv == NULL)
  29. return 1;
  30. if ((pctx = EVP_PKEY_CTX_new(priv, NULL)) == NULL) {
  31. ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
  32. goto err;
  33. }
  34. if (EVP_PKEY_decrypt_init(pctx) <= 0
  35. || EVP_PKEY_decrypt(pctx, NULL, &keylen, ek, ekl) <= 0)
  36. goto err;
  37. if ((key = OPENSSL_malloc(keylen)) == NULL) {
  38. ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
  39. goto err;
  40. }
  41. if (EVP_PKEY_decrypt(pctx, key, &keylen, ek, ekl) <= 0)
  42. goto err;
  43. if (EVP_CIPHER_CTX_set_key_length(ctx, keylen) <= 0
  44. || !EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv))
  45. goto err;
  46. ret = 1;
  47. err:
  48. EVP_PKEY_CTX_free(pctx);
  49. OPENSSL_clear_free(key, keylen);
  50. return ret;
  51. }
  52. int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
  53. {
  54. int i;
  55. i = EVP_DecryptFinal_ex(ctx, out, outl);
  56. if (i)
  57. i = EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL);
  58. return i;
  59. }