d2i_pu.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright 1995-2022 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. /*
  10. * DSA low level APIs are deprecated for public use, but still ok for
  11. * internal use.
  12. */
  13. #include "internal/deprecated.h"
  14. #include <stdio.h>
  15. #include "internal/cryptlib.h"
  16. #include <openssl/bn.h>
  17. #include <openssl/evp.h>
  18. #include <openssl/objects.h>
  19. #include <openssl/asn1.h>
  20. #include <openssl/rsa.h>
  21. #include <openssl/dsa.h>
  22. #include <openssl/ec.h>
  23. #include "crypto/evp.h"
  24. EVP_PKEY *d2i_PublicKey(int type, EVP_PKEY **a, const unsigned char **pp,
  25. long length)
  26. {
  27. EVP_PKEY *ret;
  28. EVP_PKEY *copy = NULL;
  29. if ((a == NULL) || (*a == NULL)) {
  30. if ((ret = EVP_PKEY_new()) == NULL) {
  31. ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
  32. return NULL;
  33. }
  34. } else {
  35. ret = *a;
  36. #ifndef OPENSSL_NO_EC
  37. if (evp_pkey_is_provided(ret)
  38. && EVP_PKEY_get_base_id(ret) == EVP_PKEY_EC) {
  39. if (!evp_pkey_copy_downgraded(&copy, ret))
  40. goto err;
  41. }
  42. #endif
  43. }
  44. if ((type != EVP_PKEY_get_id(ret) || copy != NULL)
  45. && !EVP_PKEY_set_type(ret, type)) {
  46. ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
  47. goto err;
  48. }
  49. switch (EVP_PKEY_get_base_id(ret)) {
  50. case EVP_PKEY_RSA:
  51. if ((ret->pkey.rsa = d2i_RSAPublicKey(NULL, pp, length)) == NULL) {
  52. ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
  53. goto err;
  54. }
  55. break;
  56. #ifndef OPENSSL_NO_DSA
  57. case EVP_PKEY_DSA:
  58. if (!d2i_DSAPublicKey(&ret->pkey.dsa, pp, length)) {
  59. ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
  60. goto err;
  61. }
  62. break;
  63. #endif
  64. #ifndef OPENSSL_NO_EC
  65. case EVP_PKEY_EC:
  66. if (copy != NULL) {
  67. /* use downgraded parameters from copy */
  68. ret->pkey.ec = copy->pkey.ec;
  69. copy->pkey.ec = NULL;
  70. }
  71. if (!o2i_ECPublicKey(&ret->pkey.ec, pp, length)) {
  72. ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
  73. goto err;
  74. }
  75. break;
  76. #endif
  77. default:
  78. ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE);
  79. goto err;
  80. }
  81. if (a != NULL)
  82. (*a) = ret;
  83. EVP_PKEY_free(copy);
  84. return ret;
  85. err:
  86. if (a == NULL || *a != ret)
  87. EVP_PKEY_free(ret);
  88. EVP_PKEY_free(copy);
  89. return NULL;
  90. }