p_open.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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_EVP_LIB);
  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. goto err;
  39. if (EVP_PKEY_decrypt(pctx, key, &keylen, ek, ekl) <= 0)
  40. goto err;
  41. if (EVP_CIPHER_CTX_set_key_length(ctx, keylen) <= 0
  42. || !EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv))
  43. goto err;
  44. ret = 1;
  45. err:
  46. EVP_PKEY_CTX_free(pctx);
  47. OPENSSL_clear_free(key, keylen);
  48. return ret;
  49. }
  50. int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
  51. {
  52. int i;
  53. i = EVP_DecryptFinal_ex(ctx, out, outl);
  54. if (i)
  55. i = EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL);
  56. return i;
  57. }