p_open.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 1995-2016 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. #ifdef OPENSSL_NO_RSA
  11. NON_EMPTY_TRANSLATION_UNIT
  12. #else
  13. # include <stdio.h>
  14. # include <openssl/evp.h>
  15. # include <openssl/objects.h>
  16. # include <openssl/x509.h>
  17. # include <openssl/rsa.h>
  18. int EVP_OpenInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
  19. const unsigned char *ek, int ekl, const unsigned char *iv,
  20. EVP_PKEY *priv)
  21. {
  22. unsigned char *key = NULL;
  23. int i, size = 0, ret = 0;
  24. if (type) {
  25. EVP_CIPHER_CTX_reset(ctx);
  26. if (!EVP_DecryptInit_ex(ctx, type, NULL, NULL, NULL))
  27. return 0;
  28. }
  29. if (!priv)
  30. return 1;
  31. if (EVP_PKEY_id(priv) != EVP_PKEY_RSA) {
  32. EVPerr(EVP_F_EVP_OPENINIT, EVP_R_PUBLIC_KEY_NOT_RSA);
  33. goto err;
  34. }
  35. size = EVP_PKEY_size(priv);
  36. key = OPENSSL_malloc(size + 2);
  37. if (key == NULL) {
  38. /* ERROR */
  39. EVPerr(EVP_F_EVP_OPENINIT, ERR_R_MALLOC_FAILURE);
  40. goto err;
  41. }
  42. i = EVP_PKEY_decrypt_old(key, ek, ekl, priv);
  43. if ((i <= 0) || !EVP_CIPHER_CTX_set_key_length(ctx, i)) {
  44. /* ERROR */
  45. goto err;
  46. }
  47. if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv))
  48. goto err;
  49. ret = 1;
  50. err:
  51. OPENSSL_clear_free(key, size);
  52. return ret;
  53. }
  54. int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
  55. {
  56. int i;
  57. i = EVP_DecryptFinal_ex(ctx, out, outl);
  58. if (i)
  59. i = EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL);
  60. return i;
  61. }
  62. #endif