Refactor VTS tests a bit, to enable adding tests in separate files.

Bug: 70409878
Test: VtsHalKeymasterV4_0TargetTest
Change-Id: Idd147d20761e7123005b468841a2ddb46cc19576
diff --git a/keymaster/4.0/vts/functional/Android.bp b/keymaster/4.0/vts/functional/Android.bp
index 3c3063c..fc6941f 100644
--- a/keymaster/4.0/vts/functional/Android.bp
+++ b/keymaster/4.0/vts/functional/Android.bp
@@ -18,6 +18,7 @@
     name: "VtsHalKeymasterV4_0TargetTest",
     defaults: ["VtsHalTargetTestDefaults"],
     srcs: [
+        "KeymasterHidlTest.cpp",
         "keymaster_hidl_hal_test.cpp",
     ],
     static_libs: [
diff --git a/keymaster/4.0/vts/functional/KeymasterHidlTest.cpp b/keymaster/4.0/vts/functional/KeymasterHidlTest.cpp
new file mode 100644
index 0000000..13b6b2f
--- /dev/null
+++ b/keymaster/4.0/vts/functional/KeymasterHidlTest.cpp
@@ -0,0 +1,589 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "KeymasterHidlTest.h"
+
+#include <android/hidl/manager/1.0/IServiceManager.h>
+
+#include <keymasterV4_0/key_param_output.h>
+
+namespace android {
+namespace hardware {
+namespace keymaster {
+namespace V4_0 {
+
+::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
+    if (set.size() == 0)
+        os << "(Empty)" << ::std::endl;
+    else {
+        os << "\n";
+        for (size_t i = 0; i < set.size(); ++i) os << set[i] << ::std::endl;
+    }
+    return os;
+}
+
+namespace test {
+
+sp<IKeymasterDevice> KeymasterHidlTest::keymaster_;
+std::vector<sp<IKeymasterDevice>> KeymasterHidlTest::all_keymasters_;
+uint32_t KeymasterHidlTest::os_version_;
+uint32_t KeymasterHidlTest::os_patch_level_;
+SecurityLevel KeymasterHidlTest::securityLevel_;
+hidl_string KeymasterHidlTest::name_;
+hidl_string KeymasterHidlTest::author_;
+
+void KeymasterHidlTest::SetUpTestCase() {
+    string service_name = KeymasterHidlEnvironment::Instance()->getServiceName<IKeymasterDevice>();
+    keymaster_ = ::testing::VtsHalHidlTargetTestBase::getService<IKeymasterDevice>(service_name);
+    ASSERT_NE(keymaster_, nullptr);
+
+    ASSERT_TRUE(keymaster_
+                    ->getHardwareInfo([&](SecurityLevel securityLevel, const hidl_string& name,
+                                          const hidl_string& author) {
+                        securityLevel_ = securityLevel;
+                        name_ = name;
+                        author_ = author;
+                    })
+                    .isOk());
+
+    os_version_ = ::keymaster::GetOsVersion();
+    os_patch_level_ = ::keymaster::GetOsPatchlevel();
+
+    auto service_manager = android::hidl::manager::V1_0::IServiceManager::getService();
+    ASSERT_NE(nullptr, service_manager.get());
+
+    all_keymasters_.push_back(keymaster_);
+    service_manager->listByInterface(
+        IKeymasterDevice::descriptor, [&](const hidl_vec<hidl_string>& names) {
+            for (auto& name : names) {
+                if (name == service_name) continue;
+                auto keymaster =
+                    ::testing::VtsHalHidlTargetTestBase::getService<IKeymasterDevice>(name);
+                ASSERT_NE(keymaster, nullptr);
+                all_keymasters_.push_back(keymaster);
+            }
+        });
+}
+
+ErrorCode KeymasterHidlTest::GenerateKey(const AuthorizationSet& key_desc, HidlBuf* key_blob,
+                                         KeyCharacteristics* key_characteristics) {
+    EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null.  Test bug";
+    EXPECT_EQ(0U, key_blob->size()) << "Key blob not empty before generating key.  Test bug.";
+    EXPECT_NE(key_characteristics, nullptr)
+        << "Previous characteristics not deleted before generating key.  Test bug.";
+
+    ErrorCode error;
+    EXPECT_TRUE(keymaster_
+                    ->generateKey(key_desc.hidl_data(),
+                                  [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
+                                      const KeyCharacteristics& hidl_key_characteristics) {
+                                      error = hidl_error;
+                                      *key_blob = hidl_key_blob;
+                                      *key_characteristics = hidl_key_characteristics;
+                                  })
+                    .isOk());
+    // On error, blob & characteristics should be empty.
+    if (error != ErrorCode::OK) {
+        EXPECT_EQ(0U, key_blob->size());
+        EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() +
+                       key_characteristics->hardwareEnforced.size()));
+    }
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::GenerateKey(const AuthorizationSet& key_desc) {
+    return GenerateKey(key_desc, &key_blob_, &key_characteristics_);
+}
+
+ErrorCode KeymasterHidlTest::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
+                                       const string& key_material, HidlBuf* key_blob,
+                                       KeyCharacteristics* key_characteristics) {
+    ErrorCode error;
+    EXPECT_TRUE(keymaster_
+                    ->importKey(key_desc.hidl_data(), format, HidlBuf(key_material),
+                                [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
+                                    const KeyCharacteristics& hidl_key_characteristics) {
+                                    error = hidl_error;
+                                    *key_blob = hidl_key_blob;
+                                    *key_characteristics = hidl_key_characteristics;
+                                })
+                    .isOk());
+    // On error, blob & characteristics should be empty.
+    if (error != ErrorCode::OK) {
+        EXPECT_EQ(0U, key_blob->size());
+        EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() +
+                       key_characteristics->hardwareEnforced.size()));
+    }
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
+                                       const string& key_material) {
+    return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
+}
+
+ErrorCode KeymasterHidlTest::ImportWrappedKey(string wrapped_key, string wrapping_key,
+                                              const AuthorizationSet& wrapping_key_desc,
+                                              string masking_key) {
+    ErrorCode error;
+    ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key);
+    EXPECT_TRUE(keymaster_
+                    ->importWrappedKey(HidlBuf(wrapped_key), key_blob_, HidlBuf(masking_key),
+                                       [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
+                                           const KeyCharacteristics& hidl_key_characteristics) {
+                                           error = hidl_error;
+                                           key_blob_ = hidl_key_blob;
+                                           key_characteristics_ = hidl_key_characteristics;
+                                       })
+                    .isOk());
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::ExportKey(KeyFormat format, const HidlBuf& key_blob,
+                                       const HidlBuf& client_id, const HidlBuf& app_data,
+                                       HidlBuf* key_material) {
+    ErrorCode error;
+    EXPECT_TRUE(keymaster_
+                    ->exportKey(format, key_blob, client_id, app_data,
+                                [&](ErrorCode hidl_error_code, const HidlBuf& hidl_key_material) {
+                                    error = hidl_error_code;
+                                    *key_material = hidl_key_material;
+                                })
+                    .isOk());
+    // On error, blob should be empty.
+    if (error != ErrorCode::OK) {
+        EXPECT_EQ(0U, key_material->size());
+    }
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::ExportKey(KeyFormat format, HidlBuf* key_material) {
+    HidlBuf client_id, app_data;
+    return ExportKey(format, key_blob_, client_id, app_data, key_material);
+}
+
+ErrorCode KeymasterHidlTest::DeleteKey(HidlBuf* key_blob, bool keep_key_blob) {
+    auto rc = keymaster_->deleteKey(*key_blob);
+    if (!keep_key_blob) *key_blob = HidlBuf();
+    if (!rc.isOk()) return ErrorCode::UNKNOWN_ERROR;
+    return rc;
+}
+
+ErrorCode KeymasterHidlTest::DeleteKey(bool keep_key_blob) {
+    return DeleteKey(&key_blob_, keep_key_blob);
+}
+
+ErrorCode KeymasterHidlTest::DeleteAllKeys() {
+    ErrorCode error = keymaster_->deleteAllKeys();
+    return error;
+}
+
+void KeymasterHidlTest::CheckedDeleteKey(HidlBuf* key_blob, bool keep_key_blob) {
+    auto rc = DeleteKey(key_blob, keep_key_blob);
+    EXPECT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
+}
+
+void KeymasterHidlTest::CheckedDeleteKey() {
+    CheckedDeleteKey(&key_blob_);
+}
+
+ErrorCode KeymasterHidlTest::GetCharacteristics(const HidlBuf& key_blob, const HidlBuf& client_id,
+                                                const HidlBuf& app_data,
+                                                KeyCharacteristics* key_characteristics) {
+    ErrorCode error = ErrorCode::UNKNOWN_ERROR;
+    EXPECT_TRUE(
+        keymaster_
+            ->getKeyCharacteristics(
+                key_blob, client_id, app_data,
+                [&](ErrorCode hidl_error, const KeyCharacteristics& hidl_key_characteristics) {
+                    error = hidl_error, *key_characteristics = hidl_key_characteristics;
+                })
+            .isOk());
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::GetCharacteristics(const HidlBuf& key_blob,
+                                                KeyCharacteristics* key_characteristics) {
+    HidlBuf client_id, app_data;
+    return GetCharacteristics(key_blob, client_id, app_data, key_characteristics);
+}
+
+ErrorCode KeymasterHidlTest::Begin(KeyPurpose purpose, const HidlBuf& key_blob,
+                                   const AuthorizationSet& in_params, AuthorizationSet* out_params,
+                                   OperationHandle* op_handle) {
+    SCOPED_TRACE("Begin");
+    ErrorCode error;
+    OperationHandle saved_handle = *op_handle;
+    EXPECT_TRUE(keymaster_
+                    ->begin(purpose, key_blob, in_params.hidl_data(), HardwareAuthToken(),
+                            [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
+                                uint64_t hidl_op_handle) {
+                                error = hidl_error;
+                                *out_params = hidl_out_params;
+                                *op_handle = hidl_op_handle;
+                            })
+                    .isOk());
+    if (error != ErrorCode::OK) {
+        // Some implementations may modify *op_handle on error.
+        *op_handle = saved_handle;
+    }
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
+                                   AuthorizationSet* out_params) {
+    SCOPED_TRACE("Begin");
+    EXPECT_EQ(kOpHandleSentinel, op_handle_);
+    return Begin(purpose, key_blob_, in_params, out_params, &op_handle_);
+}
+
+ErrorCode KeymasterHidlTest::Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
+    SCOPED_TRACE("Begin");
+    AuthorizationSet out_params;
+    ErrorCode error = Begin(purpose, in_params, &out_params);
+    EXPECT_TRUE(out_params.empty());
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::Update(OperationHandle op_handle, const AuthorizationSet& in_params,
+                                    const string& input, AuthorizationSet* out_params,
+                                    string* output, size_t* input_consumed) {
+    SCOPED_TRACE("Update");
+    ErrorCode error;
+    EXPECT_TRUE(keymaster_
+                    ->update(op_handle, in_params.hidl_data(), HidlBuf(input), HardwareAuthToken(),
+                             VerificationToken(),
+                             [&](ErrorCode hidl_error, uint32_t hidl_input_consumed,
+                                 const hidl_vec<KeyParameter>& hidl_out_params,
+                                 const HidlBuf& hidl_output) {
+                                 error = hidl_error;
+                                 out_params->push_back(AuthorizationSet(hidl_out_params));
+                                 output->append(hidl_output.to_string());
+                                 *input_consumed = hidl_input_consumed;
+                             })
+                    .isOk());
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::Update(const string& input, string* out, size_t* input_consumed) {
+    SCOPED_TRACE("Update");
+    AuthorizationSet out_params;
+    ErrorCode error = Update(op_handle_, AuthorizationSet() /* in_params */, input, &out_params,
+                             out, input_consumed);
+    EXPECT_TRUE(out_params.empty());
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::Finish(OperationHandle op_handle, const AuthorizationSet& in_params,
+                                    const string& input, const string& signature,
+                                    AuthorizationSet* out_params, string* output) {
+    SCOPED_TRACE("Finish");
+    ErrorCode error;
+    EXPECT_TRUE(
+        keymaster_
+            ->finish(op_handle, in_params.hidl_data(), HidlBuf(input), HidlBuf(signature),
+                     HardwareAuthToken(), VerificationToken(),
+                     [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
+                         const HidlBuf& hidl_output) {
+                         error = hidl_error;
+                         *out_params = hidl_out_params;
+                         output->append(hidl_output.to_string());
+                     })
+            .isOk());
+    op_handle_ = kOpHandleSentinel;  // So dtor doesn't Abort().
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::Finish(const string& message, string* output) {
+    SCOPED_TRACE("Finish");
+    AuthorizationSet out_params;
+    string finish_output;
+    ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message,
+                             "" /* signature */, &out_params, output);
+    if (error != ErrorCode::OK) {
+        return error;
+    }
+    EXPECT_EQ(0U, out_params.size());
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::Finish(const string& message, const string& signature,
+                                    string* output) {
+    SCOPED_TRACE("Finish");
+    AuthorizationSet out_params;
+    ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message, signature,
+                             &out_params, output);
+    op_handle_ = kOpHandleSentinel;  // So dtor doesn't Abort().
+    if (error != ErrorCode::OK) {
+        return error;
+    }
+    EXPECT_EQ(0U, out_params.size());
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::Abort(OperationHandle op_handle) {
+    SCOPED_TRACE("Abort");
+    auto retval = keymaster_->abort(op_handle);
+    EXPECT_TRUE(retval.isOk());
+    return retval;
+}
+
+void KeymasterHidlTest::AbortIfNeeded() {
+    SCOPED_TRACE("AbortIfNeeded");
+    if (op_handle_ != kOpHandleSentinel) {
+        EXPECT_EQ(ErrorCode::OK, Abort(op_handle_));
+        op_handle_ = kOpHandleSentinel;
+    }
+}
+
+ErrorCode KeymasterHidlTest::AttestKey(const HidlBuf& key_blob,
+                                       const AuthorizationSet& attest_params,
+                                       hidl_vec<hidl_vec<uint8_t>>* cert_chain) {
+    SCOPED_TRACE("AttestKey");
+    ErrorCode error;
+    auto rc = keymaster_->attestKey(
+        key_blob, attest_params.hidl_data(),
+        [&](ErrorCode hidl_error, const hidl_vec<hidl_vec<uint8_t>>& hidl_cert_chain) {
+            error = hidl_error;
+            *cert_chain = hidl_cert_chain;
+        });
+
+    EXPECT_TRUE(rc.isOk()) << rc.description();
+    if (!rc.isOk()) return ErrorCode::UNKNOWN_ERROR;
+
+    return error;
+}
+
+ErrorCode KeymasterHidlTest::AttestKey(const AuthorizationSet& attest_params,
+                                       hidl_vec<hidl_vec<uint8_t>>* cert_chain) {
+    SCOPED_TRACE("AttestKey");
+    return AttestKey(key_blob_, attest_params, cert_chain);
+}
+
+string KeymasterHidlTest::ProcessMessage(const HidlBuf& key_blob, KeyPurpose operation,
+                                         const string& message, const AuthorizationSet& in_params,
+                                         AuthorizationSet* out_params) {
+    SCOPED_TRACE("ProcessMessage");
+    AuthorizationSet begin_out_params;
+    EXPECT_EQ(ErrorCode::OK, Begin(operation, key_blob, in_params, &begin_out_params, &op_handle_));
+
+    string unused;
+    AuthorizationSet finish_params;
+    AuthorizationSet finish_out_params;
+    string output;
+    EXPECT_EQ(ErrorCode::OK,
+              Finish(op_handle_, finish_params, message, unused, &finish_out_params, &output));
+    op_handle_ = kOpHandleSentinel;
+
+    out_params->push_back(begin_out_params);
+    out_params->push_back(finish_out_params);
+    return output;
+}
+
+string KeymasterHidlTest::SignMessage(const HidlBuf& key_blob, const string& message,
+                                      const AuthorizationSet& params) {
+    SCOPED_TRACE("SignMessage");
+    AuthorizationSet out_params;
+    string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
+    EXPECT_TRUE(out_params.empty());
+    return signature;
+}
+
+string KeymasterHidlTest::SignMessage(const string& message, const AuthorizationSet& params) {
+    SCOPED_TRACE("SignMessage");
+    return SignMessage(key_blob_, message, params);
+}
+
+string KeymasterHidlTest::MacMessage(const string& message, Digest digest, size_t mac_length) {
+    SCOPED_TRACE("MacMessage");
+    return SignMessage(
+        key_blob_, message,
+        AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
+}
+
+void KeymasterHidlTest::CheckHmacTestVector(const string& key, const string& message, Digest digest,
+                                            const string& expected_mac) {
+    SCOPED_TRACE("CheckHmacTestVector");
+    ASSERT_EQ(ErrorCode::OK,
+              ImportKey(AuthorizationSetBuilder()
+                            .Authorization(TAG_NO_AUTH_REQUIRED)
+                            .HmacKey(key.size() * 8)
+                            .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
+                            .Digest(digest),
+                        KeyFormat::RAW, key));
+    string signature = MacMessage(message, digest, expected_mac.size() * 8);
+    EXPECT_EQ(expected_mac, signature)
+        << "Test vector didn't match for key of size " << key.size() << " message of size "
+        << message.size() << " and digest " << digest;
+    CheckedDeleteKey();
+}
+
+void KeymasterHidlTest::CheckAesCtrTestVector(const string& key, const string& nonce,
+                                              const string& message,
+                                              const string& expected_ciphertext) {
+    SCOPED_TRACE("CheckAesCtrTestVector");
+    ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
+                                           .Authorization(TAG_NO_AUTH_REQUIRED)
+                                           .AesEncryptionKey(key.size() * 8)
+                                           .BlockMode(BlockMode::CTR)
+                                           .Authorization(TAG_CALLER_NONCE)
+                                           .Padding(PaddingMode::NONE),
+                                       KeyFormat::RAW, key));
+
+    auto params = AuthorizationSetBuilder()
+                      .Authorization(TAG_NONCE, nonce.data(), nonce.size())
+                      .BlockMode(BlockMode::CTR)
+                      .Padding(PaddingMode::NONE);
+    AuthorizationSet out_params;
+    string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
+    EXPECT_EQ(expected_ciphertext, ciphertext);
+}
+
+void KeymasterHidlTest::CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
+                                                 PaddingMode padding_mode, const string& key,
+                                                 const string& iv, const string& input,
+                                                 const string& expected_output) {
+    auto authset = AuthorizationSetBuilder()
+                       .TripleDesEncryptionKey(key.size() * 7)
+                       .BlockMode(block_mode)
+                       .Padding(padding_mode);
+    if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
+    ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
+    auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
+    if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
+    AuthorizationSet output_params;
+    string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
+    EXPECT_EQ(expected_output, output);
+}
+
+void KeymasterHidlTest::VerifyMessage(const HidlBuf& key_blob, const string& message,
+                                      const string& signature, const AuthorizationSet& params) {
+    SCOPED_TRACE("VerifyMessage");
+    AuthorizationSet begin_out_params;
+    ASSERT_EQ(ErrorCode::OK,
+              Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params, &op_handle_));
+
+    string unused;
+    AuthorizationSet finish_params;
+    AuthorizationSet finish_out_params;
+    string output;
+    EXPECT_EQ(ErrorCode::OK,
+              Finish(op_handle_, finish_params, message, signature, &finish_out_params, &output));
+    op_handle_ = kOpHandleSentinel;
+    EXPECT_TRUE(output.empty());
+}
+
+void KeymasterHidlTest::VerifyMessage(const string& message, const string& signature,
+                                      const AuthorizationSet& params) {
+    SCOPED_TRACE("VerifyMessage");
+    VerifyMessage(key_blob_, message, signature, params);
+}
+
+string KeymasterHidlTest::EncryptMessage(const HidlBuf& key_blob, const string& message,
+                                         const AuthorizationSet& in_params,
+                                         AuthorizationSet* out_params) {
+    SCOPED_TRACE("EncryptMessage");
+    return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
+}
+
+string KeymasterHidlTest::EncryptMessage(const string& message, const AuthorizationSet& params,
+                                         AuthorizationSet* out_params) {
+    SCOPED_TRACE("EncryptMessage");
+    return EncryptMessage(key_blob_, message, params, out_params);
+}
+
+string KeymasterHidlTest::EncryptMessage(const string& message, const AuthorizationSet& params) {
+    SCOPED_TRACE("EncryptMessage");
+    AuthorizationSet out_params;
+    string ciphertext = EncryptMessage(message, params, &out_params);
+    EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
+    return ciphertext;
+}
+
+string KeymasterHidlTest::EncryptMessage(const string& message, BlockMode block_mode,
+                                         PaddingMode padding) {
+    SCOPED_TRACE("EncryptMessage");
+    auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
+    AuthorizationSet out_params;
+    string ciphertext = EncryptMessage(message, params, &out_params);
+    EXPECT_TRUE(out_params.empty()) << "Output params should be empty. Contained: " << out_params;
+    return ciphertext;
+}
+
+string KeymasterHidlTest::EncryptMessage(const string& message, BlockMode block_mode,
+                                         PaddingMode padding, HidlBuf* iv_out) {
+    SCOPED_TRACE("EncryptMessage");
+    auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
+    AuthorizationSet out_params;
+    string ciphertext = EncryptMessage(message, params, &out_params);
+    EXPECT_EQ(1U, out_params.size());
+    auto ivVal = out_params.GetTagValue(TAG_NONCE);
+    EXPECT_TRUE(ivVal.isOk());
+    *iv_out = ivVal.value();
+    return ciphertext;
+}
+
+string KeymasterHidlTest::EncryptMessage(const string& message, BlockMode block_mode,
+                                         PaddingMode padding, const HidlBuf& iv_in) {
+    SCOPED_TRACE("EncryptMessage");
+    auto params = AuthorizationSetBuilder()
+                      .BlockMode(block_mode)
+                      .Padding(padding)
+                      .Authorization(TAG_NONCE, iv_in);
+    AuthorizationSet out_params;
+    string ciphertext = EncryptMessage(message, params, &out_params);
+    return ciphertext;
+}
+
+string KeymasterHidlTest::DecryptMessage(const HidlBuf& key_blob, const string& ciphertext,
+                                         const AuthorizationSet& params) {
+    SCOPED_TRACE("DecryptMessage");
+    AuthorizationSet out_params;
+    string plaintext =
+        ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
+    EXPECT_TRUE(out_params.empty());
+    return plaintext;
+}
+
+string KeymasterHidlTest::DecryptMessage(const string& ciphertext, const AuthorizationSet& params) {
+    SCOPED_TRACE("DecryptMessage");
+    return DecryptMessage(key_blob_, ciphertext, params);
+}
+
+string KeymasterHidlTest::DecryptMessage(const string& ciphertext, BlockMode block_mode,
+                                         PaddingMode padding_mode, const HidlBuf& iv) {
+    SCOPED_TRACE("DecryptMessage");
+    auto params = AuthorizationSetBuilder()
+                      .BlockMode(block_mode)
+                      .Padding(padding_mode)
+                      .Authorization(TAG_NONCE, iv);
+    return DecryptMessage(key_blob_, ciphertext, params);
+}
+
+std::pair<ErrorCode, HidlBuf> KeymasterHidlTest::UpgradeKey(const HidlBuf& key_blob) {
+    std::pair<ErrorCode, HidlBuf> retval;
+    keymaster_->upgradeKey(key_blob, hidl_vec<KeyParameter>(),
+                           [&](ErrorCode error, const hidl_vec<uint8_t>& upgraded_blob) {
+                               retval = std::tie(error, upgraded_blob);
+                           });
+    return retval;
+}
+
+}  // namespace test
+}  // namespace V4_0
+}  // namespace keymaster
+}  // namespace hardware
+}  // namespace android
diff --git a/keymaster/4.0/vts/functional/KeymasterHidlTest.h b/keymaster/4.0/vts/functional/KeymasterHidlTest.h
new file mode 100644
index 0000000..a490341
--- /dev/null
+++ b/keymaster/4.0/vts/functional/KeymasterHidlTest.h
@@ -0,0 +1,229 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HARDWARE_INTERFACES_KEYMASTER_40_VTS_FUNCTIONAL_KEYMASTER_HIDL_TEST_H_
+#define HARDWARE_INTERFACES_KEYMASTER_40_VTS_FUNCTIONAL_KEYMASTER_HIDL_TEST_H_
+
+#include <android/hardware/keymaster/4.0/IKeymasterDevice.h>
+#include <android/hardware/keymaster/4.0/types.h>
+
+#include <VtsHalHidlTargetTestBase.h>
+
+#include <keymaster/keymaster_configuration.h>
+
+#include <keymasterV4_0/authorization_set.h>
+
+namespace android {
+namespace hardware {
+namespace keymaster {
+namespace V4_0 {
+
+::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set);
+
+namespace test {
+
+using ::android::sp;
+using ::std::string;
+
+class HidlBuf : public hidl_vec<uint8_t> {
+    typedef hidl_vec<uint8_t> super;
+
+   public:
+    HidlBuf() {}
+    HidlBuf(const super& other) : super(other) {}
+    HidlBuf(super&& other) : super(std::move(other)) {}
+    explicit HidlBuf(const std::string& other) : HidlBuf() { *this = other; }
+
+    HidlBuf& operator=(const super& other) {
+        super::operator=(other);
+        return *this;
+    }
+
+    HidlBuf& operator=(super&& other) {
+        super::operator=(std::move(other));
+        return *this;
+    }
+
+    HidlBuf& operator=(const string& other) {
+        resize(other.size());
+        std::copy(other.begin(), other.end(), begin());
+        return *this;
+    }
+
+    string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
+};
+
+constexpr uint64_t kOpHandleSentinel = 0xFFFFFFFFFFFFFFFF;
+
+class KeymasterHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
+   public:
+    // get the test environment singleton
+    static KeymasterHidlEnvironment* Instance() {
+        static KeymasterHidlEnvironment* instance = new KeymasterHidlEnvironment;
+        return instance;
+    }
+
+    void registerTestServices() override { registerTestService<IKeymasterDevice>(); }
+
+   private:
+    KeymasterHidlEnvironment(){};
+
+    GTEST_DISALLOW_COPY_AND_ASSIGN_(KeymasterHidlEnvironment);
+};
+
+class KeymasterHidlTest : public ::testing::VtsHalHidlTargetTestBase {
+   public:
+    void TearDown() override {
+        if (key_blob_.size()) {
+            CheckedDeleteKey();
+        }
+        AbortIfNeeded();
+    }
+
+    // SetUpTestCase runs only once per test case, not once per test.
+    static void SetUpTestCase();
+    static void TearDownTestCase() {
+        keymaster_.clear();
+        all_keymasters_.clear();
+    }
+
+    static IKeymasterDevice& keymaster() { return *keymaster_; }
+    static uint32_t os_version() { return os_version_; }
+    static uint32_t os_patch_level() { return os_patch_level_; }
+
+    ErrorCode GenerateKey(const AuthorizationSet& key_desc, HidlBuf* key_blob,
+                          KeyCharacteristics* key_characteristics);
+    ErrorCode GenerateKey(const AuthorizationSet& key_desc);
+
+    ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
+                        const string& key_material, HidlBuf* key_blob,
+                        KeyCharacteristics* key_characteristics);
+    ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
+                        const string& key_material);
+
+    ErrorCode ImportWrappedKey(string wrapped_key, string wrapping_key,
+                               const AuthorizationSet& wrapping_key_desc, string masking_key);
+
+    ErrorCode ExportKey(KeyFormat format, const HidlBuf& key_blob, const HidlBuf& client_id,
+                        const HidlBuf& app_data, HidlBuf* key_material);
+    ErrorCode ExportKey(KeyFormat format, HidlBuf* key_material);
+
+    ErrorCode DeleteKey(HidlBuf* key_blob, bool keep_key_blob = false);
+    ErrorCode DeleteKey(bool keep_key_blob = false);
+
+    ErrorCode DeleteAllKeys();
+
+    void CheckedDeleteKey(HidlBuf* key_blob, bool keep_key_blob = false);
+    void CheckedDeleteKey();
+
+    ErrorCode GetCharacteristics(const HidlBuf& key_blob, const HidlBuf& client_id,
+                                 const HidlBuf& app_data, KeyCharacteristics* key_characteristics);
+    ErrorCode GetCharacteristics(const HidlBuf& key_blob, KeyCharacteristics* key_characteristics);
+
+    ErrorCode Begin(KeyPurpose purpose, const HidlBuf& key_blob, const AuthorizationSet& in_params,
+                    AuthorizationSet* out_params, OperationHandle* op_handle);
+    ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
+                    AuthorizationSet* out_params);
+    ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params);
+
+    ErrorCode Update(OperationHandle op_handle, const AuthorizationSet& in_params,
+                     const string& input, AuthorizationSet* out_params, string* output,
+                     size_t* input_consumed);
+    ErrorCode Update(const string& input, string* out, size_t* input_consumed);
+
+    ErrorCode Finish(OperationHandle op_handle, const AuthorizationSet& in_params,
+                     const string& input, const string& signature, AuthorizationSet* out_params,
+                     string* output);
+    ErrorCode Finish(const string& message, string* output);
+    ErrorCode Finish(const string& message, const string& signature, string* output);
+    ErrorCode Finish(string* output) { return Finish(string(), output); }
+
+    ErrorCode Abort(OperationHandle op_handle);
+
+    void AbortIfNeeded();
+
+    ErrorCode AttestKey(const HidlBuf& key_blob, const AuthorizationSet& attest_params,
+                        hidl_vec<hidl_vec<uint8_t>>* cert_chain);
+    ErrorCode AttestKey(const AuthorizationSet& attest_params,
+                        hidl_vec<hidl_vec<uint8_t>>* cert_chain);
+
+    string ProcessMessage(const HidlBuf& key_blob, KeyPurpose operation, const string& message,
+                          const AuthorizationSet& in_params, AuthorizationSet* out_params);
+
+    string SignMessage(const HidlBuf& key_blob, const string& message,
+                       const AuthorizationSet& params);
+    string SignMessage(const string& message, const AuthorizationSet& params);
+
+    string MacMessage(const string& message, Digest digest, size_t mac_length);
+
+    void CheckHmacTestVector(const string& key, const string& message, Digest digest,
+                             const string& expected_mac);
+
+    void CheckAesCtrTestVector(const string& key, const string& nonce, const string& message,
+                               const string& expected_ciphertext);
+
+    void CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
+                                  PaddingMode padding_mode, const string& key, const string& iv,
+                                  const string& input, const string& expected_output);
+
+    void VerifyMessage(const HidlBuf& key_blob, const string& message, const string& signature,
+                       const AuthorizationSet& params);
+    void VerifyMessage(const string& message, const string& signature,
+                       const AuthorizationSet& params);
+
+    string EncryptMessage(const HidlBuf& key_blob, const string& message,
+                          const AuthorizationSet& in_params, AuthorizationSet* out_params);
+    string EncryptMessage(const string& message, const AuthorizationSet& params,
+                          AuthorizationSet* out_params);
+    string EncryptMessage(const string& message, const AuthorizationSet& params);
+    string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding);
+    string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
+                          HidlBuf* iv_out);
+    string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
+                          const HidlBuf& iv_in);
+
+    string DecryptMessage(const HidlBuf& key_blob, const string& ciphertext,
+                          const AuthorizationSet& params);
+    string DecryptMessage(const string& ciphertext, const AuthorizationSet& params);
+    string DecryptMessage(const string& ciphertext, BlockMode block_mode, PaddingMode padding_mode,
+                          const HidlBuf& iv);
+
+    std::pair<ErrorCode, HidlBuf> UpgradeKey(const HidlBuf& key_blob);
+
+    static bool IsSecure() { return securityLevel_ != SecurityLevel::SOFTWARE; }
+
+    HidlBuf key_blob_;
+    KeyCharacteristics key_characteristics_;
+    OperationHandle op_handle_ = kOpHandleSentinel;
+
+   private:
+    static sp<IKeymasterDevice> keymaster_;
+    static std::vector<sp<IKeymasterDevice>> all_keymasters_;
+    static uint32_t os_version_;
+    static uint32_t os_patch_level_;
+
+    static SecurityLevel securityLevel_;
+    static hidl_string name_;
+    static hidl_string author_;
+};
+
+}  // namespace test
+}  // namespace V4_0
+}  // namespace keymaster
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HARDWARE_INTERFACES_KEYMASTER_40_VTS_FUNCTIONAL_KEYMASTER_HIDL_TEST_H_
diff --git a/keymaster/4.0/vts/functional/keymaster_hidl_hal_test.cpp b/keymaster/4.0/vts/functional/keymaster_hidl_hal_test.cpp
index b0bb68e..cb6ade2 100644
--- a/keymaster/4.0/vts/functional/keymaster_hidl_hal_test.cpp
+++ b/keymaster/4.0/vts/functional/keymaster_hidl_hal_test.cpp
@@ -22,21 +22,13 @@
 #include <openssl/evp.h>
 #include <openssl/x509.h>
 
