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/asymmetric_key_factory.h>
18
19#include <keymaster/android_keymaster_utils.h>
20
21#include "asymmetric_key.h"
22#include "openssl_err.h"
23#include "openssl_utils.h"
24
25namespace keymaster {
26
27static const keymaster_key_format_t supported_import_formats[] = {KM_KEY_FORMAT_PKCS8};
28const keymaster_key_format_t*
29AsymmetricKeyFactory::SupportedImportFormats(size_t* format_count) const {
30    *format_count = array_length(supported_import_formats);
31    return supported_import_formats;
32}
33
34static const keymaster_key_format_t supported_export_formats[] = {KM_KEY_FORMAT_X509};
35const keymaster_key_format_t*
36AsymmetricKeyFactory::SupportedExportFormats(size_t* format_count) const {
37    *format_count = array_length(supported_export_formats);
38    return supported_export_formats;
39}
40
41keymaster_error_t AsymmetricKeyFactory::LoadKey(const KeymasterKeyBlob& key_material,
42                                                const AuthorizationSet& /* additional_params */,
43                                                const AuthorizationSet& hw_enforced,
44                                                const AuthorizationSet& sw_enforced,
45                                                UniquePtr<Key>* key) const {
46    UniquePtr<AsymmetricKey> asymmetric_key;
47    keymaster_error_t error = CreateEmptyKey(hw_enforced, sw_enforced, &asymmetric_key);
48    if (error != KM_ERROR_OK)
49        return error;
50
51    const uint8_t* tmp = key_material.key_material;
52    EVP_PKEY* pkey =
53        d2i_PrivateKey(evp_key_type(), NULL /* pkey */, &tmp, key_material.key_material_size);
54    if (!pkey)
55        return TranslateLastOpenSslError();
56    UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey_deleter(pkey);
57
58    if (!asymmetric_key->EvpToInternal(pkey))
59        error = TranslateLastOpenSslError();
60    else
61        key->reset(asymmetric_key.release());
62
63    return error;
64}
65
66}  // namespace keymaster
67