1 /* 2 * Copyright 2020-2022 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 <openssl/core.h> 11 #include <openssl/buffer.h> 12 #include "internal/asn1.h" 13 #include "prov/bio.h" 14 #include "endecoder_local.h" 15 16 OSSL_FUNC_keymgmt_new_fn * 17 ossl_prov_get_keymgmt_new(const OSSL_DISPATCH *fns) 18 { 19 /* Pilfer the keymgmt dispatch table */ 20 for (; fns->function_id != 0; fns++) 21 if (fns->function_id == OSSL_FUNC_KEYMGMT_NEW) 22 return OSSL_FUNC_keymgmt_new(fns); 23 24 return NULL; 25 } 26 27 OSSL_FUNC_keymgmt_free_fn * 28 ossl_prov_get_keymgmt_free(const OSSL_DISPATCH *fns) 29 { 30 /* Pilfer the keymgmt dispatch table */ 31 for (; fns->function_id != 0; fns++) 32 if (fns->function_id == OSSL_FUNC_KEYMGMT_FREE) 33 return OSSL_FUNC_keymgmt_free(fns); 34 35 return NULL; 36 } 37 38 OSSL_FUNC_keymgmt_import_fn * 39 ossl_prov_get_keymgmt_import(const OSSL_DISPATCH *fns) 40 { 41 /* Pilfer the keymgmt dispatch table */ 42 for (; fns->function_id != 0; fns++) 43 if (fns->function_id == OSSL_FUNC_KEYMGMT_IMPORT) 44 return OSSL_FUNC_keymgmt_import(fns); 45 46 return NULL; 47 } 48 49 OSSL_FUNC_keymgmt_export_fn * 50 ossl_prov_get_keymgmt_export(const OSSL_DISPATCH *fns) 51 { 52 /* Pilfer the keymgmt dispatch table */ 53 for (; fns->function_id != 0; fns++) 54 if (fns->function_id == OSSL_FUNC_KEYMGMT_EXPORT) 55 return OSSL_FUNC_keymgmt_export(fns); 56 57 return NULL; 58 } 59 60 void *ossl_prov_import_key(const OSSL_DISPATCH *fns, void *provctx, 61 int selection, const OSSL_PARAM params[]) 62 { 63 OSSL_FUNC_keymgmt_new_fn *kmgmt_new = ossl_prov_get_keymgmt_new(fns); 64 OSSL_FUNC_keymgmt_free_fn *kmgmt_free = ossl_prov_get_keymgmt_free(fns); 65 OSSL_FUNC_keymgmt_import_fn *kmgmt_import = ossl_prov_get_keymgmt_import(fns); 66 void *key = NULL; 67 68 if (kmgmt_new != NULL && kmgmt_import != NULL && kmgmt_free != NULL) { 69 if ((key = kmgmt_new(provctx)) == NULL 70 || !kmgmt_import(key, selection, params)) { 71 kmgmt_free(key); 72 key = NULL; 73 } 74 } 75 return key; 76 } 77 78 void ossl_prov_free_key(const OSSL_DISPATCH *fns, void *key) 79 { 80 OSSL_FUNC_keymgmt_free_fn *kmgmt_free = ossl_prov_get_keymgmt_free(fns); 81 82 if (kmgmt_free != NULL) 83 kmgmt_free(key); 84 } 85 86 int ossl_read_der(PROV_CTX *provctx, OSSL_CORE_BIO *cin, unsigned char **data, 87 long *len) 88 { 89 BUF_MEM *mem = NULL; 90 BIO *in = ossl_bio_new_from_core_bio(provctx, cin); 91 int ok; 92 93 if (in == NULL) 94 return 0; 95 ok = (asn1_d2i_read_bio(in, &mem) >= 0); 96 if (ok) { 97 *data = (unsigned char *)mem->data; 98 *len = (long)mem->length; 99 OPENSSL_free(mem); 100 } 101 BIO_free(in); 102 return ok; 103 } 104