2
0

x509spki.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright 1999-2021 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/x509.h>
  12. int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey)
  13. {
  14. if ((x == NULL) || (x->spkac == NULL))
  15. return 0;
  16. return X509_PUBKEY_set(&(x->spkac->pubkey), pkey);
  17. }
  18. EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x)
  19. {
  20. if ((x == NULL) || (x->spkac == NULL))
  21. return NULL;
  22. return X509_PUBKEY_get(x->spkac->pubkey);
  23. }
  24. /* Load a Netscape SPKI from a base64 encoded string */
  25. NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len)
  26. {
  27. unsigned char *spki_der;
  28. const unsigned char *p;
  29. int spki_len;
  30. NETSCAPE_SPKI *spki;
  31. if (len <= 0)
  32. len = strlen(str);
  33. if ((spki_der = OPENSSL_malloc(len + 1)) == NULL)
  34. return NULL;
  35. spki_len = EVP_DecodeBlock(spki_der, (const unsigned char *)str, len);
  36. if (spki_len < 0) {
  37. ERR_raise(ERR_LIB_X509, X509_R_BASE64_DECODE_ERROR);
  38. OPENSSL_free(spki_der);
  39. return NULL;
  40. }
  41. p = spki_der;
  42. spki = d2i_NETSCAPE_SPKI(NULL, &p, spki_len);
  43. OPENSSL_free(spki_der);
  44. return spki;
  45. }
  46. /* Generate a base64 encoded string from an SPKI */
  47. char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *spki)
  48. {
  49. unsigned char *der_spki, *p;
  50. char *b64_str;
  51. int der_len;
  52. der_len = i2d_NETSCAPE_SPKI(spki, NULL);
  53. if (der_len <= 0)
  54. return NULL;
  55. der_spki = OPENSSL_malloc(der_len);
  56. b64_str = OPENSSL_malloc(der_len * 2);
  57. if (der_spki == NULL || b64_str == NULL) {
  58. OPENSSL_free(der_spki);
  59. OPENSSL_free(b64_str);
  60. return NULL;
  61. }
  62. p = der_spki;
  63. i2d_NETSCAPE_SPKI(spki, &p);
  64. EVP_EncodeBlock((unsigned char *)b64_str, der_spki, der_len);
  65. OPENSSL_free(der_spki);
  66. return b64_str;
  67. }