1 /*
2 * Copyright 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <keymaster/km_openssl/asymmetric_key.h>
18
19 #include <keymaster/new>
20
21 #include <openssl/asn1.h>
22 #include <openssl/stack.h>
23 #include <openssl/x509.h>
24 #include <openssl/x509v3.h>
25
26 #include <keymaster/android_keymaster_utils.h>
27 #include <keymaster/attestation_record.h>
28 #include <keymaster/keymaster_context.h>
29 #include <keymaster/km_openssl/openssl_err.h>
30 #include <keymaster/km_openssl/openssl_utils.h>
31
32
33 namespace keymaster {
34
formatted_key_material(keymaster_key_format_t format,UniquePtr<uint8_t[]> * material,size_t * size) const35 keymaster_error_t AsymmetricKey::formatted_key_material(keymaster_key_format_t format,
36 UniquePtr<uint8_t[]>* material,
37 size_t* size) const {
38 if (format != KM_KEY_FORMAT_X509)
39 return KM_ERROR_UNSUPPORTED_KEY_FORMAT;
40
41 if (material == nullptr || size == nullptr)
42 return KM_ERROR_OUTPUT_PARAMETER_NULL;
43
44 EVP_PKEY_Ptr pkey(EVP_PKEY_new());
45 if (!InternalToEvp(pkey.get()))
46 return TranslateLastOpenSslError();
47
48 int key_data_length = i2d_PUBKEY(pkey.get(), nullptr);
49 if (key_data_length <= 0)
50 return TranslateLastOpenSslError();
51
52 material->reset(new(std::nothrow) uint8_t[key_data_length]);
53 if (material->get() == nullptr)
54 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
55
56 uint8_t* tmp = material->get();
57 if (i2d_PUBKEY(pkey.get(), &tmp) != key_data_length) {
58 material->reset();
59 return TranslateLastOpenSslError();
60 }
61
62 *size = key_data_length;
63 return KM_ERROR_OK;
64 }
65
66 } // namespace keymaster
67