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