x509spki.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (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. X509err(X509_F_NETSCAPE_SPKI_B64_DECODE, ERR_R_MALLOC_FAILURE);
  35. return NULL;
  36. }
  37. spki_len = EVP_DecodeBlock(spki_der, (const unsigned char *)str, len);
  38. if (spki_len < 0) {
  39. X509err(X509_F_NETSCAPE_SPKI_B64_DECODE, X509_R_BASE64_DECODE_ERROR);
  40. OPENSSL_free(spki_der);
  41. return NULL;
  42. }
  43. p = spki_der;
  44. spki = d2i_NETSCAPE_SPKI(NULL, &p, spki_len);
  45. OPENSSL_free(spki_der);
  46. return spki;
  47. }
  48. /* Generate a base64 encoded string from an SPKI */
  49. char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *spki)
  50. {
  51. unsigned char *der_spki, *p;
  52. char *b64_str;
  53. int der_len;
  54. der_len = i2d_NETSCAPE_SPKI(spki, 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. X509err(X509_F_NETSCAPE_SPKI_B64_ENCODE, ERR_R_MALLOC_FAILURE);
  59. OPENSSL_free(der_spki);
  60. OPENSSL_free(b64_str);
  61. return NULL;
  62. }
  63. p = der_spki;
  64. i2d_NETSCAPE_SPKI(spki, &p);
  65. EVP_EncodeBlock((unsigned char *)b64_str, der_spki, der_len);
  66. OPENSSL_free(der_spki);
  67. return b64_str;
  68. }