lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame^] | 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 | |
| 10 | #include <stdio.h> |
| 11 | #include "internal/cryptlib.h" |
| 12 | #include <openssl/x509.h> |
| 13 | |
| 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 | |
| 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 | |
| 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 | X509err(X509_F_NETSCAPE_SPKI_B64_DECODE, 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 | X509err(X509_F_NETSCAPE_SPKI_B64_DECODE, 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 | |
| 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 | der_len = i2d_NETSCAPE_SPKI(spki, NULL); |
| 62 | der_spki = OPENSSL_malloc(der_len); |
| 63 | b64_str = OPENSSL_malloc(der_len * 2); |
| 64 | if (der_spki == NULL || b64_str == NULL) { |
| 65 | X509err(X509_F_NETSCAPE_SPKI_B64_ENCODE, ERR_R_MALLOC_FAILURE); |
| 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 | } |