-#include <android/hardware/keymaster/4.0/IKeymasterDevice.h>
-#include <android/hardware/keymaster/4.0/types.h>
 #include <cutils/properties.h>
-#include <keymaster/keymaster_configuration.h>
-
-#include <VtsHalHidlTargetTestBase.h>
 
 #include <keymasterV4_0/attestation_record.h>
-#include <keymasterV4_0/authorization_set.h>
 #include <keymasterV4_0/key_param_output.h>
 #include <keymasterV4_0/openssl_utils.h>
 
-using ::android::sp;
-
-using ::std::string;
+#include "KeymasterHidlTest.h"
 
 static bool arm_deleteAllKeys = false;
 static bool dump_Attestations = false;
@@ -165,16 +157,6 @@
     return a_sw == b_sw && a_tee == b_tee;
 }
 
-::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
-    if (set.size() == 0)
-        os << "(Empty)" << ::std::endl;
-    else {
-        os << "\n";
-        for (size_t i = 0; i < set.size(); ++i) os << set[i] << ::std::endl;
-    }
-    return os;
-}
-
 namespace test {
 namespace {
 
@@ -370,609 +352,8 @@
     return make_string(a, N);
 }
 
-class HidlBuf : public hidl_vec<uint8_t> {
-    typedef hidl_vec<uint8_t> super;
-
-   public:
-    HidlBuf() {}
-    HidlBuf(const super& other) : super(other) {}
-    HidlBuf(super&& other) : super(std::move(other)) {}
-    explicit HidlBuf(const std::string& other) : HidlBuf() { *this = other; }
-
-    HidlBuf& operator=(const super& other) {
-        super::operator=(other);
-        return *this;
-    }
-
-    HidlBuf& operator=(super&& other) {
-        super::operator=(std::move(other));
-        return *this;
-    }
-
-    HidlBuf& operator=(const string& other) {
-        resize(other.size());
-        for (size_t i = 0; i < other.size(); ++i) {
-            (*this)[i] = static_cast<uint8_t>(other[i]);
-        }
-        return *this;
-    }
-
-    string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
-};
-
-constexpr uint64_t kOpHandleSentinel = 0xFFFFFFFFFFFFFFFF;
-
 }  // namespace
 
