android_keymaster_test.cpp revision ebc99a15e324d9f1cfaf681a8c95676984f16f08
1/*
2 * Copyright (C) 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 <fstream>
18#include <string>
19#include <vector>
20
21#include <hardware/keymaster0.h>
22#include <keymaster/key_factory.h>
23#include <keymaster/soft_keymaster_context.h>
24#include <keymaster/soft_keymaster_device.h>
25#include <keymaster/softkeymaster.h>
26
27#include "android_keymaster_test_utils.h"
28#include "keymaster0_engine.h"
29
30using std::ifstream;
31using std::istreambuf_iterator;
32using std::string;
33using std::vector;
34using std::unique_ptr;
35
36extern "C" {
37int __android_log_print(int prio, const char* tag, const char* fmt);
38int __android_log_print(int prio, const char* tag, const char* fmt) {
39    (void)prio, (void)tag, (void)fmt;
40    return 0;
41}
42}  // extern "C"
43
44namespace keymaster {
45namespace test {
46
47StdoutLogger logger;
48
49class TestKeymasterEnforcement : public KeymasterEnforcement {
50  public:
51    TestKeymasterEnforcement() : KeymasterEnforcement(3, 3) {}
52
53    virtual bool activation_date_valid(uint64_t /* activation_date */) const { return true; }
54    virtual bool expiration_date_passed(uint64_t /* expiration_date */) const { return false; }
55    virtual bool auth_token_timed_out(const hw_auth_token_t& /* token */,
56                                      uint32_t /* timeout */) const {
57        return false;
58    }
59    virtual uint32_t get_current_time() const { return 0; }
60    virtual bool ValidateTokenSignature(const hw_auth_token_t& /* token */) const { return true; }
61};
62
63class TestKeymasterContext : public SoftKeymasterContext {
64  public:
65    TestKeymasterContext(keymaster0_device_t* keymaster0 = nullptr)
66        : SoftKeymasterContext(keymaster0) {}
67
68    KeymasterEnforcement* enforcement_policy() override { return &test_policy_; }
69
70  private:
71    TestKeymasterEnforcement test_policy_;
72};
73
74class SoftKeymasterTestInstanceCreator : public Keymaster1TestInstanceCreator {
75  public:
76    keymaster1_device_t* CreateDevice() const override {
77        std::cerr << "Creating software-only device" << std::endl;
78        SoftKeymasterDevice* device = new SoftKeymasterDevice(new TestKeymasterContext);
79        return device->keymaster_device();
80    }
81
82    bool algorithm_in_hardware(keymaster_algorithm_t) const override { return false; }
83    int keymaster0_calls() const override { return 0; }
84};
85
86class Keymaster0AdapterTestInstanceCreator : public Keymaster1TestInstanceCreator {
87  public:
88    Keymaster0AdapterTestInstanceCreator(bool support_ec) : support_ec_(support_ec) {}
89
90    keymaster1_device_t* CreateDevice() const {
91        std::cerr << "Creating keymaster0-backed device (with ec: " << std::boolalpha << support_ec_
92                  << ")." << std::endl;
93        hw_device_t* softkeymaster_device;
94        EXPECT_EQ(0, openssl_open(&softkeymaster_module.common, KEYSTORE_KEYMASTER,
95                                  &softkeymaster_device));
96        // Make the software device pretend to be hardware
97        keymaster0_device_t* keymaster0_device =
98            reinterpret_cast<keymaster0_device_t*>(softkeymaster_device);
99        keymaster0_device->flags &= ~KEYMASTER_SOFTWARE_ONLY;
100
101        if (!support_ec_) {
102            // Make the software device pretend not to support EC
103            keymaster0_device->flags &= ~KEYMASTER_SUPPORTS_EC;
104        }
105
106        counting_keymaster0_device_ = new Keymaster0CountingWrapper(keymaster0_device);
107
108        SoftKeymasterDevice* keymaster =
109            new SoftKeymasterDevice(new TestKeymasterContext(counting_keymaster0_device_));
110        return keymaster->keymaster_device();
111    }
112
113    bool algorithm_in_hardware(keymaster_algorithm_t algorithm) const override {
114        switch (algorithm) {
115        case KM_ALGORITHM_RSA:
116            return true;
117        case KM_ALGORITHM_EC:
118            return support_ec_;
119        default:
120            return false;
121        }
122    }
123    int keymaster0_calls() const override { return counting_keymaster0_device_->count(); }
124
125  private:
126    mutable Keymaster0CountingWrapper* counting_keymaster0_device_;
127    bool support_ec_;
128};
129
130static auto test_params = testing::Values(
131    InstanceCreatorPtr(new SoftKeymasterTestInstanceCreator),
132    InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(true /* support_ec */)),
133    InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(false /* support_ec */)));
134
135typedef Keymaster1Test CheckSupported;
136INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, CheckSupported, test_params);
137
138TEST_P(CheckSupported, SupportedAlgorithms) {
139    EXPECT_EQ(KM_ERROR_OUTPUT_PARAMETER_NULL,
140              device()->get_supported_algorithms(device(), NULL, NULL));
141
142    size_t len;
143    keymaster_algorithm_t* algorithms;
144    EXPECT_EQ(KM_ERROR_OK, device()->get_supported_algorithms(device(), &algorithms, &len));
145    EXPECT_TRUE(ResponseContains(
146        {KM_ALGORITHM_RSA, KM_ALGORITHM_EC, KM_ALGORITHM_AES, KM_ALGORITHM_HMAC}, algorithms, len));
147    free(algorithms);
148
149    EXPECT_EQ(0, GetParam()->keymaster0_calls());
150}
151
152TEST_P(CheckSupported, SupportedBlockModes) {
153    EXPECT_EQ(KM_ERROR_OUTPUT_PARAMETER_NULL,
154              device()->get_supported_block_modes(device(), KM_ALGORITHM_RSA, KM_PURPOSE_ENCRYPT,
155                                                  NULL, NULL));
156
157    size_t len;
158    keymaster_block_mode_t* modes;
159    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_block_modes(device(), KM_ALGORITHM_RSA,
160                                                               KM_PURPOSE_ENCRYPT, &modes, &len));
161    EXPECT_EQ(0U, len);
162    free(modes);
163
164    EXPECT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE,
165              device()->get_supported_block_modes(device(), KM_ALGORITHM_EC, KM_PURPOSE_ENCRYPT,
166                                                  &modes, &len));
167
168    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_block_modes(device(), KM_ALGORITHM_AES,
169                                                               KM_PURPOSE_ENCRYPT, &modes, &len));
170    EXPECT_TRUE(ResponseContains({KM_MODE_ECB, KM_MODE_CBC, KM_MODE_CTR, KM_MODE_GCM}, modes, len));
171    free(modes);
172
173    EXPECT_EQ(0, GetParam()->keymaster0_calls());
174}
175
176TEST_P(CheckSupported, SupportedPaddingModes) {
177    EXPECT_EQ(KM_ERROR_OUTPUT_PARAMETER_NULL,
178              device()->get_supported_padding_modes(device(), KM_ALGORITHM_RSA, KM_PURPOSE_ENCRYPT,
179                                                    NULL, NULL));
180
181    size_t len;
182    keymaster_padding_t* modes;
183    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_padding_modes(device(), KM_ALGORITHM_RSA,
184                                                                 KM_PURPOSE_SIGN, &modes, &len));
185    EXPECT_TRUE(
186        ResponseContains({KM_PAD_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN, KM_PAD_RSA_PSS}, modes, len));
187    free(modes);
188
189    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_padding_modes(device(), KM_ALGORITHM_RSA,
190                                                                 KM_PURPOSE_ENCRYPT, &modes, &len));
191    EXPECT_TRUE(
192        ResponseContains({KM_PAD_NONE, KM_PAD_RSA_OAEP, KM_PAD_RSA_PKCS1_1_5_ENCRYPT}, modes, len));
193    free(modes);
194
195    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_padding_modes(device(), KM_ALGORITHM_EC,
196                                                                 KM_PURPOSE_SIGN, &modes, &len));
197    EXPECT_EQ(0U, len);
198    free(modes);
199
200    EXPECT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE,
201              device()->get_supported_padding_modes(device(), KM_ALGORITHM_AES, KM_PURPOSE_SIGN,
202                                                    &modes, &len));
203
204    EXPECT_EQ(0, GetParam()->keymaster0_calls());
205}
206
207TEST_P(CheckSupported, SupportedDigests) {
208    EXPECT_EQ(
209        KM_ERROR_OUTPUT_PARAMETER_NULL,
210        device()->get_supported_digests(device(), KM_ALGORITHM_RSA, KM_PURPOSE_SIGN, NULL, NULL));
211
212    size_t len;
213    keymaster_digest_t* digests;
214    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_digests(device(), KM_ALGORITHM_RSA,
215                                                           KM_PURPOSE_SIGN, &digests, &len));
216    EXPECT_TRUE(
217        ResponseContains({KM_DIGEST_NONE, KM_DIGEST_MD5, KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224,
218                          KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512},
219                         digests, len));
220    free(digests);
221
222    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_digests(device(), KM_ALGORITHM_EC,
223                                                           KM_PURPOSE_SIGN, &digests, &len));
224    EXPECT_TRUE(
225        ResponseContains({KM_DIGEST_NONE, KM_DIGEST_MD5, KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224,
226                          KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512},
227                         digests, len));
228    free(digests);
229
230    EXPECT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE,
231              device()->get_supported_digests(device(), KM_ALGORITHM_AES, KM_PURPOSE_SIGN, &digests,
232                                              &len));
233
234    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_digests(device(), KM_ALGORITHM_HMAC,
235                                                           KM_PURPOSE_SIGN, &digests, &len));
236    EXPECT_TRUE(ResponseContains({KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384,
237                                  KM_DIGEST_SHA_2_512, KM_DIGEST_SHA1},
238                                 digests, len));
239    free(digests);
240
241    EXPECT_EQ(0, GetParam()->keymaster0_calls());
242}
243
244TEST_P(CheckSupported, SupportedImportFormats) {
245    EXPECT_EQ(KM_ERROR_OUTPUT_PARAMETER_NULL,
246              device()->get_supported_import_formats(device(), KM_ALGORITHM_RSA, NULL, NULL));
247
248    size_t len;
249    keymaster_key_format_t* formats;
250    ASSERT_EQ(KM_ERROR_OK,
251              device()->get_supported_import_formats(device(), KM_ALGORITHM_RSA, &formats, &len));
252    EXPECT_TRUE(ResponseContains(KM_KEY_FORMAT_PKCS8, formats, len));
253    free(formats);
254
255    ASSERT_EQ(KM_ERROR_OK,
256              device()->get_supported_import_formats(device(), KM_ALGORITHM_AES, &formats, &len));
257    EXPECT_TRUE(ResponseContains(KM_KEY_FORMAT_RAW, formats, len));
258    free(formats);
259
260    ASSERT_EQ(KM_ERROR_OK,
261              device()->get_supported_import_formats(device(), KM_ALGORITHM_HMAC, &formats, &len));
262    EXPECT_TRUE(ResponseContains(KM_KEY_FORMAT_RAW, formats, len));
263    free(formats);
264
265    EXPECT_EQ(0, GetParam()->keymaster0_calls());
266}
267
268TEST_P(CheckSupported, SupportedExportFormats) {
269    EXPECT_EQ(KM_ERROR_OUTPUT_PARAMETER_NULL,
270              device()->get_supported_export_formats(device(), KM_ALGORITHM_RSA, NULL, NULL));
271
272    size_t len;
273    keymaster_key_format_t* formats;
274    ASSERT_EQ(KM_ERROR_OK,
275              device()->get_supported_export_formats(device(), KM_ALGORITHM_RSA, &formats, &len));
276    EXPECT_TRUE(ResponseContains(KM_KEY_FORMAT_X509, formats, len));
277    free(formats);
278
279    ASSERT_EQ(KM_ERROR_OK,
280              device()->get_supported_export_formats(device(), KM_ALGORITHM_EC, &formats, &len));
281    EXPECT_TRUE(ResponseContains(KM_KEY_FORMAT_X509, formats, len));
282    free(formats);
283
284    ASSERT_EQ(KM_ERROR_OK,
285              device()->get_supported_export_formats(device(), KM_ALGORITHM_AES, &formats, &len));
286    EXPECT_EQ(0U, len);
287    free(formats);
288
289    ASSERT_EQ(KM_ERROR_OK,
290              device()->get_supported_export_formats(device(), KM_ALGORITHM_AES, &formats, &len));
291    EXPECT_EQ(0U, len);
292    free(formats);
293
294    ASSERT_EQ(KM_ERROR_OK,
295              device()->get_supported_export_formats(device(), KM_ALGORITHM_HMAC, &formats, &len));
296    EXPECT_EQ(0U, len);
297    free(formats);
298
299    EXPECT_EQ(0, GetParam()->keymaster0_calls());
300}
301
302class NewKeyGeneration : public Keymaster1Test {
303  protected:
304    void CheckBaseParams() {
305        AuthorizationSet auths = sw_enforced();
306        EXPECT_GT(auths.SerializedSize(), 12U);
307
308        EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_SIGN));
309        EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_VERIFY));
310        EXPECT_TRUE(contains(auths, TAG_USER_ID, 7));
311        EXPECT_TRUE(contains(auths, TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD));
312        EXPECT_TRUE(contains(auths, TAG_AUTH_TIMEOUT, 300));
313
314        // Verify that App ID, App data and ROT are NOT included.
315        EXPECT_FALSE(contains(auths, TAG_ROOT_OF_TRUST));
316        EXPECT_FALSE(contains(auths, TAG_APPLICATION_ID));
317        EXPECT_FALSE(contains(auths, TAG_APPLICATION_DATA));
318
319        // Just for giggles, check that some unexpected tags/values are NOT present.
320        EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
321        EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_DECRYPT));
322        EXPECT_FALSE(contains(auths, TAG_AUTH_TIMEOUT, 301));
323
324        // Now check that unspecified, defaulted tags are correct.
325        EXPECT_TRUE(contains(auths, TAG_ORIGIN, KM_ORIGIN_GENERATED));
326        EXPECT_TRUE(contains(auths, KM_TAG_CREATION_DATETIME));
327    }
328};
329INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, NewKeyGeneration, test_params);
330
331TEST_P(NewKeyGeneration, Rsa) {
332    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
333                                           .RsaSigningKey(256, 3)
334                                           .Digest(KM_DIGEST_NONE)
335                                           .Padding(KM_PAD_NONE)));
336    CheckBaseParams();
337
338    // Check specified tags are all present, and in the right set.
339    AuthorizationSet crypto_params;
340    AuthorizationSet non_crypto_params;
341    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA)) {
342        EXPECT_NE(0U, hw_enforced().size());
343        EXPECT_NE(0U, sw_enforced().size());
344        crypto_params.push_back(hw_enforced());
345        non_crypto_params.push_back(sw_enforced());
346    } else {
347        EXPECT_EQ(0U, hw_enforced().size());
348        EXPECT_NE(0U, sw_enforced().size());
349        crypto_params.push_back(sw_enforced());
350    }
351
352    EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
353    EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
354    EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 256));
355    EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 256));
356    EXPECT_TRUE(contains(crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
357    EXPECT_FALSE(contains(non_crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
358
359    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
360        EXPECT_EQ(1, GetParam()->keymaster0_calls());
361}
362
363TEST_P(NewKeyGeneration, RsaDefaultSize) {
364    ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
365              GenerateKey(AuthorizationSetBuilder()
366                              .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA)
367                              .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)
368                              .SigningKey()));
369
370    EXPECT_EQ(0, GetParam()->keymaster0_calls());
371}
372
373TEST_P(NewKeyGeneration, Ecdsa) {
374    ASSERT_EQ(KM_ERROR_OK,
375              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
376    CheckBaseParams();
377
378    // Check specified tags are all present, and in the right set.
379    AuthorizationSet crypto_params;
380    AuthorizationSet non_crypto_params;
381    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC)) {
382        EXPECT_NE(0U, hw_enforced().size());
383        EXPECT_NE(0U, sw_enforced().size());
384        crypto_params.push_back(hw_enforced());
385        non_crypto_params.push_back(sw_enforced());
386    } else {
387        EXPECT_EQ(0U, hw_enforced().size());
388        EXPECT_NE(0U, sw_enforced().size());
389        crypto_params.push_back(sw_enforced());
390    }
391
392    EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
393    EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
394    EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 224));
395    EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 224));
396
397    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
398        EXPECT_EQ(1, GetParam()->keymaster0_calls());
399}
400
401TEST_P(NewKeyGeneration, EcdsaDefaultSize) {
402    ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
403              GenerateKey(AuthorizationSetBuilder()
404                              .Authorization(TAG_ALGORITHM, KM_ALGORITHM_EC)
405                              .SigningKey()
406                              .Digest(KM_DIGEST_NONE)));
407
408    EXPECT_EQ(0, GetParam()->keymaster0_calls());
409}
410
411TEST_P(NewKeyGeneration, EcdsaInvalidSize) {
412    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
413        ASSERT_EQ(
414            KM_ERROR_UNKNOWN_ERROR,
415            GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(KM_DIGEST_NONE)));
416    else
417        ASSERT_EQ(
418            KM_ERROR_UNSUPPORTED_KEY_SIZE,
419            GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(KM_DIGEST_NONE)));
420
421    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
422        EXPECT_EQ(1, GetParam()->keymaster0_calls());
423}
424
425TEST_P(NewKeyGeneration, EcdsaAllValidSizes) {
426    size_t valid_sizes[] = {224, 256, 384, 521};
427    for (size_t size : valid_sizes) {
428        EXPECT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(size).Digest(
429                                   KM_DIGEST_NONE)))
430            << "Failed to generate size: " << size;
431    }
432
433    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
434        EXPECT_EQ(4, GetParam()->keymaster0_calls());
435}
436
437TEST_P(NewKeyGeneration, HmacSha256) {
438    ASSERT_EQ(KM_ERROR_OK,
439              GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA_2_256)));
440
441    EXPECT_EQ(0, GetParam()->keymaster0_calls());
442}
443
444typedef Keymaster1Test GetKeyCharacteristics;
445INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, GetKeyCharacteristics, test_params);
446
447TEST_P(GetKeyCharacteristics, SimpleRsa) {
448    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
449                                           .RsaSigningKey(256, 3)
450                                           .Digest(KM_DIGEST_NONE)
451                                           .Padding(KM_PAD_NONE)));
452    AuthorizationSet original(sw_enforced());
453
454    ASSERT_EQ(KM_ERROR_OK, GetCharacteristics());
455    EXPECT_EQ(original, sw_enforced());
456
457    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
458        EXPECT_EQ(1, GetParam()->keymaster0_calls());
459}
460
461typedef Keymaster1Test SigningOperationsTest;
462INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, SigningOperationsTest, test_params);
463
464TEST_P(SigningOperationsTest, RsaSuccess) {
465    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
466                                           .RsaSigningKey(256, 3)
467                                           .Digest(KM_DIGEST_NONE)
468                                           .Padding(KM_PAD_NONE)));
469    string message = "12345678901234567890123456789012";
470    string signature;
471    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
472
473    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
474        EXPECT_EQ(3, GetParam()->keymaster0_calls());
475}
476
477TEST_P(SigningOperationsTest, RsaPssSha256Success) {
478    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
479                                           .RsaSigningKey(512, 3)
480                                           .Digest(KM_DIGEST_SHA_2_256)
481                                           .Padding(KM_PAD_RSA_PSS)));
482    // Use large message, which won't work without digesting.
483    string message(1024, 'a');
484    string signature;
485    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
486
487    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
488        EXPECT_EQ(3, GetParam()->keymaster0_calls());
489}
490
491TEST_P(SigningOperationsTest, RsaPaddingNoneAllowsOther) {
492    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
493                                           .RsaSigningKey(512, 3)
494                                           .Digest(KM_DIGEST_NONE)
495                                           .Padding(KM_PAD_NONE)));
496    string message = "12345678901234567890123456789012";
497    string signature;
498    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
499
500    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
501        EXPECT_EQ(3, GetParam()->keymaster0_calls());
502}
503
504TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
505    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
506                                           .RsaSigningKey(512, 3)
507                                           .Digest(KM_DIGEST_SHA_2_256)
508                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
509    string message(1024, 'a');
510    string signature;
511    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
512
513    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
514        EXPECT_EQ(3, GetParam()->keymaster0_calls());
515}
516
517TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
518    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
519                                           .RsaSigningKey(512, 3)
520                                           .Digest(KM_DIGEST_NONE)
521                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
522    string message(53, 'a');
523    string signature;
524    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN);
525
526    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
527        EXPECT_EQ(3, GetParam()->keymaster0_calls());
528}
529
530TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLarge) {
531    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
532                                           .RsaSigningKey(512, 3)
533                                           .Digest(KM_DIGEST_NONE)
534                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
535    string message(54, 'a');
536
537    AuthorizationSet begin_params(client_params());
538    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
539    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
540    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
541    string result;
542    size_t input_consumed;
543    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
544    string signature;
545    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&signature));
546
547    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
548        EXPECT_EQ(2, GetParam()->keymaster0_calls());
549}
550
551TEST_P(SigningOperationsTest, RsaPssSha256TooSmallKey) {
552    // Key must be at least 10 bytes larger than hash, to provide eight bytes of random salt, so
553    // verify that nine bytes larger than hash won't work.
554    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
555                                           .RsaSigningKey(256 + 9 * 8, 3)
556                                           .Digest(KM_DIGEST_SHA_2_256)
557                                           .Padding(KM_PAD_RSA_PSS)));
558    string message(1024, 'a');
559    string signature;
560
561    AuthorizationSet begin_params(client_params());
562    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
563    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
564    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
565}
566
567TEST_P(SigningOperationsTest, RsaNoPaddingHugeData) {
568    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
569                                           .RsaSigningKey(256, 3)
570                                           .Digest(KM_DIGEST_NONE)
571                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
572    string message(64 * 1024, 'a');
573    string signature;
574    AuthorizationSet begin_params(client_params());
575    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
576    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
577    ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
578    string result;
579    size_t input_consumed;
580    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
581
582    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
583        EXPECT_EQ(2, GetParam()->keymaster0_calls());
584}
585
586TEST_P(SigningOperationsTest, RsaAbort) {
587    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
588                                           .RsaSigningKey(256, 3)
589                                           .Digest(KM_DIGEST_NONE)
590                                           .Padding(KM_PAD_NONE)));
591    AuthorizationSet begin_params(client_params());
592    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
593    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
594    ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
595    EXPECT_EQ(KM_ERROR_OK, AbortOperation());
596    // Another abort should fail
597    EXPECT_EQ(KM_ERROR_INVALID_OPERATION_HANDLE, AbortOperation());
598
599    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
600        EXPECT_EQ(2, GetParam()->keymaster0_calls());
601}
602
603TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
604    GenerateKey(AuthorizationSetBuilder()
605                    .RsaSigningKey(256, 3)
606                    .Digest(KM_DIGEST_SHA_2_256 /* supported digest */)
607                    .Padding(KM_PAD_PKCS7));
608    AuthorizationSet begin_params(client_params());
609    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
610    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
611
612    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
613        EXPECT_EQ(2, GetParam()->keymaster0_calls());
614}
615
616TEST_P(SigningOperationsTest, RsaNoDigest) {
617    // PSS requires a digest.
618    GenerateKey(AuthorizationSetBuilder()
619                    .RsaSigningKey(256, 3)
620                    .Digest(KM_DIGEST_NONE)
621                    .Padding(KM_PAD_RSA_PSS));
622    AuthorizationSet begin_params(client_params());
623    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
624    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
625    ASSERT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
626
627    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
628        EXPECT_EQ(2, GetParam()->keymaster0_calls());
629}
630
631TEST_P(SigningOperationsTest, RsaNoPadding) {
632    // Padding must be specified
633    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaKey(256, 3).SigningKey().Digest(
634                               KM_DIGEST_NONE)));
635    AuthorizationSet begin_params(client_params());
636    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
637    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
638
639    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
640        EXPECT_EQ(2, GetParam()->keymaster0_calls());
641}
642
643TEST_P(SigningOperationsTest, RsaTooShortMessage) {
644    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
645                                           .RsaSigningKey(256, 3)
646                                           .Digest(KM_DIGEST_NONE)
647                                           .Padding(KM_PAD_NONE)));
648    AuthorizationSet begin_params(client_params());
649    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
650    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
651    ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
652
653    string message = "1234567890123456789012345678901";
654    string result;
655    size_t input_consumed;
656    ASSERT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
657    EXPECT_EQ(0U, result.size());
658    EXPECT_EQ(31U, input_consumed);
659
660    string signature;
661    ASSERT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&signature));
662    EXPECT_EQ(0U, signature.length());
663
664    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
665        EXPECT_EQ(2, GetParam()->keymaster0_calls());
666}
667
668TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
669    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
670                                           .RsaEncryptionKey(256, 3)
671                                           .Digest(KM_DIGEST_NONE)
672                                           .Padding(KM_PAD_NONE)));
673    AuthorizationSet begin_params(client_params());
674    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
675    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
676    ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
677
678    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
679        EXPECT_EQ(2, GetParam()->keymaster0_calls());
680}
681
682TEST_P(SigningOperationsTest, EcdsaSuccess) {
683    ASSERT_EQ(KM_ERROR_OK,
684              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
685    string message(224 / 8, 'a');
686    string signature;
687    SignMessage(message, &signature, KM_DIGEST_NONE);
688
689    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
690        EXPECT_EQ(3, GetParam()->keymaster0_calls());
691}
692
693TEST_P(SigningOperationsTest, EcdsaSha256Success) {
694    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(
695                               KM_DIGEST_SHA_2_256)));
696    string message(1024, 'a');
697    string signature;
698    SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
699
700    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
701        EXPECT_EQ(3, GetParam()->keymaster0_calls());
702}
703
704TEST_P(SigningOperationsTest, EcdsaNoPaddingHugeData) {
705    ASSERT_EQ(KM_ERROR_OK,
706              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
707    string message(64 * 1024, 'a');
708    string signature;
709    AuthorizationSet begin_params(client_params());
710    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
711    ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
712    string result;
713    size_t input_consumed;
714    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
715
716    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
717        EXPECT_EQ(2, GetParam()->keymaster0_calls());
718}
719
720TEST_P(SigningOperationsTest, AesEcbSign) {
721    ASSERT_EQ(KM_ERROR_OK,
722              GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128).Authorization(
723                  TAG_BLOCK_MODE, KM_MODE_ECB)));
724    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_SIGN));
725    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_VERIFY));
726
727    EXPECT_EQ(0, GetParam()->keymaster0_calls());
728}
729
730TEST_P(SigningOperationsTest, HmacSha1Success) {
731    GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA1));
732    string message = "12345678901234567890123456789012";
733    string signature;
734    MacMessage(message, &signature, KM_DIGEST_SHA1, 160);
735    ASSERT_EQ(20U, signature.size());
736
737    EXPECT_EQ(0, GetParam()->keymaster0_calls());
738}
739
740TEST_P(SigningOperationsTest, HmacSha224Success) {
741    ASSERT_EQ(KM_ERROR_OK,
742              GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA_2_224)));
743    string message = "12345678901234567890123456789012";
744    string signature;
745    MacMessage(message, &signature, KM_DIGEST_SHA_2_224, 224);
746    ASSERT_EQ(28U, signature.size());
747
748    EXPECT_EQ(0, GetParam()->keymaster0_calls());
749}
750
751TEST_P(SigningOperationsTest, HmacSha256Success) {
752    ASSERT_EQ(KM_ERROR_OK,
753              GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA_2_256)));
754    string message = "12345678901234567890123456789012";
755    string signature;
756    MacMessage(message, &signature, KM_DIGEST_SHA_2_256, 256);
757    ASSERT_EQ(32U, signature.size());
758
759    EXPECT_EQ(0, GetParam()->keymaster0_calls());
760}
761
762TEST_P(SigningOperationsTest, HmacSha384Success) {
763    ASSERT_EQ(KM_ERROR_OK,
764              GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA_2_384)));
765
766    string message = "12345678901234567890123456789012";
767    string signature;
768    MacMessage(message, &signature, KM_DIGEST_SHA_2_384, 384);
769    ASSERT_EQ(48U, signature.size());
770
771    EXPECT_EQ(0, GetParam()->keymaster0_calls());
772}
773
774TEST_P(SigningOperationsTest, HmacSha512Success) {
775    ASSERT_EQ(KM_ERROR_OK,
776              GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA_2_512)));
777    string message = "12345678901234567890123456789012";
778    string signature;
779    MacMessage(message, &signature, KM_DIGEST_SHA_2_512, 512);
780    ASSERT_EQ(64U, signature.size());
781
782    EXPECT_EQ(0, GetParam()->keymaster0_calls());
783}
784
785TEST_P(SigningOperationsTest, HmacAnyDigestSuccess) {
786    ASSERT_EQ(KM_ERROR_OK,
787              GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_NONE)));
788    string message = "12345678901234567890123456789012";
789    string signature;
790
791    size_t len;
792    keymaster_digest_t* digests;
793    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_digests(device(), KM_ALGORITHM_HMAC,
794                                                           KM_PURPOSE_SIGN, &digests, &len));
795    for (size_t i = 0; i < len; ++i)
796        MacMessage(message, &signature, digests[i], 128 /* small MAC to work with all digests */);
797    free(digests);
798
799    // Ensure that we can't actually try to do an HMAC with no digest
800    AuthorizationSet begin_params(client_params());
801    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
802    begin_params.push_back(TAG_MAC_LENGTH, 128);
803    EXPECT_EQ(KM_ERROR_UNSUPPORTED_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
804
805    EXPECT_EQ(0, GetParam()->keymaster0_calls());
806}
807
808TEST_P(SigningOperationsTest, HmacLengthInKey) {
809    // TODO(swillden): unified API should generate an error on key generation.
810    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
811                                           .HmacKey(128)
812                                           .Digest(KM_DIGEST_SHA_2_256)
813                                           .Authorization(TAG_MAC_LENGTH, 20)));
814    string message = "12345678901234567890123456789012";
815    string signature;
816    MacMessage(message, &signature, KM_DIGEST_SHA_2_256, 240);
817    // Size in key was ignored.
818    ASSERT_EQ(30U, signature.size());
819
820    EXPECT_EQ(0, GetParam()->keymaster0_calls());
821}
822
823TEST_P(SigningOperationsTest, HmacRfc4231TestCase1) {
824    uint8_t key_data[] = {
825        0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
826        0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
827    };
828    string message = "Hi There";
829    uint8_t sha_224_expected[] = {
830        0x89, 0x6f, 0xb1, 0x12, 0x8a, 0xbb, 0xdf, 0x19, 0x68, 0x32, 0x10, 0x7c, 0xd4, 0x9d,
831        0xf3, 0x3f, 0x47, 0xb4, 0xb1, 0x16, 0x99, 0x12, 0xba, 0x4f, 0x53, 0x68, 0x4b, 0x22,
832    };
833    uint8_t sha_256_expected[] = {
834        0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf,
835        0xce, 0xaf, 0x0b, 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83,
836        0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7,
837    };
838    uint8_t sha_384_expected[] = {
839        0xaf, 0xd0, 0x39, 0x44, 0xd8, 0x48, 0x95, 0x62, 0x6b, 0x08, 0x25, 0xf4,
840        0xab, 0x46, 0x90, 0x7f, 0x15, 0xf9, 0xda, 0xdb, 0xe4, 0x10, 0x1e, 0xc6,
841        0x82, 0xaa, 0x03, 0x4c, 0x7c, 0xeb, 0xc5, 0x9c, 0xfa, 0xea, 0x9e, 0xa9,
842        0x07, 0x6e, 0xde, 0x7f, 0x4a, 0xf1, 0x52, 0xe8, 0xb2, 0xfa, 0x9c, 0xb6,
843    };
844    uint8_t sha_512_expected[] = {
845        0x87, 0xaa, 0x7c, 0xde, 0xa5, 0xef, 0x61, 0x9d, 0x4f, 0xf0, 0xb4, 0x24, 0x1a,
846        0x1d, 0x6c, 0xb0, 0x23, 0x79, 0xf4, 0xe2, 0xce, 0x4e, 0xc2, 0x78, 0x7a, 0xd0,
847        0xb3, 0x05, 0x45, 0xe1, 0x7c, 0xde, 0xda, 0xa8, 0x33, 0xb7, 0xd6, 0xb8, 0xa7,
848        0x02, 0x03, 0x8b, 0x27, 0x4e, 0xae, 0xa3, 0xf4, 0xe4, 0xbe, 0x9d, 0x91, 0x4e,
849        0xeb, 0x61, 0xf1, 0x70, 0x2e, 0x69, 0x6c, 0x20, 0x3a, 0x12, 0x68, 0x54,
850    };
851
852    string key = make_string(key_data);
853
854    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
855    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
856    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
857    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
858
859    EXPECT_EQ(0, GetParam()->keymaster0_calls());
860}
861
862TEST_P(SigningOperationsTest, HmacRfc4231TestCase2) {
863    string key = "Jefe";
864    string message = "what do ya want for nothing?";
865    uint8_t sha_224_expected[] = {
866        0xa3, 0x0e, 0x01, 0x09, 0x8b, 0xc6, 0xdb, 0xbf, 0x45, 0x69, 0x0f, 0x3a, 0x7e, 0x9e,
867        0x6d, 0x0f, 0x8b, 0xbe, 0xa2, 0xa3, 0x9e, 0x61, 0x48, 0x00, 0x8f, 0xd0, 0x5e, 0x44,
868    };
869    uint8_t sha_256_expected[] = {
870        0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24,
871        0x26, 0x08, 0x95, 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27,
872        0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec, 0x38, 0x43,
873    };
874    uint8_t sha_384_expected[] = {
875        0xaf, 0x45, 0xd2, 0xe3, 0x76, 0x48, 0x40, 0x31, 0x61, 0x7f, 0x78, 0xd2,
876        0xb5, 0x8a, 0x6b, 0x1b, 0x9c, 0x7e, 0xf4, 0x64, 0xf5, 0xa0, 0x1b, 0x47,
877        0xe4, 0x2e, 0xc3, 0x73, 0x63, 0x22, 0x44, 0x5e, 0x8e, 0x22, 0x40, 0xca,
878        0x5e, 0x69, 0xe2, 0xc7, 0x8b, 0x32, 0x39, 0xec, 0xfa, 0xb2, 0x16, 0x49,
879    };
880    uint8_t sha_512_expected[] = {
881        0x16, 0x4b, 0x7a, 0x7b, 0xfc, 0xf8, 0x19, 0xe2, 0xe3, 0x95, 0xfb, 0xe7, 0x3b,
882        0x56, 0xe0, 0xa3, 0x87, 0xbd, 0x64, 0x22, 0x2e, 0x83, 0x1f, 0xd6, 0x10, 0x27,
883        0x0c, 0xd7, 0xea, 0x25, 0x05, 0x54, 0x97, 0x58, 0xbf, 0x75, 0xc0, 0x5a, 0x99,
884        0x4a, 0x6d, 0x03, 0x4f, 0x65, 0xf8, 0xf0, 0xe6, 0xfd, 0xca, 0xea, 0xb1, 0xa3,
885        0x4d, 0x4a, 0x6b, 0x4b, 0x63, 0x6e, 0x07, 0x0a, 0x38, 0xbc, 0xe7, 0x37,
886    };
887
888    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
889    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
890    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
891    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
892
893    EXPECT_EQ(0, GetParam()->keymaster0_calls());
894}
895
896TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
897    string key(20, 0xaa);
898    string message(50, 0xdd);
899    uint8_t sha_224_expected[] = {
900        0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
901        0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
902    };
903    uint8_t sha_256_expected[] = {
904        0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
905        0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
906        0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
907    };
908    uint8_t sha_384_expected[] = {
909        0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
910        0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
911        0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
912        0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
913    };
914    uint8_t sha_512_expected[] = {
915        0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
916        0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
917        0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
918        0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
919        0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
920    };
921
922    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
923    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
924    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
925    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
926
927    EXPECT_EQ(0, GetParam()->keymaster0_calls());
928}
929
930TEST_P(SigningOperationsTest, HmacRfc4231TestCase4) {
931    uint8_t key_data[25] = {
932        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
933        0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
934    };
935    string key = make_string(key_data);
936    string message(50, 0xcd);
937    uint8_t sha_224_expected[] = {
938        0x6c, 0x11, 0x50, 0x68, 0x74, 0x01, 0x3c, 0xac, 0x6a, 0x2a, 0xbc, 0x1b, 0xb3, 0x82,
939        0x62, 0x7c, 0xec, 0x6a, 0x90, 0xd8, 0x6e, 0xfc, 0x01, 0x2d, 0xe7, 0xaf, 0xec, 0x5a,
940    };
941    uint8_t sha_256_expected[] = {
942        0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81,
943        0x98, 0x99, 0xf2, 0x08, 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78,
944        0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29, 0x66, 0x5b,
945    };
946    uint8_t sha_384_expected[] = {
947        0x3e, 0x8a, 0x69, 0xb7, 0x78, 0x3c, 0x25, 0x85, 0x19, 0x33, 0xab, 0x62,
948        0x90, 0xaf, 0x6c, 0xa7, 0x7a, 0x99, 0x81, 0x48, 0x08, 0x50, 0x00, 0x9c,
949        0xc5, 0x57, 0x7c, 0x6e, 0x1f, 0x57, 0x3b, 0x4e, 0x68, 0x01, 0xdd, 0x23,
950        0xc4, 0xa7, 0xd6, 0x79, 0xcc, 0xf8, 0xa3, 0x86, 0xc6, 0x74, 0xcf, 0xfb,
951    };
952    uint8_t sha_512_expected[] = {
953        0xb0, 0xba, 0x46, 0x56, 0x37, 0x45, 0x8c, 0x69, 0x90, 0xe5, 0xa8, 0xc5, 0xf6,
954        0x1d, 0x4a, 0xf7, 0xe5, 0x76, 0xd9, 0x7f, 0xf9, 0x4b, 0x87, 0x2d, 0xe7, 0x6f,
955        0x80, 0x50, 0x36, 0x1e, 0xe3, 0xdb, 0xa9, 0x1c, 0xa5, 0xc1, 0x1a, 0xa2, 0x5e,
956        0xb4, 0xd6, 0x79, 0x27, 0x5c, 0xc5, 0x78, 0x80, 0x63, 0xa5, 0xf1, 0x97, 0x41,
957        0x12, 0x0c, 0x4f, 0x2d, 0xe2, 0xad, 0xeb, 0xeb, 0x10, 0xa2, 0x98, 0xdd,
958    };
959
960    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
961    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
962    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
963    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
964
965    EXPECT_EQ(0, GetParam()->keymaster0_calls());
966}
967
968TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
969    string key(20, 0x0c);
970    string message = "Test With Truncation";
971
972    uint8_t sha_224_expected[] = {
973        0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
974        0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
975    };
976    uint8_t sha_256_expected[] = {
977        0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
978        0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
979    };
980    uint8_t sha_384_expected[] = {
981        0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
982        0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
983    };
984    uint8_t sha_512_expected[] = {
985        0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
986        0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
987    };
988
989    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
990    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
991    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
992    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
993
994    EXPECT_EQ(0, GetParam()->keymaster0_calls());
995}
996
997TEST_P(SigningOperationsTest, HmacRfc4231TestCase6) {
998    string key(131, 0xaa);
999    string message = "Test Using Larger Than Block-Size Key - Hash Key First";
1000
1001    uint8_t sha_224_expected[] = {
1002        0x95, 0xe9, 0xa0, 0xdb, 0x96, 0x20, 0x95, 0xad, 0xae, 0xbe, 0x9b, 0x2d, 0x6f, 0x0d,
1003        0xbc, 0xe2, 0xd4, 0x99, 0xf1, 0x12, 0xf2, 0xd2, 0xb7, 0x27, 0x3f, 0xa6, 0x87, 0x0e,
1004    };
1005    uint8_t sha_256_expected[] = {
1006        0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26,
1007        0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28,
1008        0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54,
1009    };
1010    uint8_t sha_384_expected[] = {
1011        0x4e, 0xce, 0x08, 0x44, 0x85, 0x81, 0x3e, 0x90, 0x88, 0xd2, 0xc6, 0x3a,
1012        0x04, 0x1b, 0xc5, 0xb4, 0x4f, 0x9e, 0xf1, 0x01, 0x2a, 0x2b, 0x58, 0x8f,
1013        0x3c, 0xd1, 0x1f, 0x05, 0x03, 0x3a, 0xc4, 0xc6, 0x0c, 0x2e, 0xf6, 0xab,
1014        0x40, 0x30, 0xfe, 0x82, 0x96, 0x24, 0x8d, 0xf1, 0x63, 0xf4, 0x49, 0x52,
1015    };
1016    uint8_t sha_512_expected[] = {
1017        0x80, 0xb2, 0x42, 0x63, 0xc7, 0xc1, 0xa3, 0xeb, 0xb7, 0x14, 0x93, 0xc1, 0xdd,
1018        0x7b, 0xe8, 0xb4, 0x9b, 0x46, 0xd1, 0xf4, 0x1b, 0x4a, 0xee, 0xc1, 0x12, 0x1b,
1019        0x01, 0x37, 0x83, 0xf8, 0xf3, 0x52, 0x6b, 0x56, 0xd0, 0x37, 0xe0, 0x5f, 0x25,
1020        0x98, 0xbd, 0x0f, 0xd2, 0x21, 0x5d, 0x6a, 0x1e, 0x52, 0x95, 0xe6, 0x4f, 0x73,
1021        0xf6, 0x3f, 0x0a, 0xec, 0x8b, 0x91, 0x5a, 0x98, 0x5d, 0x78, 0x65, 0x98,
1022    };
1023
1024    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1025    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1026    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1027    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1028
1029    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1030}
1031
1032TEST_P(SigningOperationsTest, HmacRfc4231TestCase7) {
1033    string key(131, 0xaa);
1034    string message = "This is a test using a larger than block-size key and a larger than "
1035                     "block-size data. The key needs to be hashed before being used by the HMAC "
1036                     "algorithm.";
1037
1038    uint8_t sha_224_expected[] = {
1039        0x3a, 0x85, 0x41, 0x66, 0xac, 0x5d, 0x9f, 0x02, 0x3f, 0x54, 0xd5, 0x17, 0xd0, 0xb3,
1040        0x9d, 0xbd, 0x94, 0x67, 0x70, 0xdb, 0x9c, 0x2b, 0x95, 0xc9, 0xf6, 0xf5, 0x65, 0xd1,
1041    };
1042    uint8_t sha_256_expected[] = {
1043        0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f,
1044        0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07,
1045        0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2,
1046    };
1047    uint8_t sha_384_expected[] = {
1048        0x66, 0x17, 0x17, 0x8e, 0x94, 0x1f, 0x02, 0x0d, 0x35, 0x1e, 0x2f, 0x25,
1049        0x4e, 0x8f, 0xd3, 0x2c, 0x60, 0x24, 0x20, 0xfe, 0xb0, 0xb8, 0xfb, 0x9a,
1050        0xdc, 0xce, 0xbb, 0x82, 0x46, 0x1e, 0x99, 0xc5, 0xa6, 0x78, 0xcc, 0x31,
1051        0xe7, 0x99, 0x17, 0x6d, 0x38, 0x60, 0xe6, 0x11, 0x0c, 0x46, 0x52, 0x3e,
1052    };
1053    uint8_t sha_512_expected[] = {
1054        0xe3, 0x7b, 0x6a, 0x77, 0x5d, 0xc8, 0x7d, 0xba, 0xa4, 0xdf, 0xa9, 0xf9, 0x6e,
1055        0x5e, 0x3f, 0xfd, 0xde, 0xbd, 0x71, 0xf8, 0x86, 0x72, 0x89, 0x86, 0x5d, 0xf5,
1056        0xa3, 0x2d, 0x20, 0xcd, 0xc9, 0x44, 0xb6, 0x02, 0x2c, 0xac, 0x3c, 0x49, 0x82,
1057        0xb1, 0x0d, 0x5e, 0xeb, 0x55, 0xc3, 0xe4, 0xde, 0x15, 0x13, 0x46, 0x76, 0xfb,
1058        0x6d, 0xe0, 0x44, 0x60, 0x65, 0xc9, 0x74, 0x40, 0xfa, 0x8c, 0x6a, 0x58,
1059    };
1060
1061    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1062    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1063    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1064    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1065
1066    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1067}
1068
1069TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1070    ASSERT_EQ(KM_ERROR_OK,
1071              GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA_2_256)));
1072    AuthorizationSet begin_params(client_params());
1073    begin_params.push_back(TAG_MAC_LENGTH, 264);
1074    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1075    ASSERT_EQ(KM_ERROR_OK,
1076              BeginOperation(KM_PURPOSE_SIGN, begin_params, nullptr /* output_params */));
1077    string message = "1234567890123456789012345678901";
1078    string result;
1079    size_t input_consumed;
1080    ASSERT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1081    ASSERT_EQ(KM_ERROR_UNSUPPORTED_MAC_LENGTH, FinishOperation(&result));
1082
1083    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1084}
1085
1086// TODO(swillden): Add more verification failure tests.
1087
1088typedef Keymaster1Test VerificationOperationsTest;
1089INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, VerificationOperationsTest, test_params);
1090
1091TEST_P(VerificationOperationsTest, RsaSuccess) {
1092    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1093                                           .RsaSigningKey(256, 3)
1094                                           .Digest(KM_DIGEST_NONE)
1095                                           .Padding(KM_PAD_NONE)));
1096    string message = "12345678901234567890123456789012";
1097    string signature;
1098    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
1099    VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
1100
1101    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1102        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1103}
1104
1105TEST_P(VerificationOperationsTest, RsaPssSha256Success) {
1106    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1107                                           .RsaSigningKey(512, 3)
1108                                           .Digest(KM_DIGEST_SHA_2_256)
1109                                           .Padding(KM_PAD_RSA_PSS)));
1110    // Use large message, which won't work without digesting.
1111    string message(1024, 'a');
1112    string signature;
1113    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1114    VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1115
1116    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1117        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1118}
1119
1120TEST_P(VerificationOperationsTest, RsaPssSha256CorruptSignature) {
1121    GenerateKey(AuthorizationSetBuilder()
1122                    .RsaSigningKey(512, 3)
1123                    .Digest(KM_DIGEST_SHA_2_256)
1124                    .Padding(KM_PAD_RSA_PSS));
1125    string message(1024, 'a');
1126    string signature;
1127    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1128    ++signature[signature.size() / 2];
1129
1130    AuthorizationSet begin_params(client_params());
1131    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1132    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1133    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1134
1135    string result;
1136    size_t input_consumed;
1137    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1138    EXPECT_EQ(message.size(), input_consumed);
1139    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1140
1141    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1142        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1143}
1144
1145TEST_P(VerificationOperationsTest, RsaPssSha256CorruptInput) {
1146    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1147                                           .RsaSigningKey(512, 3)
1148                                           .Digest(KM_DIGEST_SHA_2_256)
1149                                           .Padding(KM_PAD_RSA_PSS)));
1150    // Use large message, which won't work without digesting.
1151    string message(1024, 'a');
1152    string signature;
1153    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1154    ++message[message.size() / 2];
1155
1156    AuthorizationSet begin_params(client_params());
1157    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1158    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1159    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1160
1161    string result;
1162    size_t input_consumed;
1163    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1164    EXPECT_EQ(message.size(), input_consumed);
1165    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1166
1167    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1168        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1169}
1170
1171TEST_P(VerificationOperationsTest, RsaPkcs1Sha256Success) {
1172    GenerateKey(AuthorizationSetBuilder()
1173                    .RsaSigningKey(512, 3)
1174                    .Digest(KM_DIGEST_SHA_2_256)
1175                    .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
1176    string message(1024, 'a');
1177    string signature;
1178    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1179    VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1180
1181    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1182        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1183}
1184
1185TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptSignature) {
1186    GenerateKey(AuthorizationSetBuilder()
1187                    .RsaSigningKey(512, 3)
1188                    .Digest(KM_DIGEST_SHA_2_256)
1189                    .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
1190    string message(1024, 'a');
1191    string signature;
1192    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1193    ++signature[signature.size() / 2];
1194
1195    AuthorizationSet begin_params(client_params());
1196    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1197    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1198    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1199
1200    string result;
1201    size_t input_consumed;
1202    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1203    EXPECT_EQ(message.size(), input_consumed);
1204    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1205
1206    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1207        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1208}
1209
1210TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptInput) {
1211    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1212                                           .RsaSigningKey(512, 3)
1213                                           .Digest(KM_DIGEST_SHA_2_256)
1214                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
1215    // Use large message, which won't work without digesting.
1216    string message(1024, 'a');
1217    string signature;
1218    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1219    ++message[message.size() / 2];
1220
1221    AuthorizationSet begin_params(client_params());
1222    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1223    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1224    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1225
1226    string result;
1227    size_t input_consumed;
1228    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1229    EXPECT_EQ(message.size(), input_consumed);
1230    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1231
1232    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1233        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1234}
1235
1236template <typename T> vector<T> make_vector(const T* array, size_t len) {
1237    return vector<T>(array, array + len);
1238}
1239
1240TEST_P(VerificationOperationsTest, RsaAllDigestAndPadCombinations) {
1241    // Get all supported digests and padding modes.
1242    size_t digests_len;
1243    keymaster_digest_t* digests;
1244    ASSERT_EQ(KM_ERROR_OK,
1245              device()->get_supported_digests(device(), KM_ALGORITHM_RSA, KM_PURPOSE_SIGN, &digests,
1246                                              &digests_len));
1247
1248    size_t padding_modes_len;
1249    keymaster_padding_t* padding_modes;
1250    ASSERT_EQ(KM_ERROR_OK,
1251              device()->get_supported_padding_modes(device(), KM_ALGORITHM_RSA, KM_PURPOSE_SIGN,
1252                                                    &padding_modes, &padding_modes_len));
1253
1254    // Try them.
1255    int trial_count = 0;
1256    for (keymaster_padding_t padding_mode : make_vector(padding_modes, padding_modes_len)) {
1257        for (keymaster_digest_t digest : make_vector(digests, digests_len)) {
1258            if (digest != KM_DIGEST_NONE && padding_mode == KM_PAD_NONE)
1259                // Digesting requires padding
1260                continue;
1261
1262            // Compute key & message size that will work.
1263            size_t key_bits = 0;
1264            size_t message_len = 1000;
1265
1266            if (digest == KM_DIGEST_NONE) {
1267                key_bits = 256;
1268                switch (padding_mode) {
1269                case KM_PAD_NONE:
1270                    // Match key size.
1271                    message_len = key_bits / 8;
1272                    break;
1273                case KM_PAD_RSA_PKCS1_1_5_SIGN:
1274                    message_len = key_bits / 8 - 11;
1275                    break;
1276                case KM_PAD_RSA_PSS:
1277                    // PSS requires a digest.
1278                    continue;
1279                default:
1280                    FAIL() << "Missing padding";
1281                    break;
1282                }
1283            } else {
1284                size_t digest_bits;
1285                switch (digest) {
1286                case KM_DIGEST_MD5:
1287                    digest_bits = 128;
1288                    break;
1289                case KM_DIGEST_SHA1:
1290                    digest_bits = 160;
1291                    break;
1292                case KM_DIGEST_SHA_2_224:
1293                    digest_bits = 224;
1294                    break;
1295                case KM_DIGEST_SHA_2_256:
1296                    digest_bits = 256;
1297                    break;
1298                case KM_DIGEST_SHA_2_384:
1299                    digest_bits = 384;
1300                    break;
1301                case KM_DIGEST_SHA_2_512:
1302                    digest_bits = 512;
1303                    break;
1304                default:
1305                    FAIL() << "Missing digest";
1306                }
1307
1308                switch (padding_mode) {
1309                case KM_PAD_RSA_PKCS1_1_5_SIGN:
1310                    key_bits = digest_bits + 8 * (11 + 19);
1311                    break;
1312                case KM_PAD_RSA_PSS:
1313                    key_bits = digest_bits + 8 * 10;
1314                    break;
1315                default:
1316                    FAIL() << "Missing padding";
1317                    break;
1318                }
1319            }
1320
1321            GenerateKey(AuthorizationSetBuilder()
1322                            .RsaSigningKey(key_bits, 3)
1323                            .Digest(digest)
1324                            .Padding(padding_mode));
1325            string message(message_len, 'a');
1326            string signature;
1327            SignMessage(message, &signature, digest, padding_mode);
1328            VerifyMessage(message, signature, digest, padding_mode);
1329            ++trial_count;
1330        }
1331    }
1332
1333    free(padding_modes);
1334    free(digests);
1335
1336    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1337        EXPECT_EQ(trial_count * 4, GetParam()->keymaster0_calls());
1338}
1339
1340TEST_P(VerificationOperationsTest, EcdsaSuccess) {
1341    ASSERT_EQ(KM_ERROR_OK,
1342              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
1343    string message = "12345678901234567890123456789012";
1344    string signature;
1345    SignMessage(message, &signature, KM_DIGEST_NONE);
1346    VerifyMessage(message, signature, KM_DIGEST_NONE);
1347
1348    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
1349        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1350}
1351
1352TEST_P(VerificationOperationsTest, EcdsaTooShort) {
1353    ASSERT_EQ(KM_ERROR_OK,
1354              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
1355    string message = "12345678901234567890";
1356    string signature;
1357    SignMessage(message, &signature, KM_DIGEST_NONE);
1358    VerifyMessage(message, signature, KM_DIGEST_NONE);
1359
1360    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
1361        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1362}
1363
1364TEST_P(VerificationOperationsTest, EcdsaTooLong) {
1365    ASSERT_EQ(KM_ERROR_OK,
1366              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
1367    string message = "1234567890123456789012345678901234";
1368    string signature;
1369
1370    AuthorizationSet begin_params(client_params());
1371    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
1372    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
1373    string output;
1374    size_t input_consumed;
1375    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &output, &input_consumed));
1376
1377    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
1378        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1379}
1380
1381TEST_P(VerificationOperationsTest, EcdsaSlightlyTooLong) {
1382    ASSERT_EQ(KM_ERROR_OK,
1383              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(521).Digest(KM_DIGEST_NONE)));
1384
1385    string message(66, 'a');
1386    string signature;
1387    SignMessage(message, &signature, KM_DIGEST_NONE);
1388    VerifyMessage(message, signature, KM_DIGEST_NONE);
1389
1390    // Modifying low-order bits doesn't matter, because they didn't get signed.  Ugh.
1391    message[65] ^= 7;
1392    VerifyMessage(message, signature, KM_DIGEST_NONE);
1393
1394    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
1395        EXPECT_EQ(5, GetParam()->keymaster0_calls());
1396}
1397
1398TEST_P(VerificationOperationsTest, EcdsaSha256Success) {
1399    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1400                                           .EcdsaSigningKey(256)
1401                                           .Digest(KM_DIGEST_SHA_2_256)
1402                                           .Digest(KM_DIGEST_NONE)));
1403    string message = "12345678901234567890123456789012";
1404    string signature;
1405    SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
1406    VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
1407
1408    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
1409        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1410
1411    // Just for giggles, try verifying with the wrong digest.
1412    AuthorizationSet begin_params(client_params());
1413    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
1414    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1415
1416    string result;
1417    size_t input_consumed;
1418    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1419    EXPECT_EQ(message.size(), input_consumed);
1420    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1421}
1422
1423TEST_P(VerificationOperationsTest, HmacSha1Success) {
1424    GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA1));
1425    string message = "123456789012345678901234567890123456789012345678";
1426    string signature;
1427    MacMessage(message, &signature, KM_DIGEST_SHA1, 160);
1428    VerifyMessage(message, signature, KM_DIGEST_SHA1);
1429
1430    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1431}
1432
1433TEST_P(VerificationOperationsTest, HmacSha224Success) {
1434    GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA_2_224));
1435    string message = "123456789012345678901234567890123456789012345678";
1436    string signature;
1437    MacMessage(message, &signature, KM_DIGEST_SHA_2_224, 224);
1438    VerifyMessage(message, signature, KM_DIGEST_SHA_2_224);
1439
1440    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1441}
1442
1443TEST_P(VerificationOperationsTest, HmacSha256Success) {
1444    GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA_2_256));
1445    string message = "123456789012345678901234567890123456789012345678";
1446    string signature;
1447    MacMessage(message, &signature, KM_DIGEST_SHA_2_256, 256);
1448    VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
1449
1450    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1451}
1452
1453TEST_P(VerificationOperationsTest, HmacSha384Success) {
1454    GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA_2_384));
1455    string message = "123456789012345678901234567890123456789012345678";
1456    string signature;
1457    MacMessage(message, &signature, KM_DIGEST_SHA_2_384, 384);
1458    VerifyMessage(message, signature, KM_DIGEST_SHA_2_384);
1459
1460    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1461}
1462
1463TEST_P(VerificationOperationsTest, HmacSha512Success) {
1464    GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_SHA_2_512));
1465    string message = "123456789012345678901234567890123456789012345678";
1466    string signature;
1467    MacMessage(message, &signature, KM_DIGEST_SHA_2_512, 512);
1468    VerifyMessage(message, signature, KM_DIGEST_SHA_2_512);
1469
1470    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1471}
1472
1473TEST_P(VerificationOperationsTest, HmacAnyDigestSuccess) {
1474    ASSERT_EQ(KM_ERROR_OK,
1475              GenerateKey(AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_NONE)));
1476    string message = "12345678901234567890123456789012";
1477    string signature;
1478
1479    size_t len;
1480    keymaster_digest_t* digests;
1481    ASSERT_EQ(KM_ERROR_OK, device()->get_supported_digests(device(), KM_ALGORITHM_HMAC,
1482                                                           KM_PURPOSE_SIGN, &digests, &len));
1483    for (size_t i = 0; i < len; ++i) {
1484        MacMessage(message, &signature, digests[i], 128 /* small MAC to work with all digests */);
1485        VerifyMessage(message, signature, digests[i]);
1486        if (len > 1) {
1487            size_t wrong_digest_index = (i == 0) ? 1 : 0;
1488            AuthorizationSet begin_params(client_params());
1489            begin_params.push_back(TAG_DIGEST, digests[wrong_digest_index]);
1490            begin_params.push_back(TAG_MAC_LENGTH, 128);
1491            EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1492            string output;
1493            size_t input_consumed;
1494            EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &output, &input_consumed));
1495            EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &output));
1496        }
1497    }
1498    free(digests);
1499
1500    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1501}
1502
1503typedef Keymaster1Test ExportKeyTest;
1504INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ExportKeyTest, test_params);
1505
1506TEST_P(ExportKeyTest, RsaSuccess) {
1507    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1508                                           .RsaSigningKey(256, 3)
1509                                           .Digest(KM_DIGEST_NONE)
1510                                           .Padding(KM_PAD_NONE)));
1511    string export_data;
1512    ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1513    EXPECT_GT(export_data.length(), 0U);
1514
1515    // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
1516
1517    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1518        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1519}
1520
1521TEST_P(ExportKeyTest, EcdsaSuccess) {
1522    ASSERT_EQ(KM_ERROR_OK,
1523              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
1524    string export_data;
1525    ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1526    EXPECT_GT(export_data.length(), 0U);
1527
1528    // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
1529
1530    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
1531        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1532}
1533
1534TEST_P(ExportKeyTest, RsaUnsupportedKeyFormat) {
1535    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1536                                           .RsaSigningKey(256, 3)
1537                                           .Digest(KM_DIGEST_NONE)
1538                                           .Padding(KM_PAD_NONE)));
1539    string export_data;
1540    ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
1541
1542    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1543        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1544}
1545
1546TEST_P(ExportKeyTest, RsaCorruptedKeyBlob) {
1547    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1548                                           .RsaSigningKey(256, 3)
1549                                           .Digest(KM_DIGEST_NONE)
1550                                           .Padding(KM_PAD_NONE)));
1551    corrupt_key_blob();
1552    string export_data;
1553    ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1554
1555    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1556        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1557}
1558
1559TEST_P(ExportKeyTest, AesKeyExportFails) {
1560    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128)));
1561    string export_data;
1562
1563    EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1564    EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
1565    EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_RAW, &export_data));
1566
1567    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1568}
1569
1570static string read_file(const string& file_name) {
1571    ifstream file_stream(file_name, std::ios::binary);
1572    istreambuf_iterator<char> file_begin(file_stream);
1573    istreambuf_iterator<char> file_end;
1574    return string(file_begin, file_end);
1575}
1576
1577typedef Keymaster1Test ImportKeyTest;
1578INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ImportKeyTest, test_params);
1579
1580TEST_P(ImportKeyTest, RsaSuccess) {
1581    string pk8_key = read_file("rsa_privkey_pk8.der");
1582    ASSERT_EQ(633U, pk8_key.size());
1583
1584    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
1585                                         .RsaSigningKey(1024, 65537)
1586                                         .Digest(KM_DIGEST_NONE)
1587                                         .Padding(KM_PAD_NONE),
1588                                     KM_KEY_FORMAT_PKCS8, pk8_key));
1589
1590    // Check values derived from the key.
1591    EXPECT_TRUE(contains(GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1592                                                                             : sw_enforced(),
1593                         TAG_ALGORITHM, KM_ALGORITHM_RSA));
1594    EXPECT_TRUE(contains(GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1595                                                                             : sw_enforced(),
1596                         TAG_KEY_SIZE, 1024));
1597    EXPECT_TRUE(contains(GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1598                                                                             : sw_enforced(),
1599                         TAG_RSA_PUBLIC_EXPONENT, 65537U));
1600
1601    // And values provided by AndroidKeymaster
1602    EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1603    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1604
1605    string message(1024 / 8, 'a');
1606    string signature;
1607    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
1608    VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
1609
1610    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1611        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1612}
1613
1614TEST_P(ImportKeyTest, OldApiRsaSuccess) {
1615    string pk8_key = read_file("rsa_privkey_pk8.der");
1616    ASSERT_EQ(633U, pk8_key.size());
1617
1618    // NOTE: This will break when the keymaster0 APIs are removed from keymaster1.  But at that
1619    // point softkeymaster will no longer support keymaster0 APIs anyway.
1620    uint8_t* key_blob;
1621    size_t key_blob_length;
1622    ASSERT_EQ(0,
1623              device()->import_keypair(device(), reinterpret_cast<const uint8_t*>(pk8_key.data()),
1624                                       pk8_key.size(), &key_blob, &key_blob_length));
1625    set_key_blob(key_blob, key_blob_length);
1626
1627    string message(1024 / 8, 'a');
1628    AuthorizationSet begin_params;  // Don't use client data.
1629    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
1630    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
1631    AuthorizationSet update_params;
1632    AuthorizationSet output_params;
1633    string signature =
1634        ProcessMessage(KM_PURPOSE_SIGN, message, begin_params, update_params, &output_params);
1635    ProcessMessage(KM_PURPOSE_VERIFY, message, signature, begin_params, update_params,
1636                   &output_params);
1637
1638    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1639        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1640}
1641
1642TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
1643    string pk8_key = read_file("rsa_privkey_pk8.der");
1644    ASSERT_EQ(633U, pk8_key.size());
1645    ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
1646              ImportKey(AuthorizationSetBuilder()
1647                            .RsaSigningKey(2048 /* Doesn't match key */, 3)
1648                            .Digest(KM_DIGEST_NONE)
1649                            .Padding(KM_PAD_NONE),
1650                        KM_KEY_FORMAT_PKCS8, pk8_key));
1651
1652    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1653}
1654
1655TEST_P(ImportKeyTest, RsaPublicExponenMismatch) {
1656    string pk8_key = read_file("rsa_privkey_pk8.der");
1657    ASSERT_EQ(633U, pk8_key.size());
1658    ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
1659              ImportKey(AuthorizationSetBuilder()
1660                            .RsaSigningKey(256, 3 /* Doesnt' match key */)
1661                            .Digest(KM_DIGEST_NONE)
1662                            .Padding(KM_PAD_NONE),
1663                        KM_KEY_FORMAT_PKCS8, pk8_key));
1664
1665    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1666}
1667
1668TEST_P(ImportKeyTest, EcdsaSuccess) {
1669    string pk8_key = read_file("ec_privkey_pk8.der");
1670    ASSERT_EQ(138U, pk8_key.size());
1671
1672    ASSERT_EQ(KM_ERROR_OK,
1673              ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
1674                        KM_KEY_FORMAT_PKCS8, pk8_key));
1675
1676    // Check values derived from the key.
1677    EXPECT_TRUE(
1678        contains(GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC) ? hw_enforced() : sw_enforced(),
1679                 TAG_ALGORITHM, KM_ALGORITHM_EC));
1680    EXPECT_TRUE(
1681        contains(GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC) ? hw_enforced() : sw_enforced(),
1682                 TAG_KEY_SIZE, 256));
1683
1684    // And values provided by AndroidKeymaster
1685    EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1686    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1687
1688    string message(32, 'a');
1689    string signature;
1690    SignMessage(message, &signature, KM_DIGEST_NONE);
1691    VerifyMessage(message, signature, KM_DIGEST_NONE);
1692
1693    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
1694        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1695}
1696
1697TEST_P(ImportKeyTest, EcdsaSizeSpecified) {
1698    string pk8_key = read_file("ec_privkey_pk8.der");
1699    ASSERT_EQ(138U, pk8_key.size());
1700
1701    ASSERT_EQ(KM_ERROR_OK,
1702              ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
1703                        KM_KEY_FORMAT_PKCS8, pk8_key));
1704
1705    // Check values derived from the key.
1706    EXPECT_TRUE(
1707        contains(GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC) ? hw_enforced() : sw_enforced(),
1708                 TAG_ALGORITHM, KM_ALGORITHM_EC));
1709    EXPECT_TRUE(
1710        contains(GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC) ? hw_enforced() : sw_enforced(),
1711                 TAG_KEY_SIZE, 256));
1712
1713    // And values provided by AndroidKeymaster
1714    EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1715    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1716
1717    string message(32, 'a');
1718    string signature;
1719    SignMessage(message, &signature, KM_DIGEST_NONE);
1720    VerifyMessage(message, signature, KM_DIGEST_NONE);
1721
1722    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
1723        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1724}
1725
1726TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
1727    string pk8_key = read_file("ec_privkey_pk8.der");
1728    ASSERT_EQ(138U, pk8_key.size());
1729    ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
1730              ImportKey(AuthorizationSetBuilder()
1731                            .EcdsaSigningKey(224 /* Doesn't match key */)
1732                            .Digest(KM_DIGEST_NONE),
1733                        KM_KEY_FORMAT_PKCS8, pk8_key));
1734
1735    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1736}
1737
1738TEST_P(ImportKeyTest, AesKeySuccess) {
1739    char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1740    string key(key_data, sizeof(key_data));
1741    ASSERT_EQ(KM_ERROR_OK,
1742              ImportKey(AuthorizationSetBuilder().AesEncryptionKey(128).EcbMode().Authorization(
1743                            TAG_PADDING, KM_PAD_PKCS7),
1744                        KM_KEY_FORMAT_RAW, key));
1745
1746    EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1747    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1748
1749    string message = "Hello World!";
1750    string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
1751    string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
1752    EXPECT_EQ(message, plaintext);
1753
1754    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1755}
1756
1757TEST_P(ImportKeyTest, HmacSha256KeySuccess) {
1758    char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1759    string key(key_data, sizeof(key_data));
1760    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
1761                                         .HmacKey(sizeof(key_data) * 8)
1762                                         .Digest(KM_DIGEST_SHA_2_256)
1763                                         .Authorization(TAG_MAC_LENGTH, 32),
1764                                     KM_KEY_FORMAT_RAW, key));
1765
1766    EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1767    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1768
1769    string message = "Hello World!";
1770    string signature;
1771    MacMessage(message, &signature, KM_DIGEST_SHA_2_256, 32);
1772    VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
1773
1774    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1775}
1776
1777typedef Keymaster1Test EncryptionOperationsTest;
1778INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, EncryptionOperationsTest, test_params);
1779
1780TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
1781    ASSERT_EQ(KM_ERROR_OK,
1782              GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
1783
1784    string message = "12345678901234567890123456789012";
1785    string ciphertext1 = EncryptMessage(string(message), KM_PAD_NONE);
1786    EXPECT_EQ(256U / 8, ciphertext1.size());
1787
1788    string ciphertext2 = EncryptMessage(string(message), KM_PAD_NONE);
1789    EXPECT_EQ(256U / 8, ciphertext2.size());
1790
1791    // Unpadded RSA is deterministic
1792    EXPECT_EQ(ciphertext1, ciphertext2);
1793
1794    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1795        EXPECT_EQ(3, GetParam()->keymaster0_calls());
1796}
1797
1798TEST_P(EncryptionOperationsTest, RsaNoPaddingTooShort) {
1799    ASSERT_EQ(KM_ERROR_OK,
1800              GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
1801
1802    string message = "1234567890123456789012345678901";
1803
1804    AuthorizationSet begin_params(client_params());
1805    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
1806    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
1807
1808    string result;
1809    size_t input_consumed;
1810    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1811    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
1812    EXPECT_EQ(0U, result.size());
1813
1814    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1815        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1816}
1817
1818TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
1819    ASSERT_EQ(KM_ERROR_OK,
1820              GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
1821
1822    string message = "123456789012345678901234567890123";
1823
1824    AuthorizationSet begin_params(client_params());
1825    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
1826    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
1827
1828    string result;
1829    size_t input_consumed;
1830    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
1831
1832    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1833        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1834}
1835
1836TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
1837    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1838                                           .RsaEncryptionKey(512, 3)
1839                                           .Padding(KM_PAD_RSA_OAEP)
1840                                           .Digest(KM_DIGEST_SHA_2_256)));
1841
1842    string message = "Hello World!";
1843    string ciphertext1 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
1844    EXPECT_EQ(512U / 8, ciphertext1.size());
1845
1846    string ciphertext2 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
1847    EXPECT_EQ(512U / 8, ciphertext2.size());
1848
1849    // OAEP randomizes padding so every result should be different.
1850    EXPECT_NE(ciphertext1, ciphertext2);
1851
1852    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1853        EXPECT_EQ(3, GetParam()->keymaster0_calls());
1854}
1855
1856TEST_P(EncryptionOperationsTest, RsaOaepRoundTrip) {
1857    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1858                                           .RsaEncryptionKey(512, 3)
1859                                           .Padding(KM_PAD_RSA_OAEP)
1860                                           .Digest(KM_DIGEST_SHA_2_256)));
1861    string message = "Hello World!";
1862    string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
1863    EXPECT_EQ(512U / 8, ciphertext.size());
1864
1865    string plaintext = DecryptMessage(ciphertext, KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
1866    EXPECT_EQ(message, plaintext);
1867
1868    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1869        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1870}
1871
1872TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
1873    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1874                                           .RsaEncryptionKey(512, 3)
1875                                           .Padding(KM_PAD_RSA_OAEP)
1876                                           .Digest(KM_DIGEST_NONE)));
1877    string message = "Hello World!";
1878
1879    AuthorizationSet begin_params(client_params());
1880    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
1881    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
1882    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
1883
1884    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1885        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1886}
1887
1888TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
1889    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1890                                           .RsaEncryptionKey(512, 3)
1891                                           .Padding(KM_PAD_RSA_OAEP)
1892                                           .Digest(KM_DIGEST_SHA_2_256)));
1893    string message = "12345678901234567890123";
1894    string result;
1895    size_t input_consumed;
1896
1897    AuthorizationSet begin_params(client_params());
1898    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
1899    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1900    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
1901    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1902    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
1903    EXPECT_EQ(0U, result.size());
1904
1905    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1906        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1907}
1908
1909TEST_P(EncryptionOperationsTest, RsaOaepCorruptedDecrypt) {
1910    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1911                                           .RsaEncryptionKey(512, 3)
1912                                           .Padding(KM_PAD_RSA_OAEP)
1913                                           .Digest(KM_DIGEST_SHA_2_256)));
1914    string message = "Hello World!";
1915    string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
1916    EXPECT_EQ(512U / 8, ciphertext.size());
1917
1918    // Corrupt the ciphertext
1919    ciphertext[512 / 8 / 2]++;
1920
1921    string result;
1922    size_t input_consumed;
1923    AuthorizationSet begin_params(client_params());
1924    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
1925    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1926    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
1927    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
1928    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
1929    EXPECT_EQ(0U, result.size());
1930
1931    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1932        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1933}
1934
1935TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
1936    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
1937                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
1938    string message = "Hello World!";
1939    string ciphertext1 = EncryptMessage(string(message), KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
1940    EXPECT_EQ(512U / 8, ciphertext1.size());
1941
1942    string ciphertext2 = EncryptMessage(string(message), KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
1943    EXPECT_EQ(512U / 8, ciphertext2.size());
1944
1945    // PKCS1 v1.5 randomizes padding so every result should be different.
1946    EXPECT_NE(ciphertext1, ciphertext2);
1947
1948    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1949        EXPECT_EQ(3, GetParam()->keymaster0_calls());
1950}
1951
1952TEST_P(EncryptionOperationsTest, RsaPkcs1RoundTrip) {
1953    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
1954                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
1955    string message = "Hello World!";
1956    string ciphertext = EncryptMessage(string(message), KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
1957    EXPECT_EQ(512U / 8, ciphertext.size());
1958
1959    string plaintext = DecryptMessage(ciphertext, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
1960    EXPECT_EQ(message, plaintext);
1961
1962    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1963        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1964}
1965
1966TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
1967    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
1968                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
1969    string message = "123456789012345678901234567890123456789012345678901234";
1970    string result;
1971    size_t input_consumed;
1972
1973    AuthorizationSet begin_params(client_params());
1974    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
1975    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
1976    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1977    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
1978    EXPECT_EQ(0U, result.size());
1979
1980    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1981        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1982}
1983
1984TEST_P(EncryptionOperationsTest, RsaPkcs1InvalidDigest) {
1985    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1986                                           .RsaEncryptionKey(512, 3)
1987                                           .Padding(KM_PAD_RSA_PKCS1_1_5_ENCRYPT)
1988                                           .Digest(KM_DIGEST_NONE)));
1989    string message = "Hello World!";
1990    string result;
1991
1992    AuthorizationSet begin_params(client_params());
1993    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
1994    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);  // Any digest is invalid
1995    EXPECT_EQ(KM_ERROR_UNSUPPORTED_DIGEST, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
1996
1997    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
1998        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1999}
2000
2001TEST_P(EncryptionOperationsTest, RsaPkcs1CorruptedDecrypt) {
2002    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2003                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2004    string message = "Hello World!";
2005    string ciphertext = EncryptMessage(string(message), KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2006    EXPECT_EQ(512U / 8, ciphertext.size());
2007
2008    // Corrupt the ciphertext
2009    ciphertext[512 / 8 / 2]++;
2010
2011    string result;
2012    size_t input_consumed;
2013    AuthorizationSet begin_params(client_params());
2014    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2015    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2016    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
2017    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
2018    EXPECT_EQ(0U, result.size());
2019
2020    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
2021        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2022}
2023
2024TEST_P(EncryptionOperationsTest, RsaEncryptWithSigningKey) {
2025    ASSERT_EQ(KM_ERROR_OK,
2026              GenerateKey(AuthorizationSetBuilder().RsaSigningKey(256, 3).Padding(KM_PAD_NONE)));
2027
2028    AuthorizationSet begin_params(client_params());
2029    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2030    ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2031
2032    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_RSA))
2033        EXPECT_EQ(2, GetParam()->keymaster0_calls());
2034}
2035
2036TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
2037    ASSERT_EQ(KM_ERROR_OK,
2038              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
2039    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
2040    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
2041
2042    if (GetParam()->algorithm_in_hardware(KM_ALGORITHM_EC))
2043        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2044}
2045
2046TEST_P(EncryptionOperationsTest, HmacEncrypt) {
2047    ASSERT_EQ(
2048        KM_ERROR_OK,
2049        GenerateKey(
2050            AuthorizationSetBuilder().HmacKey(128).Digest(KM_DIGEST_NONE).Padding(KM_PAD_NONE)));
2051    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
2052    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
2053
2054    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2055}
2056
2057TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
2058    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2059                                           .AesEncryptionKey(128)
2060                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2061                                           .Padding(KM_PAD_NONE)));
2062    // Two-block message.
2063    string message = "12345678901234567890123456789012";
2064    string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
2065    EXPECT_EQ(message.size(), ciphertext1.size());
2066
2067    string ciphertext2 = EncryptMessage(string(message), KM_MODE_ECB, KM_PAD_NONE);
2068    EXPECT_EQ(message.size(), ciphertext2.size());
2069
2070    // ECB is deterministic.
2071    EXPECT_EQ(ciphertext1, ciphertext2);
2072
2073    string plaintext = DecryptMessage(ciphertext1, KM_MODE_ECB, KM_PAD_NONE);
2074    EXPECT_EQ(message, plaintext);
2075
2076    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2077}
2078
2079TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
2080    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2081                                           .AesEncryptionKey(128)
2082                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2083                                           .Padding(KM_PAD_NONE)));
2084    // Message is slightly shorter than two blocks.
2085    string message = "1234567890123456789012345678901";
2086
2087    AuthorizationSet begin_params(client_params());
2088    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2089    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2090    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2091    string ciphertext;
2092    size_t input_consumed;
2093    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &ciphertext, &input_consumed));
2094    EXPECT_EQ(message.size(), input_consumed);
2095    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&ciphertext));
2096
2097    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2098}
2099
2100TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
2101    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2102                                           .AesEncryptionKey(128)
2103                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2104                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2105
2106    // Try various message lengths; all should work.
2107    for (size_t i = 0; i < 32; ++i) {
2108        string message(i, 'a');
2109        string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
2110        EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2111        string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
2112        EXPECT_EQ(message, plaintext);
2113    }
2114
2115    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2116}
2117
2118TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
2119    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2120                                           .AesEncryptionKey(128)
2121                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2122                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2123
2124    string message = "a";
2125    string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
2126    EXPECT_EQ(16U, ciphertext.size());
2127    EXPECT_NE(ciphertext, message);
2128    ++ciphertext[ciphertext.size() / 2];
2129
2130    AuthorizationSet begin_params(client_params());
2131    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2132    begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
2133    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2134    string plaintext;
2135    size_t input_consumed;
2136    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &plaintext, &input_consumed));
2137    EXPECT_EQ(ciphertext.size(), input_consumed);
2138    EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&plaintext));
2139
2140    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2141}
2142
2143TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
2144    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2145                                           .AesEncryptionKey(128)
2146                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2147                                           .Padding(KM_PAD_NONE)));
2148    string message = "123";
2149    string iv1;
2150    string ciphertext1 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv1);
2151    EXPECT_EQ(message.size(), ciphertext1.size());
2152    EXPECT_EQ(16U, iv1.size());
2153
2154    string iv2;
2155    string ciphertext2 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv2);
2156    EXPECT_EQ(message.size(), ciphertext2.size());
2157    EXPECT_EQ(16U, iv2.size());
2158
2159    // IVs should be random, so ciphertexts should differ.
2160    EXPECT_NE(iv1, iv2);
2161    EXPECT_NE(ciphertext1, ciphertext2);
2162
2163    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CTR, KM_PAD_NONE, iv1);
2164    EXPECT_EQ(message, plaintext);
2165
2166    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2167}
2168
2169TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
2170    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2171                                           .AesEncryptionKey(128)
2172                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2173                                           .Padding(KM_PAD_NONE)));
2174
2175    int increment = 15;
2176    string message(239, 'a');
2177    AuthorizationSet input_params(client_params());
2178    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2179    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2180    AuthorizationSet output_params;
2181    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2182
2183    string ciphertext;
2184    size_t input_consumed;
2185    for (size_t i = 0; i < message.size(); i += increment)
2186        EXPECT_EQ(KM_ERROR_OK,
2187                  UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
2188    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2189    EXPECT_EQ(message.size(), ciphertext.size());
2190
2191    // Move TAG_NONCE into input_params
2192    input_params.Reinitialize(output_params);
2193    input_params.push_back(client_params());
2194    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2195    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2196    output_params.Clear();
2197
2198    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
2199    string plaintext;
2200    for (size_t i = 0; i < ciphertext.size(); i += increment)
2201        EXPECT_EQ(KM_ERROR_OK,
2202                  UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
2203    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2204    EXPECT_EQ(ciphertext.size(), plaintext.size());
2205    EXPECT_EQ(message, plaintext);
2206
2207    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2208}
2209
2210struct AesCtrSp80038aTestVector {
2211    const char* key;
2212    const char* nonce;
2213    const char* plaintext;
2214    const char* ciphertext;
2215};
2216
2217// These test vectors are taken from
2218// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
2219static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
2220    // AES-128
2221    {
2222        "2b7e151628aed2a6abf7158809cf4f3c", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2223        "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2224        "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2225        "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
2226        "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
2227    },
2228    // AES-192
2229    {
2230        "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2231        "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2232        "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2233        "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
2234        "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
2235    },
2236    // AES-256
2237    {
2238        "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
2239        "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2240        "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2241        "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2242        "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
2243        "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
2244    },
2245};
2246
2247TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
2248    for (size_t i = 0; i < 3; i++) {
2249        const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
2250        const string key = hex2str(test.key);
2251        const string nonce = hex2str(test.nonce);
2252        const string plaintext = hex2str(test.plaintext);
2253        const string ciphertext = hex2str(test.ciphertext);
2254        CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
2255    }
2256
2257    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2258}
2259
2260TEST_P(EncryptionOperationsTest, AesCtrInvalidPaddingMode) {
2261    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2262                                           .AesEncryptionKey(128)
2263                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2264                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2265    AuthorizationSet begin_params(client_params());
2266    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2267    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2268    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2269
2270    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2271}
2272
2273TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
2274    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2275                                           .AesEncryptionKey(128)
2276                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2277                                           .Authorization(TAG_CALLER_NONCE)
2278                                           .Padding(KM_PAD_NONE)));
2279
2280    AuthorizationSet input_params(client_params());
2281    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2282    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2283    input_params.push_back(TAG_NONCE, "123", 3);
2284    EXPECT_EQ(KM_ERROR_INVALID_NONCE, BeginOperation(KM_PURPOSE_ENCRYPT, input_params));
2285
2286    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2287}
2288
2289TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
2290    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2291                                           .AesEncryptionKey(128)
2292                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2293                                           .Padding(KM_PAD_NONE)));
2294    // Two-block message.
2295    string message = "12345678901234567890123456789012";
2296    string iv1;
2297    string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2298    EXPECT_EQ(message.size(), ciphertext1.size());
2299
2300    string iv2;
2301    string ciphertext2 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv2);
2302    EXPECT_EQ(message.size(), ciphertext2.size());
2303
2304    // IVs should be random, so ciphertexts should differ.
2305    EXPECT_NE(iv1, iv2);
2306    EXPECT_NE(ciphertext1, ciphertext2);
2307
2308    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2309    EXPECT_EQ(message, plaintext);
2310
2311    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2312}
2313
2314TEST_P(EncryptionOperationsTest, AesCallerNonce) {
2315    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2316                                           .AesEncryptionKey(128)
2317                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2318                                           .Authorization(TAG_CALLER_NONCE)
2319                                           .Padding(KM_PAD_NONE)));
2320    string message = "12345678901234567890123456789012";
2321    string iv1;
2322    // Don't specify nonce, should get a random one.
2323    string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2324    EXPECT_EQ(message.size(), ciphertext1.size());
2325    EXPECT_EQ(16U, iv1.size());
2326
2327    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2328    EXPECT_EQ(message, plaintext);
2329
2330    // Now specify a nonce, should also work.
2331    AuthorizationSet input_params(client_params());
2332    AuthorizationSet update_params;
2333    AuthorizationSet output_params;
2334    input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
2335    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2336    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2337    string ciphertext2 =
2338        ProcessMessage(KM_PURPOSE_ENCRYPT, message, input_params, update_params, &output_params);
2339
2340    // Decrypt with correct nonce.
2341    plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
2342                               &output_params);
2343    EXPECT_EQ(message, plaintext);
2344
2345    // Now try with wrong nonce.
2346    input_params.Reinitialize(client_params());
2347    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2348    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2349    input_params.push_back(TAG_NONCE, "aaaaaaaaaaaaaaaa", 16);
2350    plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
2351                               &output_params);
2352    EXPECT_NE(message, plaintext);
2353
2354    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2355}
2356
2357TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
2358    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2359                                           .AesEncryptionKey(128)
2360                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2361                                           .Padding(KM_PAD_NONE)));
2362
2363    string message = "12345678901234567890123456789012";
2364    string iv1;
2365    // Don't specify nonce, should get a random one.
2366    string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2367    EXPECT_EQ(message.size(), ciphertext1.size());
2368    EXPECT_EQ(16U, iv1.size());
2369
2370    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2371    EXPECT_EQ(message, plaintext);
2372
2373    // Now specify a nonce, should fail.
2374    AuthorizationSet input_params(client_params());
2375    AuthorizationSet update_params;
2376    AuthorizationSet output_params;
2377    input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
2378    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2379    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2380
2381    EXPECT_EQ(KM_ERROR_CALLER_NONCE_PROHIBITED,
2382              BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2383
2384    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2385}
2386
2387TEST_P(EncryptionOperationsTest, AesCbcIncrementalNoPadding) {
2388    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2389                                           .AesEncryptionKey(128)
2390                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2391                                           .Padding(KM_PAD_NONE)));
2392
2393    int increment = 15;
2394    string message(240, 'a');
2395    AuthorizationSet input_params(client_params());
2396    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2397    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2398    AuthorizationSet output_params;
2399    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2400
2401    string ciphertext;
2402    size_t input_consumed;
2403    for (size_t i = 0; i < message.size(); i += increment)
2404        EXPECT_EQ(KM_ERROR_OK,
2405                  UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
2406    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2407    EXPECT_EQ(message.size(), ciphertext.size());
2408
2409    // Move TAG_NONCE into input_params
2410    input_params.Reinitialize(output_params);
2411    input_params.push_back(client_params());
2412    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2413    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2414    output_params.Clear();
2415
2416    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
2417    string plaintext;
2418    for (size_t i = 0; i < ciphertext.size(); i += increment)
2419        EXPECT_EQ(KM_ERROR_OK,
2420                  UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
2421    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2422    EXPECT_EQ(ciphertext.size(), plaintext.size());
2423    EXPECT_EQ(message, plaintext);
2424
2425    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2426}
2427
2428TEST_P(EncryptionOperationsTest, AesCbcPkcs7Padding) {
2429    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2430                                           .AesEncryptionKey(128)
2431                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2432                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2433
2434    // Try various message lengths; all should work.
2435    for (size_t i = 0; i < 32; ++i) {
2436        string message(i, 'a');
2437        string iv;
2438        string ciphertext = EncryptMessage(message, KM_MODE_CBC, KM_PAD_PKCS7, &iv);
2439        EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2440        string plaintext = DecryptMessage(ciphertext, KM_MODE_CBC, KM_PAD_PKCS7, iv);
2441        EXPECT_EQ(message, plaintext);
2442    }
2443
2444    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2445}
2446
2447TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
2448    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2449                                           .AesEncryptionKey(128)
2450                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2451                                           .Authorization(TAG_PADDING, KM_PAD_NONE)));
2452    string aad = "foobar";
2453    string message = "123456789012345678901234567890123456";
2454    AuthorizationSet begin_params(client_params());
2455    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2456    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2457    begin_params.push_back(TAG_MAC_LENGTH, 128);
2458
2459    AuthorizationSet update_params;
2460    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2461
2462    // Encrypt
2463    AuthorizationSet begin_out_params;
2464    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2465    string ciphertext;
2466    size_t input_consumed;
2467    AuthorizationSet update_out_params;
2468    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
2469                                           &input_consumed));
2470    EXPECT_EQ(message.size(), input_consumed);
2471    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2472
2473    // Grab nonce
2474    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
2475    begin_params.push_back(begin_out_params);
2476
2477    // Decrypt.
2478    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2479    string plaintext;
2480    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
2481                                           &plaintext, &input_consumed));
2482    EXPECT_EQ(ciphertext.size(), input_consumed);
2483    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2484
2485    EXPECT_EQ(message, plaintext);
2486    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2487}
2488
2489TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
2490    uint8_t nonce[] = {
2491        0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
2492    };
2493    uint8_t ciphertext[] = {
2494        0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc, 0xd2, 0xcb, 0x16,
2495        0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78, 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a,
2496        0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d, 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76,
2497        0x76, 0x5e, 0xfb, 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
2498        0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
2499    };
2500    string ciphertext_str(reinterpret_cast<char*>(ciphertext), sizeof(ciphertext));
2501
2502    AuthorizationSet begin_params(client_params());
2503    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2504    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2505    begin_params.push_back(TAG_MAC_LENGTH, 128);
2506    begin_params.push_back(TAG_NONCE, nonce, sizeof(nonce));
2507
2508    string plaintext;
2509    size_t input_consumed;
2510
2511    // Import correct key and decrypt
2512    uint8_t good_key[] = {
2513        0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
2514        0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
2515    };
2516    string good_key_str(reinterpret_cast<char*>(good_key), sizeof(good_key));
2517    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
2518                                         .AesEncryptionKey(128)
2519                                         .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2520                                         .Authorization(TAG_PADDING, KM_PAD_NONE)
2521                                         .Authorization(TAG_CALLER_NONCE),
2522                                     KM_KEY_FORMAT_RAW, good_key_str));
2523    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2524    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
2525    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2526
2527    // Import bad key and decrypt
2528    uint8_t bad_key[] = {
2529        0xbb, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
2530        0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
2531    };
2532    string bad_key_str(reinterpret_cast<char*>(bad_key), sizeof(bad_key));
2533    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
2534                                         .AesEncryptionKey(128)
2535                                         .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2536                                         .Authorization(TAG_PADDING, KM_PAD_NONE),
2537                                     KM_KEY_FORMAT_RAW, bad_key_str));
2538    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2539    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
2540    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
2541
2542    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2543}
2544
2545TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
2546    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2547                                           .AesEncryptionKey(128)
2548                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2549                                           .Authorization(TAG_PADDING, KM_PAD_NONE)));
2550    string aad = "123456789012345678";
2551    string empty_message;
2552    AuthorizationSet begin_params(client_params());
2553    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2554    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2555    begin_params.push_back(TAG_MAC_LENGTH, 128);
2556
2557    AuthorizationSet update_params;
2558    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2559
2560    // Encrypt
2561    AuthorizationSet begin_out_params;
2562    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2563    string ciphertext;
2564    size_t input_consumed;
2565    AuthorizationSet update_out_params;
2566    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, empty_message, &update_out_params,
2567                                           &ciphertext, &input_consumed));
2568    EXPECT_EQ(0U, input_consumed);
2569    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2570
2571    // Grab nonce
2572    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
2573    begin_params.push_back(begin_out_params);
2574
2575    // Decrypt.
2576    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2577    string plaintext;
2578    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
2579                                           &plaintext, &input_consumed));
2580    EXPECT_EQ(ciphertext.size(), input_consumed);
2581    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2582
2583    EXPECT_EQ(empty_message, plaintext);
2584    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2585}
2586
2587TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
2588    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2589                                           .AesEncryptionKey(128)
2590                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2591                                           .Authorization(TAG_PADDING, KM_PAD_NONE)));
2592    AuthorizationSet begin_params(client_params());
2593    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2594    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2595    begin_params.push_back(TAG_MAC_LENGTH, 128);
2596
2597    AuthorizationSet update_params;
2598    update_params.push_back(TAG_ASSOCIATED_DATA, "b", 1);
2599
2600    // Encrypt
2601    AuthorizationSet begin_out_params;
2602    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2603    string ciphertext;
2604    size_t input_consumed;
2605    AuthorizationSet update_out_params;
2606
2607    // Send AAD, incrementally
2608    for (int i = 0; i < 1000; ++i) {
2609        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &ciphertext,
2610                                               &input_consumed));
2611        EXPECT_EQ(0U, input_consumed);
2612        EXPECT_EQ(0U, ciphertext.size());
2613    }
2614
2615    // Now send data, incrementally, no data.
2616    AuthorizationSet empty_params;
2617    for (int i = 0; i < 1000; ++i) {
2618        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, "a", &update_out_params, &ciphertext,
2619                                               &input_consumed));
2620        EXPECT_EQ(1U, input_consumed);
2621    }
2622    EXPECT_EQ(1000U, ciphertext.size());
2623
2624    // And finish.
2625    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2626    EXPECT_EQ(1016U, ciphertext.size());
2627
2628    // Grab nonce
2629    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
2630    begin_params.push_back(begin_out_params);
2631
2632    // Decrypt.
2633    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2634    string plaintext;
2635
2636    // Send AAD, incrementally, no data
2637    for (int i = 0; i < 1000; ++i) {
2638        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &plaintext,
2639                                               &input_consumed));
2640        EXPECT_EQ(0U, input_consumed);
2641        EXPECT_EQ(0U, plaintext.size());
2642    }
2643
2644    // Now send data, incrementally.
2645    for (size_t i = 0; i < ciphertext.length(); ++i) {
2646        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, string(ciphertext.data() + i, 1),
2647                                               &update_out_params, &plaintext, &input_consumed));
2648        EXPECT_EQ(1U, input_consumed);
2649    }
2650    EXPECT_EQ(1000U, plaintext.size());
2651    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2652
2653    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2654}
2655
2656TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
2657    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2658                                           .AesEncryptionKey(128)
2659                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2660                                           .Authorization(TAG_PADDING, KM_PAD_NONE)));
2661    string message = "123456789012345678901234567890123456";
2662    AuthorizationSet begin_params(client_params());
2663    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2664    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2665    begin_params.push_back(TAG_MAC_LENGTH, 128);
2666    AuthorizationSet begin_out_params;
2667
2668    AuthorizationSet update_params;
2669    update_params.push_back(TAG_ASSOCIATED_DATA, "foo", 3);
2670
2671    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2672
2673    // No data, AAD only.
2674    string ciphertext;
2675    size_t input_consumed;
2676    AuthorizationSet update_out_params;
2677    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "" /* message */, &update_out_params,
2678                                           &ciphertext, &input_consumed));
2679    EXPECT_EQ(0U, input_consumed);
2680
2681    // AAD and data.
2682    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
2683                                           &input_consumed));
2684    EXPECT_EQ(message.size(), input_consumed);
2685    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2686
2687    // Grab nonce.
2688    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
2689    begin_params.push_back(begin_out_params);
2690
2691    // Decrypt
2692    update_params.Clear();
2693    update_params.push_back(TAG_ASSOCIATED_DATA, "foofoo", 6);
2694
2695    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2696    string plaintext;
2697    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
2698                                           &plaintext, &input_consumed));
2699    EXPECT_EQ(ciphertext.size(), input_consumed);
2700    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2701
2702    EXPECT_EQ(message, plaintext);
2703    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2704}
2705
2706TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
2707    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2708                                           .AesEncryptionKey(128)
2709                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2710                                           .Authorization(TAG_PADDING, KM_PAD_NONE)));
2711    string message = "12345678901234567890123456789012";
2712    AuthorizationSet begin_params(client_params());
2713    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2714    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2715    begin_params.push_back(TAG_MAC_LENGTH, 128);
2716
2717    AuthorizationSet update_params;
2718    update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
2719
2720    AuthorizationSet finish_params;
2721    AuthorizationSet finish_out_params;
2722
2723    // Encrypt
2724    AuthorizationSet begin_out_params;
2725    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2726    AuthorizationSet update_out_params;
2727    string ciphertext;
2728    size_t input_consumed;
2729    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
2730                                           &input_consumed));
2731    EXPECT_EQ(message.size(), input_consumed);
2732    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2733
2734    // Grab nonce
2735    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
2736    begin_params.push_back(begin_out_params);
2737
2738    update_params.Clear();
2739    update_params.push_back(TAG_ASSOCIATED_DATA, "barfoo" /* Wrong AAD */, 6);
2740
2741    // Decrypt.
2742    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
2743    string plaintext;
2744    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
2745                                           &plaintext, &input_consumed));
2746    EXPECT_EQ(ciphertext.size(), input_consumed);
2747    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
2748
2749    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2750}
2751
2752TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
2753    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2754                                           .AesEncryptionKey(128)
2755                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2756                                           .Authorization(TAG_PADDING, KM_PAD_NONE)));
2757    string message = "12345678901234567890123456789012";
2758    AuthorizationSet begin_params(client_params());
2759    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2760    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2761    begin_params.push_back(TAG_MAC_LENGTH, 128);
2762
2763    AuthorizationSet update_params;
2764    update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
2765
2766    // Encrypt
2767    AuthorizationSet begin_out_params;
2768    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2769    AuthorizationSet update_out_params;
2770    string ciphertext;
2771    size_t input_consumed;
2772    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
2773                                           &input_consumed));
2774    EXPECT_EQ(message.size(), input_consumed);
2775    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2776
2777    begin_params.push_back(TAG_NONCE, "123456789012", 12);
2778
2779    // Decrypt
2780    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
2781    string plaintext;
2782    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
2783                                           &plaintext, &input_consumed));
2784    EXPECT_EQ(ciphertext.size(), input_consumed);
2785    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
2786
2787    // With wrong nonce, should have gotten garbage plaintext.
2788    EXPECT_NE(message, plaintext);
2789    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2790}
2791
2792TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
2793    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2794                                           .AesEncryptionKey(128)
2795                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2796                                           .Authorization(TAG_PADDING, KM_PAD_NONE)));
2797    string aad = "foobar";
2798    string message = "123456789012345678901234567890123456";
2799    AuthorizationSet begin_params(client_params());
2800    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2801    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2802    begin_params.push_back(TAG_MAC_LENGTH, 128);
2803    AuthorizationSet begin_out_params;
2804
2805    AuthorizationSet update_params;
2806    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2807
2808    // Encrypt
2809    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2810    AuthorizationSet update_out_params;
2811    string ciphertext;
2812    size_t input_consumed;
2813    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
2814                                           &input_consumed));
2815    EXPECT_EQ(message.size(), input_consumed);
2816    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2817
2818    // Corrupt tag
2819    (*ciphertext.rbegin())++;
2820
2821    // Grab nonce.
2822    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
2823    begin_params.push_back(begin_out_params);
2824
2825    // Decrypt.
2826    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
2827    string plaintext;
2828    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
2829                                           &plaintext, &input_consumed));
2830    EXPECT_EQ(ciphertext.size(), input_consumed);
2831    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
2832
2833    EXPECT_EQ(message, plaintext);
2834    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2835}
2836
2837typedef Keymaster1Test MaxOperationsTest;
2838INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, MaxOperationsTest, test_params);
2839
2840TEST_P(MaxOperationsTest, TestLimit) {
2841    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2842                                           .AesEncryptionKey(128)
2843                                           .EcbMode()
2844                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
2845                                           .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
2846
2847    string message = "1234567890123456";
2848    string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
2849    string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
2850    string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
2851
2852    // Fourth time should fail.
2853    AuthorizationSet begin_params(client_params());
2854    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2855    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2856    EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2857
2858    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2859}
2860
2861TEST_P(MaxOperationsTest, TestAbort) {
2862    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2863                                           .AesEncryptionKey(128)
2864                                           .EcbMode()
2865                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
2866                                           .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
2867
2868    string message = "1234567890123456";
2869    string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
2870    string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
2871    string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
2872
2873    // Fourth time should fail.
2874    AuthorizationSet begin_params(client_params());
2875    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2876    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2877    EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2878
2879    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2880}
2881
2882typedef Keymaster1Test AddEntropyTest;
2883INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, AddEntropyTest, test_params);
2884
2885TEST_P(AddEntropyTest, AddEntropy) {
2886    // There's no obvious way to test that entropy is actually added, but we can test that the API
2887    // doesn't blow up or return an error.
2888    EXPECT_EQ(KM_ERROR_OK,
2889              device()->add_rng_entropy(device(), reinterpret_cast<const uint8_t*>("foo"), 3));
2890
2891    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2892}
2893
2894typedef Keymaster1Test Keymaster0AdapterTest;
2895INSTANTIATE_TEST_CASE_P(
2896    AndroidKeymasterTest, Keymaster0AdapterTest,
2897    ::testing::Values(
2898        InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(true /* support_ec */)),
2899        InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(false /* support_ec */))));
2900
2901TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster1RsaBlob) {
2902    // Load and use an old-style Keymaster1 software key blob.  These blobs contain OCB-encrypted
2903    // key data.
2904    string km1_sw = read_file("km1_sw_rsa_512.blob");
2905    EXPECT_EQ(486U, km1_sw.length());
2906
2907    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
2908    memcpy(key_data, km1_sw.data(), km1_sw.length());
2909    set_key_blob(key_data, km1_sw.length());
2910
2911    string message(64, 'a');
2912    string signature;
2913    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
2914
2915    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2916}
2917
2918TEST_P(Keymaster0AdapterTest, UnversionedSoftwareKeymaster1RsaBlob) {
2919    // Load and use an old-style Keymaster1 software key blob, without the version byte.  These
2920    // blobs contain OCB-encrypted key data.
2921    string km1_sw = read_file("km1_sw_rsa_512_unversioned.blob");
2922    EXPECT_EQ(477U, km1_sw.length());
2923
2924    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
2925    memcpy(key_data, km1_sw.data(), km1_sw.length());
2926    set_key_blob(key_data, km1_sw.length());
2927
2928    string message(64, 'a');
2929    string signature;
2930    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
2931
2932    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2933}
2934
2935TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster1EcdsaBlob) {
2936    // Load and use an old-style Keymaster1 software key blob.  These blobs contain OCB-encrypted
2937    // key data.
2938    string km1_sw = read_file("km1_sw_ecdsa_256.blob");
2939    EXPECT_EQ(270U, km1_sw.length());
2940
2941    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
2942    memcpy(key_data, km1_sw.data(), km1_sw.length());
2943    set_key_blob(key_data, km1_sw.length());
2944
2945    string message(32, static_cast<char>(0xFF));
2946    string signature;
2947    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
2948
2949    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2950}
2951
2952struct Malloc_Delete {
2953    void operator()(void* p) { free(p); }
2954};
2955
2956TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster0RsaBlob) {
2957    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
2958    string km0_sw = read_file("km0_sw_rsa_512.blob");
2959    EXPECT_EQ(333U, km0_sw.length());
2960
2961    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
2962    memcpy(key_data, km0_sw.data(), km0_sw.length());
2963    set_key_blob(key_data, km0_sw.length());
2964
2965    string message(64, 'a');
2966    string signature;
2967    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
2968
2969    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2970}
2971
2972TEST_P(Keymaster0AdapterTest, OldSwKeymaster0RsaBlobGetCharacteristics) {
2973    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
2974    string km0_sw = read_file("km0_sw_rsa_512.blob");
2975    EXPECT_EQ(333U, km0_sw.length());
2976
2977    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
2978    memcpy(key_data, km0_sw.data(), km0_sw.length());
2979    set_key_blob(key_data, km0_sw.length());
2980
2981    EXPECT_EQ(KM_ERROR_OK, GetCharacteristics());
2982    EXPECT_TRUE(contains(sw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
2983    EXPECT_TRUE(contains(sw_enforced(), TAG_KEY_SIZE, 512));
2984    EXPECT_TRUE(contains(sw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
2985    EXPECT_TRUE(contains(sw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
2986    EXPECT_TRUE(contains(sw_enforced(), TAG_PADDING, KM_PAD_NONE));
2987    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_SIGN));
2988    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_VERIFY));
2989    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_ALL_USERS));
2990    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_NO_AUTH_REQUIRED));
2991
2992    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2993}
2994
2995TEST_P(Keymaster0AdapterTest, OldHwKeymaster0RsaBlob) {
2996    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
2997    string km0_sw = read_file("km0_sw_rsa_512.blob");
2998    EXPECT_EQ(333U, km0_sw.length());
2999
3000    // The keymaster0 wrapper swaps the old softkeymaster leading 'P' for a 'Q' to make the key not
3001    // be recognized as a software key.  Do the same here to pretend this is a hardware key.
3002    EXPECT_EQ('P', km0_sw[0]);
3003    km0_sw[0] = 'Q';
3004
3005    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
3006    memcpy(key_data, km0_sw.data(), km0_sw.length());
3007    set_key_blob(key_data, km0_sw.length());
3008
3009    string message(64, 'a');
3010    string signature;
3011    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
3012    VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
3013
3014    EXPECT_EQ(5, GetParam()->keymaster0_calls());
3015}
3016
3017TEST_P(Keymaster0AdapterTest, OldHwKeymaster0RsaBlobGetCharacteristics) {
3018    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
3019    string km0_sw = read_file("km0_sw_rsa_512.blob");
3020    EXPECT_EQ(333U, km0_sw.length());
3021
3022    // The keymaster0 wrapper swaps the old softkeymaster leading 'P' for a 'Q' to make the key not
3023    // be recognized as a software key.  Do the same here to pretend this is a hardware key.
3024    EXPECT_EQ('P', km0_sw[0]);
3025    km0_sw[0] = 'Q';
3026
3027    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
3028    memcpy(key_data, km0_sw.data(), km0_sw.length());
3029    set_key_blob(key_data, km0_sw.length());
3030
3031    EXPECT_EQ(KM_ERROR_OK, GetCharacteristics());
3032    EXPECT_TRUE(contains(hw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
3033    EXPECT_TRUE(contains(hw_enforced(), TAG_KEY_SIZE, 512));
3034    EXPECT_TRUE(contains(hw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
3035    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
3036    EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_NONE));
3037    EXPECT_EQ(5U, hw_enforced().size());
3038
3039    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_SIGN));
3040    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_VERIFY));
3041    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_ALL_USERS));
3042    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_NO_AUTH_REQUIRED));
3043
3044    EXPECT_FALSE(contains(sw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
3045    EXPECT_FALSE(contains(sw_enforced(), TAG_KEY_SIZE, 512));
3046    EXPECT_FALSE(contains(sw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
3047    EXPECT_FALSE(contains(sw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
3048    EXPECT_FALSE(contains(sw_enforced(), TAG_PADDING, KM_PAD_NONE));
3049
3050    EXPECT_EQ(1, GetParam()->keymaster0_calls());
3051}
3052
3053}  // namespace test
3054}  // namespace keymaster
3055