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