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 "asymmetric_key.h"
18
19 #include <new>
20
21 #include <openssl/x509.h>
22
23 #include "openssl_err.h"
24 #include "openssl_utils.h"
25
26 namespace keymaster {
27
key_material(UniquePtr<uint8_t[]> * material,size_t * size) const28 keymaster_error_t AsymmetricKey::key_material(UniquePtr<uint8_t[]>* material, size_t* size) const {
29 if (material == NULL || size == NULL)
30 return KM_ERROR_OUTPUT_PARAMETER_NULL;
31
32 UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKEY_new());
33 if (pkey.get() == NULL)
34 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
35
36 if (!InternalToEvp(pkey.get()))
37 return TranslateLastOpenSslError();
38
39 *size = i2d_PrivateKey(pkey.get(), NULL /* key_data*/);
40 if (*size <= 0)
41 return TranslateLastOpenSslError();
42
43 material->reset(new (std::nothrow) uint8_t[*size]);
44 uint8_t* tmp = material->get();
45 i2d_PrivateKey(pkey.get(), &tmp);
46
47 return KM_ERROR_OK;
48 }
49
formatted_key_material(keymaster_key_format_t format,UniquePtr<uint8_t[]> * material,size_t * size) const50 keymaster_error_t AsymmetricKey::formatted_key_material(keymaster_key_format_t format,
51 UniquePtr<uint8_t[]>* material,
52 size_t* size) const {
53 if (format != KM_KEY_FORMAT_X509)
54 return KM_ERROR_UNSUPPORTED_KEY_FORMAT;
55
56 if (material == NULL || size == NULL)
57 return KM_ERROR_OUTPUT_PARAMETER_NULL;
58
59 UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKEY_new());
60 if (!InternalToEvp(pkey.get()))
61 return TranslateLastOpenSslError();
62
63 int key_data_length = i2d_PUBKEY(pkey.get(), NULL);
64 if (key_data_length <= 0)
65 return TranslateLastOpenSslError();
66
67 material->reset(new (std::nothrow) uint8_t[key_data_length]);
68 if (material->get() == NULL)
69 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
70
71 uint8_t* tmp = material->get();
72 if (i2d_PUBKEY(pkey.get(), &tmp) != key_data_length) {
73 material->reset();
74 return TranslateLastOpenSslError();
75 }
76
77 *size = key_data_length;
78 return KM_ERROR_OK;
79 }
80
81 } // namespace keymaster
82