blob: c8e9b79aa11ddb77648d4039cb54526b9d662f9e [file] [log] [blame]
Shawn Willden4d306ec2015-03-04 07:29:49 -07001/*
2 * Copyright 2015 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 "openssl_utils.h"
18
19#include "openssl_err.h"
20
21namespace keymaster {
22
23void convert_bn_to_blob(BIGNUM* bn, keymaster_blob_t* blob) {
24 blob->data_length = BN_num_bytes(bn);
25 blob->data = new uint8_t[blob->data_length];
26 BN_bn2bin(bn, const_cast<uint8_t*>(blob->data));
27}
28
29static int convert_to_evp(keymaster_algorithm_t algorithm) {
30 switch (algorithm) {
31 case KM_ALGORITHM_RSA:
32 return EVP_PKEY_RSA;
33 case KM_ALGORITHM_ECDSA:
34 return EVP_PKEY_EC;
35 default:
36 return -1;
37 };
38}
39
40keymaster_error_t convert_pkcs8_blob_to_evp(const uint8_t* key_data, size_t key_length,
41 keymaster_algorithm_t expected_algorithm,
42 UniquePtr<EVP_PKEY, EVP_PKEY_Delete>* pkey) {
43 if (key_data == NULL || key_length <= 0)
44 return KM_ERROR_INVALID_KEY_BLOB;
45
46 UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> pkcs8(
47 d2i_PKCS8_PRIV_KEY_INFO(NULL, &key_data, key_length));
48 if (pkcs8.get() == NULL)
49 return TranslateLastOpenSslError(true /* log_message */);
50
51 pkey->reset(EVP_PKCS82PKEY(pkcs8.get()));
52 if (!pkey->get())
53 return TranslateLastOpenSslError(true /* log_message */);
54
55 if (EVP_PKEY_type((*pkey)->type) != convert_to_evp(expected_algorithm)) {
56 LOG_E("EVP key algorithm was %d, not the expected %d", EVP_PKEY_type((*pkey)->type),
57 convert_to_evp(expected_algorithm));
58 return KM_ERROR_INVALID_KEY_BLOB;
59 }
60
61 return KM_ERROR_OK;
62}
63
64} // namespace keymaster