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