• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
10 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include <openssl/x509.h>
13 
NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI * x,EVP_PKEY * pkey)14 int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey)
15 {
16     if ((x == NULL) || (x->spkac == NULL))
17         return 0;
18     return X509_PUBKEY_set(&(x->spkac->pubkey), pkey);
19 }
20 
NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI * x)21 EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x)
22 {
23     if ((x == NULL) || (x->spkac == NULL))
24         return NULL;
25     return X509_PUBKEY_get(x->spkac->pubkey);
26 }
27 
28 /* Load a Netscape SPKI from a base64 encoded string */
29 
NETSCAPE_SPKI_b64_decode(const char * str,int len)30 NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len)
31 {
32     unsigned char *spki_der;
33     const unsigned char *p;
34     int spki_len;
35     NETSCAPE_SPKI *spki;
36     if (len <= 0)
37         len = strlen(str);
38     if ((spki_der = OPENSSL_malloc(len + 1)) == NULL) {
39         ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
40         return NULL;
41     }
42     spki_len = EVP_DecodeBlock(spki_der, (const unsigned char *)str, len);
43     if (spki_len < 0) {
44         ERR_raise(ERR_LIB_X509, X509_R_BASE64_DECODE_ERROR);
45         OPENSSL_free(spki_der);
46         return NULL;
47     }
48     p = spki_der;
49     spki = d2i_NETSCAPE_SPKI(NULL, &p, spki_len);
50     OPENSSL_free(spki_der);
51     return spki;
52 }
53 
54 /* Generate a base64 encoded string from an SPKI */
55 
NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI * spki)56 char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *spki)
57 {
58     unsigned char *der_spki, *p;
59     char *b64_str;
60     int der_len;
61 
62     der_len = i2d_NETSCAPE_SPKI(spki, NULL);
63     if (der_len <= 0)
64         return NULL;
65     der_spki = OPENSSL_malloc(der_len);
66     b64_str = OPENSSL_malloc(der_len * 2);
67     if (der_spki == NULL || b64_str == NULL) {
68         ERR_raise(ERR_LIB_X509, ERR_R_MALLOC_FAILURE);
69         OPENSSL_free(der_spki);
70         OPENSSL_free(b64_str);
71         return NULL;
72     }
73     p = der_spki;
74     i2d_NETSCAPE_SPKI(spki, &p);
75     EVP_EncodeBlock((unsigned char *)b64_str, der_spki, der_len);
76     OPENSSL_free(der_spki);
77     return b64_str;
78 }
79