blob: 2ead3c572eca52b3311b8f3f1d426fa7c80c6b83 [file] [log] [blame]
Shawn Willdend67afae2014-08-19 12:36:27 -06001/*
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
Shawn Willdena278f612014-12-23 11:22:21 -070017#include "asymmetric_key.h"
18
Shawn Willden0f906ec2015-06-20 09:16:30 -060019#include <new>
20
Shawn Willdenf268d742014-08-19 15:36:26 -060021#include <openssl/x509.h>
22
Shawn Willden567a4a02014-12-31 12:14:46 -070023#include "openssl_err.h"
Shawn Willdend67afae2014-08-19 12:36:27 -060024#include "openssl_utils.h"
Shawn Willdend67afae2014-08-19 12:36:27 -060025
26namespace keymaster {
27
Shawn Willdenf268d742014-08-19 15:36:26 -060028keymaster_error_t AsymmetricKey::formatted_key_material(keymaster_key_format_t format,
29 UniquePtr<uint8_t[]>* material,
Shawn Willdend67afae2014-08-19 12:36:27 -060030 size_t* size) const {
Shawn Willdenf268d742014-08-19 15:36:26 -060031 if (format != KM_KEY_FORMAT_X509)
32 return KM_ERROR_UNSUPPORTED_KEY_FORMAT;
33
Shawn Willdend67afae2014-08-19 12:36:27 -060034 if (material == NULL || size == NULL)
35 return KM_ERROR_OUTPUT_PARAMETER_NULL;
36
Shawn Willden722d8a42016-01-28 08:02:44 +000037 UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKEY_new());
Shawn Willdenf268d742014-08-19 15:36:26 -060038 if (!InternalToEvp(pkey.get()))
Shawn Willden567a4a02014-12-31 12:14:46 -070039 return TranslateLastOpenSslError();
Shawn Willdenf268d742014-08-19 15:36:26 -060040
41 int key_data_length = i2d_PUBKEY(pkey.get(), NULL);
42 if (key_data_length <= 0)
Shawn Willden567a4a02014-12-31 12:14:46 -070043 return TranslateLastOpenSslError();
Shawn Willdenf268d742014-08-19 15:36:26 -060044
Shawn Willden0f906ec2015-06-20 09:16:30 -060045 material->reset(new (std::nothrow) uint8_t[key_data_length]);
Shawn Willdenf268d742014-08-19 15:36:26 -060046 if (material->get() == NULL)
47 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
48
49 uint8_t* tmp = material->get();
50 if (i2d_PUBKEY(pkey.get(), &tmp) != key_data_length) {
51 material->reset();
Shawn Willden567a4a02014-12-31 12:14:46 -070052 return TranslateLastOpenSslError();
Shawn Willdenf268d742014-08-19 15:36:26 -060053 }
54
55 *size = key_data_length;
56 return KM_ERROR_OK;
Shawn Willdend67afae2014-08-19 12:36:27 -060057}
58
Shawn Willdend67afae2014-08-19 12:36:27 -060059} // namespace keymaster