-class KeymasterHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
-   public:
-    // get the test environment singleton
-    static KeymasterHidlEnvironment* Instance() {
-        static KeymasterHidlEnvironment* instance = new KeymasterHidlEnvironment;
-        return instance;
-    }
-
-    void registerTestServices() override { registerTestService<IKeymasterDevice>(); }
-
-   private:
-    KeymasterHidlEnvironment(){};
-
-    GTEST_DISALLOW_COPY_AND_ASSIGN_(KeymasterHidlEnvironment);
-};
-
-class KeymasterHidlTest : public ::testing::VtsHalHidlTargetTestBase {
-   public:
-    void TearDown() override {
-        if (key_blob_.size()) {
-            CheckedDeleteKey();
-        }
-        AbortIfNeeded();
-    }
-
-    // SetUpTestCase runs only once per test case, not once per test.
-    static void SetUpTestCase() {
-        string service_name =
-            KeymasterHidlEnvironment::Instance()->getServiceName<IKeymasterDevice>();
-        keymaster_ =
-            ::testing::VtsHalHidlTargetTestBase::getService<IKeymasterDevice>(service_name);
-        ASSERT_NE(keymaster_, nullptr);
-
-        ASSERT_TRUE(keymaster_
-                        ->getHardwareInfo([&](SecurityLevel securityLevel, const hidl_string& name,
-                                              const hidl_string& author) {
-                            securityLevel_ = securityLevel;
-                            name_ = name;
-                            author_ = author;
-                        })
-                        .isOk());
-
-        os_version_ = ::keymaster::GetOsVersion();
-        os_patch_level_ = ::keymaster::GetOsPatchlevel();
-    }
-
-    static void TearDownTestCase() { keymaster_.clear(); }
-
-    static IKeymasterDevice& keymaster() { return *keymaster_; }
-    static uint32_t os_version() { return os_version_; }
-    static uint32_t os_patch_level() { return os_patch_level_; }
-
-    ErrorCode GenerateKey(const AuthorizationSet& key_desc, HidlBuf* key_blob,
-                          KeyCharacteristics* key_characteristics) {
-        EXPECT_NE(key_blob, nullptr) << "Key blob pointer must not be null.  Test bug";
-        EXPECT_EQ(0U, key_blob->size()) << "Key blob not empty before generating key.  Test bug.";
-        EXPECT_NE(key_characteristics, nullptr)
-            << "Previous characteristics not deleted before generating key.  Test bug.";
-
-        ErrorCode error;
-        EXPECT_TRUE(keymaster_
-                        ->generateKey(key_desc.hidl_data(),
-                                      [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
-                                          const KeyCharacteristics& hidl_key_characteristics) {
-                                          error = hidl_error;
-                                          *key_blob = hidl_key_blob;
-                                          *key_characteristics = hidl_key_characteristics;
-                                      })
-                        .isOk());
-        // On error, blob & characteristics should be empty.
-        if (error != ErrorCode::OK) {
-            EXPECT_EQ(0U, key_blob->size());
-            EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() +
-                           key_characteristics->hardwareEnforced.size()));
-        }
-        return error;
-    }
-
-    ErrorCode GenerateKey(const AuthorizationSet& key_desc) {
-        return GenerateKey(key_desc, &key_blob_, &key_characteristics_);
-    }
-
-    ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
-                        const string& key_material, HidlBuf* key_blob,
-                        KeyCharacteristics* key_characteristics) {
-        ErrorCode error;
-        EXPECT_TRUE(keymaster_
-                        ->importKey(key_desc.hidl_data(), format, HidlBuf(key_material),
-                                    [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
-                                        const KeyCharacteristics& hidl_key_characteristics) {
-                                        error = hidl_error;
-                                        *key_blob = hidl_key_blob;
-                                        *key_characteristics = hidl_key_characteristics;
-                                    })
-                        .isOk());
-        // On error, blob & characteristics should be empty.
-        if (error != ErrorCode::OK) {
-            EXPECT_EQ(0U, key_blob->size());
-            EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() +
-                           key_characteristics->hardwareEnforced.size()));
-        }
-        return error;
-    }
-
-    ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
-                        const string& key_material) {
-        return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
-    }
-
-    ErrorCode ImportWrappedKey(string wrapped_key, string wrapping_key,
-                               const AuthorizationSet& wrapping_key_desc, string masking_key) {
-        ErrorCode error;
-
-        ImportKey(wrapping_key_desc, KeyFormat::PKCS8, wrapping_key);
-
-        EXPECT_TRUE(keymaster_
-                        ->importWrappedKey(HidlBuf(wrapped_key), key_blob_, HidlBuf(masking_key),
-                                           [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
-                                               const KeyCharacteristics& hidl_key_characteristics) {
-                                               error = hidl_error;
-                                               key_blob_ = hidl_key_blob;
-                                               key_characteristics_ = hidl_key_characteristics;
-
-                                           })
-                        .isOk());
-
-        return error;
-    }
-
-    ErrorCode ExportKey(KeyFormat format, const HidlBuf& key_blob, const HidlBuf& client_id,
-                        const HidlBuf& app_data, HidlBuf* key_material) {
-        ErrorCode error;
-        EXPECT_TRUE(
-            keymaster_
-                ->exportKey(format, key_blob, client_id, app_data,
-                            [&](ErrorCode hidl_error_code, const HidlBuf& hidl_key_material) {
-                                error = hidl_error_code;
-                                *key_material = hidl_key_material;
-                            })
-                .isOk());
-        // On error, blob should be empty.
-        if (error != ErrorCode::OK) {
-            EXPECT_EQ(0U, key_material->size());
-        }
-        return error;
-    }
-
-    ErrorCode ExportKey(KeyFormat format, HidlBuf* key_material) {
-        HidlBuf client_id, app_data;
-        return ExportKey(format, key_blob_, client_id, app_data, key_material);
-    }
-
-    ErrorCode DeleteKey(HidlBuf* key_blob, bool keep_key_blob = false) {
-        auto rc = keymaster_->deleteKey(*key_blob);
-        if (!keep_key_blob) *key_blob = HidlBuf();
-        if (!rc.isOk()) return ErrorCode::UNKNOWN_ERROR;
-        return rc;
-    }
-
-    ErrorCode DeleteKey(bool keep_key_blob = false) { return DeleteKey(&key_blob_, keep_key_blob); }
-
-    ErrorCode DeleteAllKeys() {
-        ErrorCode error = keymaster_->deleteAllKeys();
-        return error;
-    }
-
-    void CheckedDeleteKey(HidlBuf* key_blob, bool keep_key_blob = false) {
-        auto rc = DeleteKey(key_blob, keep_key_blob);
-        EXPECT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
-    }
-
-    void CheckedDeleteKey() { CheckedDeleteKey(&key_blob_); }
-
-    ErrorCode GetCharacteristics(const HidlBuf& key_blob, const HidlBuf& client_id,
-                                 const HidlBuf& app_data, KeyCharacteristics* key_characteristics) {
-        ErrorCode error = ErrorCode::UNKNOWN_ERROR;
-        EXPECT_TRUE(
-            keymaster_
-                ->getKeyCharacteristics(
-                    key_blob, client_id, app_data,
-                    [&](ErrorCode hidl_error, const KeyCharacteristics& hidl_key_characteristics) {
-                        error = hidl_error, *key_characteristics = hidl_key_characteristics;
-                    })
-                .isOk());
-        return error;
-    }
-
-    ErrorCode GetCharacteristics(const HidlBuf& key_blob, KeyCharacteristics* key_characteristics) {
-        HidlBuf client_id, app_data;
-        return GetCharacteristics(key_blob, client_id, app_data, key_characteristics);
-    }
-
-    ErrorCode Begin(KeyPurpose purpose, const HidlBuf& key_blob, const AuthorizationSet& in_params,
-                    AuthorizationSet* out_params, OperationHandle* op_handle) {
-        SCOPED_TRACE("Begin");
-        ErrorCode error;
-        OperationHandle saved_handle = *op_handle;
-        EXPECT_TRUE(
-            keymaster_
-                ->begin(purpose, key_blob, in_params.hidl_data(), HardwareAuthToken(),
-                        [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
-                            uint64_t hidl_op_handle) {
-                            error = hidl_error;
-                            *out_params = hidl_out_params;
-                            *op_handle = hidl_op_handle;
-                        })
-                .isOk());
-        if (error != ErrorCode::OK) {
-            // Some implementations may modify *op_handle on error.
-            *op_handle = saved_handle;
-        }
-        return error;
-    }
-
-    ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
-                    AuthorizationSet* out_params) {
-        SCOPED_TRACE("Begin");
-        EXPECT_EQ(kOpHandleSentinel, op_handle_);
-        return Begin(purpose, key_blob_, in_params, out_params, &op_handle_);
-    }
-
-    ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
-        SCOPED_TRACE("Begin");
-        AuthorizationSet out_params;
-        ErrorCode error = Begin(purpose, in_params, &out_params);
-        EXPECT_TRUE(out_params.empty());
-        return error;
-    }
-
-    ErrorCode Update(OperationHandle op_handle, const AuthorizationSet& in_params,
-                     const string& input, AuthorizationSet* out_params, string* output,
-                     size_t* input_consumed) {
-        SCOPED_TRACE("Update");
-        ErrorCode error;
-        EXPECT_TRUE(keymaster_
-                        ->update(op_handle, in_params.hidl_data(), HidlBuf(input),
-                                 HardwareAuthToken(), VerificationToken(),
-                                 [&](ErrorCode hidl_error, uint32_t hidl_input_consumed,
-                                     const hidl_vec<KeyParameter>& hidl_out_params,
-                                     const HidlBuf& hidl_output) {
-                                     error = hidl_error;
-                                     out_params->push_back(AuthorizationSet(hidl_out_params));
-                                     output->append(hidl_output.to_string());
-                                     *input_consumed = hidl_input_consumed;
-                                 })
-                        .isOk());
-        return error;
-    }
-
-    ErrorCode Update(const string& input, string* out, size_t* input_consumed) {
-        SCOPED_TRACE("Update");
-        AuthorizationSet out_params;
-        ErrorCode error = Update(op_handle_, AuthorizationSet() /* in_params */, input, &out_params,
-                                 out, input_consumed);
-        EXPECT_TRUE(out_params.empty());
-        return error;
-    }
-
-    ErrorCode Finish(OperationHandle op_handle, const AuthorizationSet& in_params,
-                     const string& input, const string& signature, AuthorizationSet* out_params,
-                     string* output) {
-        SCOPED_TRACE("Finish");
-        ErrorCode error;
-        EXPECT_TRUE(
-            keymaster_
-                ->finish(op_handle, in_params.hidl_data(), HidlBuf(input), HidlBuf(signature),
-                         HardwareAuthToken(), VerificationToken(),
-                         [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
-                             const HidlBuf& hidl_output) {
-                             error = hidl_error;
-                             *out_params = hidl_out_params;
-                             output->append(hidl_output.to_string());
-                         })
-                .isOk());
-        op_handle_ = kOpHandleSentinel;  // So dtor doesn't Abort().
-        return error;
-    }
-
-    ErrorCode Finish(const string& message, string* output) {
-        SCOPED_TRACE("Finish");
-        AuthorizationSet out_params;
-        string finish_output;
-        ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message,
-                                 "" /* signature */, &out_params, output);
-        if (error != ErrorCode::OK) {
-            return error;
-        }
-        EXPECT_EQ(0U, out_params.size());
-        return error;
-    }
-
-    ErrorCode Finish(string* output) { return Finish(string(), output); }
-
-    ErrorCode Finish(const string& message, const string& signature, string* output) {
-        SCOPED_TRACE("Finish");
-        AuthorizationSet out_params;
-        ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message, signature,
-                                 &out_params, output);
-        op_handle_ = kOpHandleSentinel;  // So dtor doesn't Abort().
-        if (error != ErrorCode::OK) {
-            return error;
-        }
-        EXPECT_EQ(0U, out_params.size());
-        return error;
-    }
-
-    ErrorCode Abort(OperationHandle op_handle) {
-        SCOPED_TRACE("Abort");
-        auto retval = keymaster_->abort(op_handle);
-        EXPECT_TRUE(retval.isOk());
-        return retval;
-    }
-
-    void AbortIfNeeded() {
-        SCOPED_TRACE("AbortIfNeeded");
-        if (op_handle_ != kOpHandleSentinel) {
-            EXPECT_EQ(ErrorCode::OK, Abort(op_handle_));
-            op_handle_ = kOpHandleSentinel;
-        }
-    }
-
-    ErrorCode AttestKey(const HidlBuf& key_blob, const AuthorizationSet& attest_params,
-                        hidl_vec<hidl_vec<uint8_t>>* cert_chain) {
-        SCOPED_TRACE("AttestKey");
-        ErrorCode error;
-        auto rc = keymaster_->attestKey(
-            key_blob, attest_params.hidl_data(),
-            [&](ErrorCode hidl_error, const hidl_vec<hidl_vec<uint8_t>>& hidl_cert_chain) {
-                error = hidl_error;
-                *cert_chain = hidl_cert_chain;
-            });
-
-        EXPECT_TRUE(rc.isOk()) << rc.description();
-        if (!rc.isOk()) return ErrorCode::UNKNOWN_ERROR;
-
-        return error;
-    }
-
-    ErrorCode AttestKey(const AuthorizationSet& attest_params,
-                        hidl_vec<hidl_vec<uint8_t>>* cert_chain) {
-        SCOPED_TRACE("AttestKey");
-        return AttestKey(key_blob_, attest_params, cert_chain);
-    }
-
-    string ProcessMessage(const HidlBuf& key_blob, KeyPurpose operation, const string& message,
-                          const AuthorizationSet& in_params, AuthorizationSet* out_params) {
-        SCOPED_TRACE("ProcessMessage");
-        AuthorizationSet begin_out_params;
-        EXPECT_EQ(ErrorCode::OK,
-                  Begin(operation, key_blob, in_params, &begin_out_params, &op_handle_));
-
-        string unused;
-        AuthorizationSet finish_params;
-        AuthorizationSet finish_out_params;
-        string output;
-        EXPECT_EQ(ErrorCode::OK,
-                  Finish(op_handle_, finish_params, message, unused, &finish_out_params, &output));
-        op_handle_ = kOpHandleSentinel;
-
-        out_params->push_back(begin_out_params);
-        out_params->push_back(finish_out_params);
-        return output;
-    }
-
-    string SignMessage(const HidlBuf& key_blob, const string& message,
-                       const AuthorizationSet& params) {
-        SCOPED_TRACE("SignMessage");
-        AuthorizationSet out_params;
-        string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
-        EXPECT_TRUE(out_params.empty());
-        return signature;
-    }
-
-    string SignMessage(const string& message, const AuthorizationSet& params) {
-        SCOPED_TRACE("SignMessage");
-        return SignMessage(key_blob_, message, params);
-    }
-
-    string MacMessage(const string& message, Digest digest, size_t mac_length) {
-        SCOPED_TRACE("MacMessage");
-        return SignMessage(
-            key_blob_, message,
-            AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
-    }
-
-    void CheckHmacTestVector(const string& key, const string& message, Digest digest,
-                             const string& expected_mac) {
-        SCOPED_TRACE("CheckHmacTestVector");
-        ASSERT_EQ(ErrorCode::OK,
-                  ImportKey(AuthorizationSetBuilder()
-                                .Authorization(TAG_NO_AUTH_REQUIRED)
-                                .HmacKey(key.size() * 8)
-                                .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
-                                .Digest(digest),
-                            KeyFormat::RAW, key));
-        string signature = MacMessage(message, digest, expected_mac.size() * 8);
-        EXPECT_EQ(expected_mac, signature)
-            << "Test vector didn't match for key of size " << key.size() << " message of size "
-            << message.size() << " and digest " << digest;
-        CheckedDeleteKey();
-    }
-
-    void CheckAesCtrTestVector(const string& key, const string& nonce, const string& message,
-                               const string& expected_ciphertext) {
-        SCOPED_TRACE("CheckAesCtrTestVector");
-        ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
-                                               .Authorization(TAG_NO_AUTH_REQUIRED)
-                                               .AesEncryptionKey(key.size() * 8)
-                                               .BlockMode(BlockMode::CTR)
-                                               .Authorization(TAG_CALLER_NONCE)
-                                               .Padding(PaddingMode::NONE),
-                                           KeyFormat::RAW, key));
-
-        auto params = AuthorizationSetBuilder()
-                          .Authorization(TAG_NONCE, nonce.data(), nonce.size())
-                          .BlockMode(BlockMode::CTR)
-                          .Padding(PaddingMode::NONE);
-        AuthorizationSet out_params;
-        string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
-        EXPECT_EQ(expected_ciphertext, ciphertext);
-    }
-
-    void CheckTripleDesTestVector(KeyPurpose purpose, BlockMode block_mode,
-                                  PaddingMode padding_mode, const string& key, const string& iv,
-                                  const string& input, const string& expected_output) {
-        auto authset = AuthorizationSetBuilder()
-                           .TripleDesEncryptionKey(key.size() * 7)
-                           .BlockMode(block_mode)
-                           .Padding(padding_mode);
-        if (iv.size()) authset.Authorization(TAG_CALLER_NONCE);
-
-        ASSERT_EQ(ErrorCode::OK, ImportKey(authset, KeyFormat::RAW, key));
-
-        auto begin_params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
-        if (iv.size()) begin_params.Authorization(TAG_NONCE, iv.data(), iv.size());
-        AuthorizationSet output_params;
-        string output = ProcessMessage(key_blob_, purpose, input, begin_params, &output_params);
-        EXPECT_EQ(expected_output, output);
-    }
-
-    void VerifyMessage(const HidlBuf& key_blob, const string& message, const string& signature,
-                       const AuthorizationSet& params) {
-        SCOPED_TRACE("VerifyMessage");
-        AuthorizationSet begin_out_params;
-        ASSERT_EQ(ErrorCode::OK,
-                  Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params, &op_handle_));
-
-        string unused;
-        AuthorizationSet finish_params;
-        AuthorizationSet finish_out_params;
-        string output;
-        EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, signature,
-                                        &finish_out_params, &output));
-        op_handle_ = kOpHandleSentinel;
-        EXPECT_TRUE(output.empty());
-    }
-
-    void VerifyMessage(const string& message, const string& signature,
-                       const AuthorizationSet& params) {
-        SCOPED_TRACE("VerifyMessage");
-        VerifyMessage(key_blob_, message, signature, params);
-    }
-
-    string EncryptMessage(const HidlBuf& key_blob, const string& message,
-                          const AuthorizationSet& in_params, AuthorizationSet* out_params) {
-        SCOPED_TRACE("EncryptMessage");
-        return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
-    }
-
-    string EncryptMessage(const string& message, const AuthorizationSet& params,
-                          AuthorizationSet* out_params) {
-        SCOPED_TRACE("EncryptMessage");
-        return EncryptMessage(key_blob_, message, params, out_params);
-    }
-
-    string EncryptMessage(const string& message, const AuthorizationSet& params) {
-        SCOPED_TRACE("EncryptMessage");
-        AuthorizationSet out_params;
-        string ciphertext = EncryptMessage(message, params, &out_params);
-        EXPECT_TRUE(out_params.empty())
-            << "Output params should be empty. Contained: " << out_params;
-        return ciphertext;
-    }
-
-    string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding) {
-        SCOPED_TRACE("EncryptMessage");
-        auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
-        AuthorizationSet out_params;
-        string ciphertext = EncryptMessage(message, params, &out_params);
-        EXPECT_TRUE(out_params.empty())
-            << "Output params should be empty. Contained: " << out_params;
-        return ciphertext;
-    }
-
-    string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
-                          HidlBuf* iv) {
-        SCOPED_TRACE("EncryptMessage");
-        auto params = AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding);
-        AuthorizationSet out_params;
-        string ciphertext = EncryptMessage(message, params, &out_params);
-        EXPECT_EQ(1U, out_params.size());
-        auto ivVal = out_params.GetTagValue(TAG_NONCE);
-        EXPECT_TRUE(ivVal.isOk());
-        *iv = ivVal.value();
-        return ciphertext;
-    }
-
-    string EncryptMessage(const string& message, BlockMode block_mode, PaddingMode padding,
-                          const HidlBuf& iv) {
-        SCOPED_TRACE("EncryptMessage");
-        auto params = AuthorizationSetBuilder()
-                          .BlockMode(block_mode)
-                          .Padding(padding)
-                          .Authorization(TAG_NONCE, iv);
-        AuthorizationSet out_params;
-        string ciphertext = EncryptMessage(message, params, &out_params);
-        return ciphertext;
-    }
-
-    string DecryptMessage(const HidlBuf& key_blob, const string& ciphertext,
-                          const AuthorizationSet& params) {
-        SCOPED_TRACE("DecryptMessage");
-        AuthorizationSet out_params;
-        string plaintext =
-            ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
-        EXPECT_TRUE(out_params.empty());
-        return plaintext;
-    }
-
-    string DecryptMessage(const string& ciphertext, const AuthorizationSet& params) {
-        SCOPED_TRACE("DecryptMessage");
-        return DecryptMessage(key_blob_, ciphertext, params);
-    }
-
-    string DecryptMessage(const string& ciphertext, BlockMode block_mode, PaddingMode padding_mode,
-                          const HidlBuf& iv) {
-        SCOPED_TRACE("DecryptMessage");
-        auto params = AuthorizationSetBuilder()
-                          .BlockMode(block_mode)
-                          .Padding(padding_mode)
-                          .Authorization(TAG_NONCE, iv);
-        return DecryptMessage(key_blob_, ciphertext, params);
-    }
-
-    std::pair<ErrorCode, HidlBuf> UpgradeKey(const HidlBuf& key_blob) {
-        std::pair<ErrorCode, HidlBuf> retval;
-        keymaster_->upgradeKey(key_blob, hidl_vec<KeyParameter>(),
-                               [&](ErrorCode error, const hidl_vec<uint8_t>& upgraded_blob) {
-                                   retval = std::tie(error, upgraded_blob);
-                               });
-        return retval;
-    }
-
-    static bool IsSecure() { return securityLevel_ != SecurityLevel::SOFTWARE; }
-
-    HidlBuf key_blob_;
-    KeyCharacteristics key_characteristics_;
-    OperationHandle op_handle_ = kOpHandleSentinel;
-
-   private:
-    static sp<IKeymasterDevice> keymaster_;
-    static uint32_t os_version_;
-    static uint32_t os_patch_level_;
-
-    static SecurityLevel securityLevel_;
-    static hidl_string name_;
-    static hidl_string author_;
-};
-
 bool verify_attestation_record(const string& challenge, const string& app_id,
                                AuthorizationSet expected_sw_enforced,
                                AuthorizationSet expected_tee_enforced,
@@ -1032,13 +413,6 @@
     return true;
 }
 
-sp<IKeymasterDevice> KeymasterHidlTest::keymaster_;
-uint32_t KeymasterHidlTest::os_version_;
-uint32_t KeymasterHidlTest::os_patch_level_;
-SecurityLevel KeymasterHidlTest::securityLevel_;
-hidl_string KeymasterHidlTest::name_;
-hidl_string KeymasterHidlTest::author_;
-
 class NewKeyGenerationTest : public KeymasterHidlTest {
    protected:
     void CheckBaseParams(const KeyCharacteristics& keyCharacteristics) {