xref: /openssl/crypto/x509/x509spki.c (revision e077455e)
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         return NULL;
40     spki_len = EVP_DecodeBlock(spki_der, (const unsigned char *)str, len);
41     if (spki_len < 0) {
42         ERR_raise(ERR_LIB_X509, X509_R_BASE64_DECODE_ERROR);
43         OPENSSL_free(spki_der);
44         return NULL;
45     }
46     p = spki_der;
47     spki = d2i_NETSCAPE_SPKI(NULL, &p, spki_len);
48     OPENSSL_free(spki_der);
49     return spki;
50 }
51 
52 /* Generate a base64 encoded string from an SPKI */
53 
NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI * spki)54 char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *spki)
55 {
56     unsigned char *der_spki, *p;
57     char *b64_str;
58     int der_len;
59 
60     der_len = i2d_NETSCAPE_SPKI(spki, NULL);
61     if (der_len <= 0)
62         return NULL;
63     der_spki = OPENSSL_malloc(der_len);
64     b64_str = OPENSSL_malloc(der_len * 2);
65     if (der_spki == NULL || b64_str == NULL) {
66         OPENSSL_free(der_spki);
67         OPENSSL_free(b64_str);
68         return NULL;
69     }
70     p = der_spki;
71     i2d_NETSCAPE_SPKI(spki, &p);
72     EVP_EncodeBlock((unsigned char *)b64_str, der_spki, der_len);
73     OPENSSL_free(der_spki);
74     return b64_str;
75 }
76