1 /*
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 <keymaster/km_openssl/ecies_kem.h>
18
19 #include <gtest/gtest.h>
20 #include <openssl/evp.h>
21
22 #include <hardware/keymaster_defs.h>
23
24 #include <keymaster/android_keymaster_utils.h>
25 #include <keymaster/km_openssl/nist_curve_key_exchange.h>
26
27 #include "android_keymaster_test_utils.h"
28
29 using std::string;
30
31 namespace keymaster {
32 namespace test {
33
34 StdoutLogger logger;
35
36 static const keymaster_ec_curve_t kEcCurves[] = {KM_EC_CURVE_P_224, KM_EC_CURVE_P_256,
37 KM_EC_CURVE_P_384, KM_EC_CURVE_P_521};
38
39 /**
40 * TestConsistency just tests that the basic key encapsulation hold.
41 */
TEST(EciesKem,TestConsistency)42 TEST(EciesKem, TestConsistency) {
43 static const uint32_t kKeyLen = 32;
44 for (auto& curve : kEcCurves) {
45 AuthorizationSet kem_description(AuthorizationSetBuilder()
46 .Authorization(TAG_EC_CURVE, curve)
47 .Authorization(TAG_KDF, KM_KDF_RFC5869_SHA256)
48 .Authorization(TAG_ECIES_SINGLE_HASH_MODE)
49 .Authorization(TAG_KEY_SIZE, kKeyLen));
50 keymaster_error_t error;
51 EciesKem* kem = new EciesKem(kem_description, &error);
52 ASSERT_EQ(KM_ERROR_OK, error);
53
54 NistCurveKeyExchange* key_exchange = NistCurveKeyExchange::GenerateKeyExchange(curve);
55 Buffer peer_public_value;
56 ASSERT_TRUE(key_exchange->public_value(&peer_public_value));
57
58 Buffer output_clear_key;
59 Buffer output_encrypted_key;
60 ASSERT_TRUE(kem->Encrypt(peer_public_value, &output_clear_key, &output_encrypted_key));
61 ASSERT_EQ(kKeyLen, output_clear_key.available_read());
62 ASSERT_EQ(peer_public_value.available_read(), output_encrypted_key.available_read());
63
64 Buffer decrypted_clear_key;
65 ASSERT_TRUE(
66 kem->Decrypt(key_exchange->private_key(), output_encrypted_key, &decrypted_clear_key));
67 ASSERT_EQ(kKeyLen, decrypted_clear_key.available_read());
68 EXPECT_EQ(0, memcmp(output_clear_key.peek_read(), decrypted_clear_key.peek_read(),
69 output_clear_key.available_read()));
70 }
71 }
72
73 } // namespace test
74 } // namespace keymaster
75