Merge "wifi: add an api route for removing a P2P client"
diff --git a/drm/1.0/vts/functional/Android.bp b/drm/1.0/vts/functional/Android.bp
index 5ea6ad3..a35d41d 100644
--- a/drm/1.0/vts/functional/Android.bp
+++ b/drm/1.0/vts/functional/Android.bp
@@ -23,6 +23,14 @@
     default_applicable_licenses: ["hardware_interfaces_license"],
 }
 
+cc_library_headers {
+    name: "drm_hal_vendor_module_headers",
+    vendor_available: true,
+    export_include_dirs: [
+        "include",
+    ],
+}
+
 cc_library_static {
     name: "libdrmvtshelper",
     defaults: ["VtsHalTargetTestDefaults"],
@@ -36,6 +44,7 @@
         "android.hardware.drm@1.0-helper",
     ],
     export_include_dirs: ["include"],
+    export_static_lib_headers: ["android.hardware.drm@1.0-helper"],
 }
 
 cc_library_static {
diff --git a/drm/1.2/vts/functional/Android.bp b/drm/1.2/vts/functional/Android.bp
index ca90ee9..5a655e7 100644
--- a/drm/1.2/vts/functional/Android.bp
+++ b/drm/1.2/vts/functional/Android.bp
@@ -24,6 +24,19 @@
 }
 
 cc_library_static {
+    name: "libvtsclearkey",
+    srcs: [
+        "drm_hal_clearkey_module.cpp",
+    ],
+    static_libs: [
+        "libgtest",
+    ],
+    header_libs: ["drm_hal_vendor_module_headers"],
+    export_header_lib_headers: ["drm_hal_vendor_module_headers"],
+    export_include_dirs: ["."],
+}
+
+cc_library_static {
     name: "android.hardware.drm@1.2-vts",
     defaults: ["VtsHalTargetTestDefaults"],
     local_include_dirs: [
diff --git a/drm/aidl/vts/Android.bp b/drm/aidl/vts/Android.bp
new file mode 100644
index 0000000..5b41830
--- /dev/null
+++ b/drm/aidl/vts/Android.bp
@@ -0,0 +1,73 @@
+//
+// Copyright (C) 2021 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.
+//
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "hardware_interfaces_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["hardware_interfaces_license"],
+}
+
+cc_test {
+    name: "VtsAidlHalDrmTargetTest",
+    defaults: [
+        "VtsHalTargetTestDefaults",
+        "use_libaidlvintf_gtest_helper_static",
+    ],
+    srcs: [
+        "drm_hal_common.cpp",
+        "drm_hal_test.cpp",
+        "drm_hal_test_main.cpp",
+    ],
+    local_include_dirs: [
+        "include",
+    ],
+    header_libs: [
+        "drm_hal_vendor_module_headers",
+    ],
+    shared_libs: [
+        "libandroid",
+        "libbinder_ndk",
+        "libcrypto",
+        "libnativehelper",
+    ],
+    static_libs: [
+        "android.hardware.drm@1.0-helper",
+        "android.hardware.drm-V1-ndk",
+        "android.hardware.common-V2-ndk",
+        "libdrmvtshelper",
+        "libvtsclearkey",
+    ],
+    arch: {
+        arm: {
+            data: [":libvtswidevine-arm-prebuilts"],
+        },
+        arm64: {
+            data: [":libvtswidevine-arm64-prebuilts"],
+        },
+        x86: {
+            data: [":libvtswidevine-x86-prebuilts"],
+        },
+        x86_64: {
+            data: [":libvtswidevine-x86_64-prebuilts"],
+        },
+    },
+    test_suites: [
+        "general-tests",
+        "vts",
+    ],
+}
diff --git a/drm/aidl/vts/AndroidTest.xml b/drm/aidl/vts/AndroidTest.xml
new file mode 100644
index 0000000..9e5b41a
--- /dev/null
+++ b/drm/aidl/vts/AndroidTest.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+<configuration description="Runs VtsAidlHalDrmTargetTest.">
+    <option name="test-suite-tag" value="apct" />
+    <option name="test-suite-tag" value="apct-native" />
+    <option name="not-shardable" value="true" />
+
+    <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer"/>
+
+    <target_preparer class="com.android.tradefed.targetprep.WifiPreparer" >
+        <option name="verify-only" value="true" />
+    </target_preparer>
+
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="true" />
+        <option name="push-file" key="VtsAidlHalDrmTargetTest" value="/data/local/tmp/VtsAidlHalDrmTargetTest" />
+        <option name="push-file" key="libvtswidevine64.so" value="/data/local/tmp/64/lib/libvtswidevine.so" />
+        <option name="push-file" key="libvtswidevine32.so" value="/data/local/tmp/32/lib/libvtswidevine.so" />
+    </target_preparer>
+
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="VtsAidlHalDrmTargetTest" />
+    </test>
+</configuration>
diff --git a/drm/aidl/vts/OWNERS b/drm/aidl/vts/OWNERS
new file mode 100644
index 0000000..e44b93e
--- /dev/null
+++ b/drm/aidl/vts/OWNERS
@@ -0,0 +1,4 @@
+edwinwong@google.com
+jtinker@google.com
+kelzhan@google.com
+robertshih@google.com
diff --git a/drm/aidl/vts/drm_hal_common.cpp b/drm/aidl/vts/drm_hal_common.cpp
new file mode 100644
index 0000000..751c25b
--- /dev/null
+++ b/drm/aidl/vts/drm_hal_common.cpp
@@ -0,0 +1,602 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+
+#define LOG_TAG "drm_hal_common"
+
+#include <gtest/gtest.h>
+#include <log/log.h>
+#include <openssl/aes.h>
+#include <sys/mman.h>
+#include <random>
+
+#include <android/binder_manager.h>
+#include <android/binder_process.h>
+#include <android/sharedmem.h>
+
+#include "drm_hal_clearkey_module.h"
+#include "drm_hal_common.h"
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace drm {
+namespace vts {
+
+namespace clearkeydrm = ::android::hardware::drm::V1_2::vts;
+
+using std::vector;
+using ::aidl::android::hardware::common::Ashmem;
+using ::aidl::android::hardware::drm::BufferType;
+using ::aidl::android::hardware::drm::DecryptResult;
+using ::aidl::android::hardware::drm::DestinationBuffer;
+using ::aidl::android::hardware::drm::EventType;
+using ::aidl::android::hardware::drm::ICryptoPlugin;
+using ::aidl::android::hardware::drm::IDrmPlugin;
+using ::aidl::android::hardware::drm::KeyRequest;
+using ::aidl::android::hardware::drm::KeyRequestType;
+using ::aidl::android::hardware::drm::KeySetId;
+using ::aidl::android::hardware::drm::KeyType;
+using ::aidl::android::hardware::drm::KeyValue;
+using ::aidl::android::hardware::drm::Mode;
+using ::aidl::android::hardware::drm::Pattern;
+using ::aidl::android::hardware::drm::ProvisionRequest;
+using ::aidl::android::hardware::drm::ProvideProvisionResponseResult;
+using ::aidl::android::hardware::drm::SecurityLevel;
+using ::aidl::android::hardware::drm::Status;
+using ::aidl::android::hardware::drm::SubSample;
+using ::aidl::android::hardware::drm::Uuid;
+
+Status DrmErr(const ::ndk::ScopedAStatus& ret) {
+    return static_cast<Status>(ret.getServiceSpecificError());
+}
+
+std::string HalBaseName(const std::string& fullname) {
+    auto idx = fullname.find('/');
+    if (idx == std::string::npos) {
+        return fullname;
+    }
+    return fullname.substr(idx + 1);
+}
+
+const char* kDrmIface = "android.hardware.drm.IDrmFactory";
+const char* kCryptoIface = "android.hardware.drm.ICryptoFactory";
+
+std::string HalFullName(const std::string& iface, const std::string& basename) {
+    return iface + '/' + basename;
+}
+
+testing::AssertionResult IsOk(const ::ndk::ScopedAStatus& ret) {
+    if (ret.isOk()) {
+        return testing::AssertionSuccess();
+    }
+    return testing::AssertionFailure() << "ex: " << ret.getExceptionCode()
+                                       << "; svc err: " << ret.getServiceSpecificError()
+                                       << "; desc: " << ret.getDescription();
+}
+
+const char* kCallbackLostState = "LostState";
+const char* kCallbackKeysChange = "KeysChange";
+
+drm_vts::VendorModules* DrmHalTest::gVendorModules = nullptr;
+
+/**
+ * DrmHalPluginListener
+ */
+::ndk::ScopedAStatus DrmHalPluginListener::onEvent(
+        EventType eventType,
+        const vector<uint8_t>& sessionId,
+        const vector<uint8_t>& data) {
+    ListenerArgs args{};
+    args.eventType = eventType;
+    args.sessionId = sessionId;
+    args.data = data;
+    eventPromise.set_value(args);
+    return ::ndk::ScopedAStatus::ok();
+}
+
+::ndk::ScopedAStatus DrmHalPluginListener::onExpirationUpdate(
+        const vector<uint8_t>& sessionId,
+        int64_t expiryTimeInMS) {
+    ListenerArgs args{};
+    args.sessionId = sessionId;
+    args.expiryTimeInMS = expiryTimeInMS;
+    expirationUpdatePromise.set_value(args);
+    return ::ndk::ScopedAStatus::ok();
+
+}
+
+::ndk::ScopedAStatus DrmHalPluginListener::onSessionLostState(const vector<uint8_t>& sessionId) {
+    ListenerArgs args{};
+    args.sessionId = sessionId;
+    sessionLostStatePromise.set_value(args);
+    return ::ndk::ScopedAStatus::ok();
+}
+
+::ndk::ScopedAStatus DrmHalPluginListener::onKeysChange(
+        const std::vector<uint8_t>& sessionId,
+        const std::vector<::aidl::android::hardware::drm::KeyStatus>& keyStatusList,
+        bool hasNewUsableKey) {
+    ListenerArgs args{};
+    args.sessionId = sessionId;
+    args.keyStatusList = keyStatusList;
+    args.hasNewUsableKey = hasNewUsableKey;
+    keysChangePromise.set_value(args);
+    return ::ndk::ScopedAStatus::ok();
+}
+
+ListenerArgs DrmHalPluginListener::getListenerArgs(std::promise<ListenerArgs>& promise) {
+    auto future = promise.get_future();
+    auto timeout = std::chrono::milliseconds(500);
+    EXPECT_EQ(future.wait_for(timeout), std::future_status::ready);
+    return future.get();
+}
+
+ListenerArgs DrmHalPluginListener::getEventArgs() {
+    return getListenerArgs(eventPromise);
+}
+
+ListenerArgs DrmHalPluginListener::getExpirationUpdateArgs() {
+    return getListenerArgs(expirationUpdatePromise);
+}
+
+ListenerArgs DrmHalPluginListener::getSessionLostStateArgs() {
+    return getListenerArgs(sessionLostStatePromise);
+}
+
+ListenerArgs DrmHalPluginListener::getKeysChangeArgs() {
+    return getListenerArgs(keysChangePromise);
+}
+
+static DrmHalVTSVendorModule_V1* getModuleForInstance(const std::string& instance) {
+    if (instance.find("clearkey") != std::string::npos ||
+        instance.find("default") != std::string::npos) {
+        return new clearkeydrm::DrmHalVTSClearkeyModule();
+    }
+
+    return static_cast<DrmHalVTSVendorModule_V1*>(
+            DrmHalTest::gVendorModules->getModuleByName(instance));
+}
+
+/**
+ * DrmHalTest
+ */
+
+DrmHalTest::DrmHalTest() : vendorModule(getModuleForInstance(GetParamService())) {}
+
+void DrmHalTest::SetUp() {
+    const ::testing::TestInfo* const test_info =
+            ::testing::UnitTest::GetInstance()->current_test_info();
+
+    ALOGD("Running test %s.%s from (vendor) module %s", test_info->test_case_name(),
+          test_info->name(), GetParamService().c_str());
+
+    auto svc = GetParamService();
+    const string cryptoInstance = HalFullName(kCryptoIface, svc);
+    const string drmInstance = HalFullName(kDrmIface, svc);
+
+    if (drmInstance.find("IDrmFactory") != std::string::npos) {
+        drmFactory = IDrmFactory::fromBinder(
+                ::ndk::SpAIBinder(AServiceManager_waitForService(drmInstance.c_str())));
+        ASSERT_NE(drmFactory, nullptr);
+        drmPlugin = createDrmPlugin();
+    }
+
+    if (cryptoInstance.find("ICryptoFactory") != std::string::npos) {
+        cryptoFactory = ICryptoFactory::fromBinder(
+                ::ndk::SpAIBinder(AServiceManager_waitForService(cryptoInstance.c_str())));
+        ASSERT_NE(cryptoFactory, nullptr);
+        cryptoPlugin = createCryptoPlugin();
+    }
+
+    if (!vendorModule) {
+        ASSERT_NE(drmInstance, "widevine") << "Widevine requires vendor module.";
+        ASSERT_NE(drmInstance, "clearkey") << "Clearkey requires vendor module.";
+        GTEST_SKIP() << "No vendor module installed";
+    }
+
+    ASSERT_EQ(HalBaseName(drmInstance), vendorModule->getServiceName());
+    contentConfigurations = vendorModule->getContentConfigurations();
+
+    // If drm scheme not installed skip subsequent tests
+    bool result = false;
+    drmFactory->isCryptoSchemeSupported({getUUID()}, "cenc", SecurityLevel::SW_SECURE_CRYPTO,
+                                        &result);
+    if (!result) {
+        if (GetParamUUID() == std::array<uint8_t, 16>()) {
+            GTEST_SKIP() << "vendor module drm scheme not supported";
+        } else {
+            FAIL() << "param scheme must not supported";
+        }
+    }
+
+    ASSERT_NE(nullptr, drmPlugin.get())
+            << "Can't find " << vendorModule->getServiceName() << " drm aidl plugin";
+    ASSERT_NE(nullptr, cryptoPlugin.get())
+            << "Can't find " << vendorModule->getServiceName() << " crypto aidl plugin";
+}
+
+std::shared_ptr<::aidl::android::hardware::drm::IDrmPlugin> DrmHalTest::createDrmPlugin() {
+    if (drmFactory == nullptr) {
+        return nullptr;
+    }
+    std::string packageName("aidl.android.hardware.drm.test");
+    std::shared_ptr<::aidl::android::hardware::drm::IDrmPlugin> result;
+    auto ret = drmFactory->createPlugin({getUUID()}, packageName, &result);
+    EXPECT_OK(ret) << "createDrmPlugin remote call failed";
+    return result;
+}
+
+std::shared_ptr<::aidl::android::hardware::drm::ICryptoPlugin> DrmHalTest::createCryptoPlugin() {
+    if (cryptoFactory == nullptr) {
+        return nullptr;
+    }
+    vector<uint8_t> initVec;
+    std::shared_ptr<::aidl::android::hardware::drm::ICryptoPlugin> result;
+    auto ret = cryptoFactory->createPlugin({getUUID()}, initVec, &result);
+    EXPECT_OK(ret) << "createCryptoPlugin remote call failed";
+    return result;
+}
+
+::aidl::android::hardware::drm::Uuid DrmHalTest::getAidlUUID() {
+    return toAidlUuid(getUUID());
+}
+
+std::vector<uint8_t> DrmHalTest::getUUID() {
+    auto paramUUID = GetParamUUID();
+    if (paramUUID == std::array<uint8_t, 16>()) {
+        return getVendorUUID();
+    }
+    return std::vector(paramUUID.begin(), paramUUID.end());
+}
+
+std::vector<uint8_t> DrmHalTest::getVendorUUID() {
+    if (vendorModule == nullptr) {
+        ALOGW("vendor module for %s not found", GetParamService().c_str());
+        return {};
+    }
+    return vendorModule->getUUID();
+}
+
+void DrmHalTest::provision() {
+    std::string certificateType;
+    std::string certificateAuthority;
+    vector<uint8_t> provisionRequest;
+    std::string defaultUrl;
+    ProvisionRequest result;
+    auto ret = drmPlugin->getProvisionRequest(certificateType, certificateAuthority, &result);
+
+    EXPECT_TXN(ret);
+    if (ret.isOk()) {
+        EXPECT_NE(result.request.size(), 0u);
+        provisionRequest = result.request;
+        defaultUrl = result.defaultUrl;
+    } else if (DrmErr(ret) == Status::ERROR_DRM_CANNOT_HANDLE) {
+        EXPECT_EQ(0u, result.request.size());
+    }
+
+    if (provisionRequest.size() > 0) {
+        vector<uint8_t> response =
+                vendorModule->handleProvisioningRequest(provisionRequest, defaultUrl);
+        ASSERT_NE(0u, response.size());
+
+        ProvideProvisionResponseResult result;
+        auto ret = drmPlugin->provideProvisionResponse(response, &result);
+        EXPECT_TXN(ret);
+    }
+}
+
+SessionId DrmHalTest::openSession(SecurityLevel level, Status* err) {
+    SessionId sessionId;
+    auto ret = drmPlugin->openSession(level, &sessionId);
+    EXPECT_TXN(ret);
+    *err = DrmErr(ret);
+    return sessionId;
+}
+
+/**
+ * Helper method to open a session and verify that a non-empty
+ * session ID is returned
+ */
+SessionId DrmHalTest::openSession() {
+    SessionId sessionId;
+    auto ret = drmPlugin->openSession(SecurityLevel::DEFAULT, &sessionId);
+    EXPECT_OK(ret);
+    EXPECT_NE(0u, sessionId.size());
+    return sessionId;
+}
+
+/**
+ * Helper method to close a session
+ */
+void DrmHalTest::closeSession(const SessionId& sessionId) {
+    auto ret = drmPlugin->closeSession(sessionId);
+    EXPECT_OK(ret);
+}
+
+vector<uint8_t> DrmHalTest::getKeyRequest(
+        const SessionId& sessionId,
+        const DrmHalVTSVendorModule_V1::ContentConfiguration& configuration,
+        const KeyType& type = KeyType::STREAMING) {
+    KeyRequest result;
+    auto ret = drmPlugin->getKeyRequest(sessionId, configuration.initData, configuration.mimeType,
+                                        type, toAidlKeyedVector(configuration.optionalParameters),
+                                        &result);
+    EXPECT_OK(ret) << "Failed to get key request for configuration "
+                   << configuration.name << " for key type "
+                   << static_cast<int>(type);
+    if (type == KeyType::RELEASE) {
+        EXPECT_EQ(KeyRequestType::RELEASE, result.requestType);
+    } else {
+        EXPECT_EQ(KeyRequestType::INITIAL, result.requestType);
+    }
+    EXPECT_NE(result.request.size(), 0u) << "Expected key request size"
+                                            " to have length > 0 bytes";
+    return result.request;
+}
+
+DrmHalVTSVendorModule_V1::ContentConfiguration DrmHalTest::getContent(const KeyType& type) const {
+    for (const auto& config : contentConfigurations) {
+        if (type != KeyType::OFFLINE || config.policy.allowOffline) {
+            return config;
+        }
+    }
+    ADD_FAILURE() << "no content configurations found";
+    return {};
+}
+
+vector<uint8_t> DrmHalTest::provideKeyResponse(const SessionId& sessionId,
+                                               const vector<uint8_t>& keyResponse) {
+    KeySetId result;
+    auto ret = drmPlugin->provideKeyResponse(sessionId, keyResponse, &result);
+    EXPECT_OK(ret) << "Failure providing key response for configuration ";
+    return result.keySetId;
+}
+
+/**
+ * Helper method to load keys for subsequent decrypt tests.
+ * These tests use predetermined key request/response to
+ * avoid requiring a round trip to a license server.
+ */
+vector<uint8_t> DrmHalTest::loadKeys(
+        const SessionId& sessionId,
+        const DrmHalVTSVendorModule_V1::ContentConfiguration& configuration, const KeyType& type) {
+    vector<uint8_t> keyRequest = getKeyRequest(sessionId, configuration, type);
+
+    /**
+     * Get key response from vendor module
+     */
+    vector<uint8_t> keyResponse =
+            vendorModule->handleKeyRequest(keyRequest, configuration.serverUrl);
+    EXPECT_NE(keyResponse.size(), 0u) << "Expected key response size "
+                                         "to have length > 0 bytes";
+
+    return provideKeyResponse(sessionId, keyResponse);
+}
+
+vector<uint8_t> DrmHalTest::loadKeys(const SessionId& sessionId, const KeyType& type) {
+    return loadKeys(sessionId, getContent(type), type);
+}
+
+std::array<uint8_t, 16> DrmHalTest::toStdArray(const vector<uint8_t>& vec) {
+    EXPECT_EQ(16u, vec.size());
+    std::array<uint8_t, 16> arr;
+    std::copy_n(vec.begin(), vec.size(), arr.begin());
+    return arr;
+}
+
+KeyedVector DrmHalTest::toAidlKeyedVector(const map<string, string>& params) {
+    std::vector<KeyValue> stdKeyedVector;
+    for (auto it = params.begin(); it != params.end(); ++it) {
+        KeyValue keyValue;
+        keyValue.key = it->first;
+        keyValue.value = it->second;
+        stdKeyedVector.push_back(keyValue);
+    }
+    return KeyedVector(stdKeyedVector);
+}
+
+/**
+ * getDecryptMemory allocates memory for decryption, then sets it
+ * as a shared buffer base in the crypto hal.  A parcelable Ashmem
+ * is returned.
+ *
+ * @param size the size of the memory segment to allocate
+ * @param the index of the memory segment which will be used
+ * to refer to it for decryption.
+ */
+Ashmem DrmHalTest::getDecryptMemory(size_t size, size_t index) {
+    int fd = ASharedMemory_create("drmVtsSharedMemory", size);
+    EXPECT_GE(fd, 0);
+    EXPECT_EQ(size, ASharedMemory_getSize(fd));
+
+    Ashmem ashmem;
+    ashmem.fd = ::ndk::ScopedFileDescriptor(fd);
+    ashmem.size = size;
+    EXPECT_OK(cryptoPlugin->setSharedBufferBase(ashmem, index));
+    return ashmem;
+}
+
+void DrmHalTest::fillRandom(const Ashmem& ashmem) {
+    std::random_device rd;
+    std::mt19937 rand(rd());
+
+    ::ndk::ScopedFileDescriptor fd = ashmem.fd.dup();
+    size_t size = ashmem.size;
+    uint8_t* base = static_cast<uint8_t*>(
+            mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd.get(), 0));
+    EXPECT_NE(MAP_FAILED, base);
+    for (size_t i = 0; i < size / sizeof(uint32_t); i++) {
+        auto p = static_cast<uint32_t*>(static_cast<void*>(base));
+        p[i] = rand();
+    }
+}
+
+uint32_t DrmHalTest::decrypt(Mode mode, bool isSecure, const std::array<uint8_t, 16>& keyId,
+                             uint8_t* iv, const vector<SubSample>& subSamples,
+                             const Pattern& pattern, const vector<uint8_t>& key,
+                             Status expectedStatus) {
+    const size_t kSegmentIndex = 0;
+
+    uint8_t localIv[AES_BLOCK_SIZE];
+    memcpy(localIv, iv, AES_BLOCK_SIZE);
+    vector<uint8_t> ivVec(localIv, localIv + AES_BLOCK_SIZE);
+
+    int64_t totalSize = 0;
+    for (size_t i = 0; i < subSamples.size(); i++) {
+        totalSize += subSamples[i].numBytesOfClearData;
+        totalSize += subSamples[i].numBytesOfEncryptedData;
+    }
+
+    // The first totalSize bytes of shared memory is the encrypted
+    // input, the second totalSize bytes (if exists) is the decrypted output.
+    size_t factor = expectedStatus == Status::ERROR_DRM_FRAME_TOO_LARGE ? 1 : 2;
+    Ashmem sharedMemory = getDecryptMemory(totalSize * factor, kSegmentIndex);
+
+    const SharedBuffer sourceBuffer = {.bufferId = kSegmentIndex, .offset = 0, .size = totalSize};
+    fillRandom(sharedMemory);
+
+    const DestinationBuffer destBuffer = {
+            .type = BufferType::SHARED_MEMORY,
+            .nonsecureMemory = {.bufferId = kSegmentIndex, .offset = totalSize, .size = totalSize},
+            .secureMemory = {.fds = {}, .ints = {}}};
+    const uint64_t offset = 0;
+    uint32_t bytesWritten = 0;
+    vector<uint8_t> keyIdVec(keyId.begin(), keyId.end());
+    DecryptResult result;
+    auto ret = cryptoPlugin->decrypt(isSecure, keyIdVec, ivVec, mode, pattern, subSamples,
+                                     sourceBuffer, offset, destBuffer, &result);
+    EXPECT_TXN(ret);
+    EXPECT_EQ(expectedStatus, DrmErr(ret)) << "Unexpected decrypt status " << result.detailedError;
+    bytesWritten = result.bytesWritten;
+
+    if (bytesWritten != totalSize) {
+        return bytesWritten;
+    }
+    ::ndk::ScopedFileDescriptor fd = sharedMemory.fd.dup();
+    uint8_t* base = static_cast<uint8_t*>(
+            mmap(nullptr, totalSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd.get(), 0));
+    EXPECT_NE(MAP_FAILED, base);
+
+    // generate reference vector
+    vector<uint8_t> reference(totalSize);
+
+    memcpy(localIv, iv, AES_BLOCK_SIZE);
+    switch (mode) {
+        case Mode::UNENCRYPTED:
+            memcpy(&reference[0], base, totalSize);
+            break;
+        case Mode::AES_CTR:
+            aes_ctr_decrypt(&reference[0], base, localIv, subSamples, key);
+            break;
+        case Mode::AES_CBC:
+            aes_cbc_decrypt(&reference[0], base, localIv, subSamples, key);
+            break;
+        case Mode::AES_CBC_CTS:
+            ADD_FAILURE() << "AES_CBC_CTS mode not supported";
+            break;
+    }
+
+    // compare reference to decrypted data which is at base + total size
+    EXPECT_EQ(0, memcmp(static_cast<void*>(&reference[0]), static_cast<void*>(base + totalSize),
+                        totalSize))
+            << "decrypt data mismatch";
+    return totalSize;
+}
+
+/**
+ * Decrypt a list of clear+encrypted subsamples using the specified key
+ * in AES-CTR mode
+ */
+void DrmHalTest::aes_ctr_decrypt(uint8_t* dest, uint8_t* src, uint8_t* iv,
+                                 const vector<SubSample>& subSamples, const vector<uint8_t>& key) {
+    AES_KEY decryptionKey;
+    AES_set_encrypt_key(&key[0], 128, &decryptionKey);
+
+    size_t offset = 0;
+    unsigned int blockOffset = 0;
+    uint8_t previousEncryptedCounter[AES_BLOCK_SIZE];
+    memset(previousEncryptedCounter, 0, AES_BLOCK_SIZE);
+
+    for (size_t i = 0; i < subSamples.size(); i++) {
+        const SubSample& subSample = subSamples[i];
+
+        if (subSample.numBytesOfClearData > 0) {
+            memcpy(dest + offset, src + offset, subSample.numBytesOfClearData);
+            offset += subSample.numBytesOfClearData;
+        }
+
+        if (subSample.numBytesOfEncryptedData > 0) {
+            AES_ctr128_encrypt(src + offset, dest + offset, subSample.numBytesOfEncryptedData,
+                               &decryptionKey, iv, previousEncryptedCounter, &blockOffset);
+            offset += subSample.numBytesOfEncryptedData;
+        }
+    }
+}
+
+/**
+ * Decrypt a list of clear+encrypted subsamples using the specified key
+ * in AES-CBC mode
+ */
+void DrmHalTest::aes_cbc_decrypt(uint8_t* dest, uint8_t* src, uint8_t* iv,
+                                 const vector<SubSample>& subSamples, const vector<uint8_t>& key) {
+    AES_KEY decryptionKey;
+    AES_set_encrypt_key(&key[0], 128, &decryptionKey);
+
+    size_t offset = 0;
+    for (size_t i = 0; i < subSamples.size(); i++) {
+        memcpy(dest + offset, src + offset, subSamples[i].numBytesOfClearData);
+        offset += subSamples[i].numBytesOfClearData;
+
+        AES_cbc_encrypt(src + offset, dest + offset, subSamples[i].numBytesOfEncryptedData,
+                        &decryptionKey, iv, 0 /* decrypt */);
+        offset += subSamples[i].numBytesOfEncryptedData;
+    }
+}
+
+/**
+ * Helper method to test decryption with invalid keys is returned
+ */
+void DrmHalClearkeyTest::decryptWithInvalidKeys(vector<uint8_t>& invalidResponse,
+                                                vector<uint8_t>& iv, const Pattern& noPattern,
+                                                const vector<SubSample>& subSamples) {
+    DrmHalVTSVendorModule_V1::ContentConfiguration content = getContent();
+    if (content.keys.empty()) {
+        FAIL() << "no keys";
+    }
+
+    const auto& key = content.keys[0];
+    auto sessionId = openSession();
+    KeySetId result;
+    auto ret = drmPlugin->provideKeyResponse(sessionId, invalidResponse, &result);
+
+    EXPECT_OK(ret);
+    EXPECT_EQ(0u, result.keySetId.size());
+
+    EXPECT_OK(cryptoPlugin->setMediaDrmSession(sessionId));
+
+    uint32_t byteCount =
+            decrypt(Mode::AES_CTR, key.isSecure, toStdArray(key.keyId), &iv[0], subSamples,
+                    noPattern, key.clearContentKey, Status::ERROR_DRM_NO_LICENSE);
+    EXPECT_EQ(0u, byteCount);
+
+    closeSession(sessionId);
+}
+
+}  // namespace vts
+}  // namespace drm
+}  // namespace hardware
+}  // namespace android
+}  // namespace aidl
diff --git a/drm/aidl/vts/drm_hal_test.cpp b/drm/aidl/vts/drm_hal_test.cpp
new file mode 100644
index 0000000..3ac9f5c
--- /dev/null
+++ b/drm/aidl/vts/drm_hal_test.cpp
@@ -0,0 +1,551 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+
+#define LOG_TAG "drm_hal_test"
+
+#include <gtest/gtest.h>
+#include <log/log.h>
+#include <openssl/aes.h>
+
+#include <memory>
+#include <vector>
+
+#include "drm_hal_common.h"
+
+using ::aidl::android::hardware::drm::EventType;
+using ::aidl::android::hardware::drm::HdcpLevels;
+using ::aidl::android::hardware::drm::KeyRequest;
+using ::aidl::android::hardware::drm::HdcpLevel;
+using ::aidl::android::hardware::drm::IDrmPluginListener;
+using ::aidl::android::hardware::drm::KeyRequestType;
+using ::aidl::android::hardware::drm::KeySetId;
+using ::aidl::android::hardware::drm::KeyStatus;
+using ::aidl::android::hardware::drm::KeyStatusType;
+using ::aidl::android::hardware::drm::KeyType;
+using ::aidl::android::hardware::drm::Mode;
+using ::aidl::android::hardware::drm::OfflineLicenseState;
+using ::aidl::android::hardware::drm::Pattern;
+using ::aidl::android::hardware::drm::SecurityLevel;
+using ::aidl::android::hardware::drm::Status;
+using ::aidl::android::hardware::drm::SubSample;
+using ::aidl::android::hardware::drm::Uuid;
+
+using ::aidl::android::hardware::drm::vts::DrmErr;
+using ::aidl::android::hardware::drm::vts::DrmHalClearkeyTest;
+using ::aidl::android::hardware::drm::vts::DrmHalPluginListener;
+using ::aidl::android::hardware::drm::vts::DrmHalTest;
+using ::aidl::android::hardware::drm::vts::ListenerArgs;
+using ::aidl::android::hardware::drm::vts::kCallbackKeysChange;
+using ::aidl::android::hardware::drm::vts::kCallbackLostState;
+
+using std::string;
+using std::vector;
+
+static const char* const kVideoMp4 = "video/mp4";
+static const char* const kBadMime = "video/unknown";
+static const char* const kDrmErrorTestKey = "drmErrorTest";
+static const char* const kDrmErrorInvalidState = "invalidState";
+static const char* const kDrmErrorResourceContention = "resourceContention";
+static constexpr SecurityLevel kSwSecureCrypto = SecurityLevel::SW_SECURE_CRYPTO;
+static constexpr SecurityLevel kHwSecureAll = SecurityLevel::HW_SECURE_ALL;
+
+/**
+ * Ensure drm factory supports module UUID Scheme
+ */
+TEST_P(DrmHalTest, VendorUuidSupported) {
+    bool result = false;
+    auto ret =
+            drmFactory->isCryptoSchemeSupported(getAidlUUID(), kVideoMp4, kSwSecureCrypto, &result);
+    ALOGI("kVideoMp4 = %s res %d", kVideoMp4, static_cast<bool>(result));
+    EXPECT_OK(ret);
+    EXPECT_TRUE(result);
+}
+
+/**
+ * Ensure drm factory doesn't support an invalid scheme UUID
+ */
+TEST_P(DrmHalTest, InvalidPluginNotSupported) {
+    const vector<uint8_t> kInvalidUUID = {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80,
+                                          0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80};
+    bool result = false;
+    auto ret = drmFactory->isCryptoSchemeSupported(toAidlUuid(kInvalidUUID), kVideoMp4,
+                                                   kSwSecureCrypto, &result);
+    EXPECT_OK(ret);
+    EXPECT_FALSE(result);
+}
+
+/**
+ * Ensure drm factory doesn't support an empty UUID
+ */
+TEST_P(DrmHalTest, EmptyPluginUUIDNotSupported) {
+    vector<uint8_t> emptyUUID(16);
+    memset(emptyUUID.data(), 0, 16);
+    bool result = false;
+    auto ret = drmFactory->isCryptoSchemeSupported(toAidlUuid(emptyUUID), kVideoMp4,
+                                                   kSwSecureCrypto, &result);
+    EXPECT_OK(ret);
+    EXPECT_FALSE(result);
+}
+
+/**
+ * Ensure drm factory doesn't support an invalid mime type
+ */
+TEST_P(DrmHalTest, BadMimeNotSupported) {
+    bool result = false;
+    auto ret =
+            drmFactory->isCryptoSchemeSupported(getAidlUUID(), kBadMime, kSwSecureCrypto, &result);
+    EXPECT_OK(ret);
+    EXPECT_FALSE(result);
+}
+
+/**
+ *  DrmPlugin tests
+ */
+
+/**
+ * Test that a DRM plugin can handle provisioning.  While
+ * it is not required that a DRM scheme require provisioning,
+ * it should at least return appropriate status values. If
+ * a provisioning request is returned, it is passed to the
+ * vendor module which should provide a provisioning response
+ * that is delivered back to the HAL.
+ */
+TEST_P(DrmHalTest, DoProvisioning) {
+    for (auto level : {kHwSecureAll, kSwSecureCrypto}) {
+        Status err = Status::OK;
+        auto sid = openSession(level, &err);
+        if (err == Status::OK) {
+            closeSession(sid);
+        } else if (err == Status::ERROR_DRM_CANNOT_HANDLE) {
+            continue;
+        } else {
+            EXPECT_EQ(Status::ERROR_DRM_NOT_PROVISIONED, err);
+            provision();
+        }
+    }
+}
+
+/**
+ * A get key request should fail if no sessionId is provided
+ */
+TEST_P(DrmHalTest, GetKeyRequestNoSession) {
+    SessionId invalidSessionId;
+    vector<uint8_t> initData;
+    KeyedVector optionalParameters;
+    KeyRequest result;
+    auto ret = drmPlugin->getKeyRequest(invalidSessionId, initData, kVideoMp4, KeyType::STREAMING,
+                                        optionalParameters, &result);
+    EXPECT_TXN(ret);
+    EXPECT_EQ(Status::BAD_VALUE, DrmErr(ret));
+}
+
+/**
+ * Test that the plugin returns the documented error for the
+ * case of attempting to generate a key request using an
+ * invalid mime type
+ */
+TEST_P(DrmHalTest, GetKeyRequestBadMime) {
+    auto sessionId = openSession();
+    vector<uint8_t> initData;
+    KeyedVector optionalParameters;
+    KeyRequest result;
+    auto ret = drmPlugin->getKeyRequest(sessionId, initData, kBadMime, KeyType::STREAMING,
+                                        optionalParameters, &result);
+    EXPECT_EQ(EX_SERVICE_SPECIFIC, ret.getExceptionCode());
+    closeSession(sessionId);
+}
+
+/**
+ * Test drm plugin offline key support
+ */
+TEST_P(DrmHalTest, OfflineLicenseTest) {
+    auto sessionId = openSession();
+    vector<uint8_t> keySetId = loadKeys(sessionId, KeyType::OFFLINE);
+    closeSession(sessionId);
+
+    vector<KeySetId> result;
+    auto ret = drmPlugin->getOfflineLicenseKeySetIds(&result);
+    EXPECT_OK(ret);
+    bool found = false;
+    for (KeySetId keySetId2 : result) {
+        if (keySetId == keySetId2.keySetId) {
+            found = true;
+            break;
+        }
+    }
+    EXPECT_TRUE(found) << "keySetId not found";
+
+    ret = drmPlugin->removeOfflineLicense({keySetId});
+    EXPECT_OK(ret);
+
+    ret = drmPlugin->getOfflineLicenseKeySetIds(&result);
+    EXPECT_OK(ret);
+    for (KeySetId keySetId2 : result) {
+        EXPECT_NE(keySetId, keySetId2.keySetId);
+    }
+
+    ret = drmPlugin->removeOfflineLicense({keySetId});
+    EXPECT_TXN(ret);
+    EXPECT_EQ(Status::BAD_VALUE, DrmErr(ret));
+}
+
+/**
+ * Test drm plugin offline key state
+ */
+TEST_P(DrmHalTest, OfflineLicenseStateTest) {
+    auto sessionId = openSession();
+    DrmHalVTSVendorModule_V1::ContentConfiguration content = getContent(KeyType::OFFLINE);
+    vector<uint8_t> keySetId = loadKeys(sessionId, content, KeyType::OFFLINE);
+    closeSession(sessionId);
+
+    OfflineLicenseState result{};
+    auto ret = drmPlugin->getOfflineLicenseState({keySetId}, &result);
+    EXPECT_OK(ret);
+    EXPECT_EQ(OfflineLicenseState::USABLE, result);
+
+    vector<uint8_t> keyRequest = getKeyRequest(keySetId, content, KeyType::RELEASE);
+    ret = drmPlugin->getOfflineLicenseState({keySetId}, &result);
+    EXPECT_OK(ret);
+    EXPECT_EQ(OfflineLicenseState::INACTIVE, result);
+
+    /**
+     * Get key response from vendor module
+     */
+    vector<uint8_t> keyResponse = vendorModule->handleKeyRequest(keyRequest, content.serverUrl);
+    EXPECT_GT(keyResponse.size(), 0u);
+
+    result = OfflineLicenseState::UNKNOWN;
+    provideKeyResponse(keySetId, keyResponse);
+    ret = drmPlugin->getOfflineLicenseState({keySetId}, &result);
+    EXPECT_TXN(ret);
+    EXPECT_EQ(Status::BAD_VALUE, DrmErr(ret));
+    EXPECT_EQ(OfflineLicenseState::UNKNOWN, result);
+}
+
+/**
+ * Negative offline license test. Remove empty keySetId
+ */
+TEST_P(DrmHalTest, RemoveEmptyKeySetId) {
+    KeySetId emptyKeySetId;
+    auto ret = drmPlugin->removeOfflineLicense(emptyKeySetId);
+    EXPECT_TXN(ret);
+    EXPECT_EQ(Status::BAD_VALUE, DrmErr(ret));
+}
+
+/**
+ * Negative offline license test. Get empty keySetId state
+ */
+TEST_P(DrmHalTest, GetEmptyKeySetIdState) {
+    KeySetId emptyKeySetId;
+    OfflineLicenseState result;
+    auto ret = drmPlugin->getOfflineLicenseState(emptyKeySetId, &result);
+    EXPECT_TXN(ret);
+    EXPECT_EQ(Status::BAD_VALUE, DrmErr(ret));
+    EXPECT_EQ(OfflineLicenseState::UNKNOWN, result);
+}
+
+/**
+ * Test that the plugin returns valid connected and max HDCP levels
+ */
+TEST_P(DrmHalTest, GetHdcpLevels) {
+    HdcpLevels result;
+    auto ret = drmPlugin->getHdcpLevels(&result);
+    EXPECT_OK(ret);
+    EXPECT_GE(result.connectedLevel, HdcpLevel::HDCP_NONE);
+    EXPECT_LE(result.maxLevel, HdcpLevel::HDCP_V2_3);
+}
+
+/**
+ *  CryptoPlugin Decrypt tests
+ */
+
+/**
+ * Positive decrypt test. "Decrypt" a single clear segment
+ */
+TEST_P(DrmHalTest, ClearSegmentTest) {
+    for (const auto& config : contentConfigurations) {
+        for (const auto& key : config.keys) {
+            const size_t kSegmentSize = 1024;
+            vector<uint8_t> iv(AES_BLOCK_SIZE, 0);
+            const Pattern noPattern = {0, 0};
+            const vector<SubSample> subSamples = {
+                    {.numBytesOfClearData = kSegmentSize, .numBytesOfEncryptedData = 0}};
+            auto sessionId = openSession();
+            loadKeys(sessionId, config);
+
+            auto ret = cryptoPlugin->setMediaDrmSession(sessionId);
+            EXPECT_OK(ret);
+
+            uint32_t byteCount =
+                    decrypt(Mode::UNENCRYPTED, key.isSecure, toStdArray(key.keyId), &iv[0],
+                            subSamples, noPattern, key.clearContentKey, Status::OK);
+            EXPECT_EQ(kSegmentSize, byteCount);
+
+            closeSession(sessionId);
+        }
+    }
+}
+
+/**
+ * Positive decrypt test. Decrypt a single segment using aes_ctr.
+ * Verify data matches.
+ */
+TEST_P(DrmHalTest, EncryptedAesCtrSegmentTest) {
+    for (const auto& config : contentConfigurations) {
+        for (const auto& key : config.keys) {
+            const size_t kSegmentSize = 1024;
+            vector<uint8_t> iv(AES_BLOCK_SIZE, 0);
+            const Pattern noPattern = {0, 0};
+            const vector<SubSample> subSamples = {
+                    {.numBytesOfClearData = kSegmentSize, .numBytesOfEncryptedData = 0}};
+            auto sessionId = openSession();
+            loadKeys(sessionId, config);
+
+            auto ret = cryptoPlugin->setMediaDrmSession(sessionId);
+            EXPECT_OK(ret);
+
+            uint32_t byteCount = decrypt(Mode::AES_CTR, key.isSecure, toStdArray(key.keyId), &iv[0],
+                                         subSamples, noPattern, key.clearContentKey, Status::OK);
+            EXPECT_EQ(kSegmentSize, byteCount);
+
+            closeSession(sessionId);
+        }
+    }
+}
+
+/**
+ * Negative decrypt test.  Decrypted frame too large to fit in output buffer
+ */
+TEST_P(DrmHalTest, ErrorFrameTooLarge) {
+    for (const auto& config : contentConfigurations) {
+        for (const auto& key : config.keys) {
+            const size_t kSegmentSize = 1024;
+            vector<uint8_t> iv(AES_BLOCK_SIZE, 0);
+            const Pattern noPattern = {0, 0};
+            const vector<SubSample> subSamples = {
+                    {.numBytesOfClearData = kSegmentSize, .numBytesOfEncryptedData = 0}};
+            auto sessionId = openSession();
+            loadKeys(sessionId, config);
+
+            auto ret = cryptoPlugin->setMediaDrmSession(sessionId);
+            EXPECT_OK(ret);
+
+            decrypt(Mode::UNENCRYPTED, key.isSecure, toStdArray(key.keyId), &iv[0], subSamples,
+                    noPattern, key.clearContentKey, Status::ERROR_DRM_FRAME_TOO_LARGE);
+
+            closeSession(sessionId);
+        }
+    }
+}
+
+/**
+ * Negative decrypt test. Decrypt without loading keys.
+ */
+TEST_P(DrmHalTest, EncryptedAesCtrSegmentTestNoKeys) {
+    for (const auto& config : contentConfigurations) {
+        for (const auto& key : config.keys) {
+            vector<uint8_t> iv(AES_BLOCK_SIZE, 0);
+            const Pattern noPattern = {0, 0};
+            const vector<SubSample> subSamples = {
+                    {.numBytesOfClearData = 256, .numBytesOfEncryptedData = 256}};
+            auto sessionId = openSession();
+
+            auto ret = cryptoPlugin->setMediaDrmSession(sessionId);
+            EXPECT_OK(ret);
+
+            uint32_t byteCount =
+                    decrypt(Mode::AES_CTR, key.isSecure, toStdArray(key.keyId), &iv[0], subSamples,
+                            noPattern, key.clearContentKey, Status::ERROR_DRM_NO_LICENSE);
+            EXPECT_EQ(0u, byteCount);
+
+            closeSession(sessionId);
+        }
+    }
+}
+
+/**
+ * Ensure clearkey drm factory doesn't support security level higher than supported
+ */
+TEST_P(DrmHalClearkeyTest, BadLevelNotSupported) {
+    bool result = false;
+    auto ret = drmFactory->isCryptoSchemeSupported(getAidlUUID(), kVideoMp4, kHwSecureAll, &result);
+    EXPECT_OK(ret);
+    EXPECT_FALSE(result);
+}
+
+/**
+ * Test resource contention during attempt to generate key request
+ */
+TEST_P(DrmHalClearkeyTest, GetKeyRequestResourceContention) {
+    auto ret = drmPlugin->setPropertyString(kDrmErrorTestKey, kDrmErrorResourceContention);
+    EXPECT_OK(ret);
+
+    auto sessionId = openSession();
+    vector<uint8_t> initData;
+    KeyedVector optionalParameters;
+    KeyRequest result;
+    ret = drmPlugin->getKeyRequest(sessionId, initData, kVideoMp4, KeyType::STREAMING,
+                                   optionalParameters, &result);
+    EXPECT_TXN(ret);
+    EXPECT_EQ(Status::ERROR_DRM_RESOURCE_CONTENTION, DrmErr(ret));
+
+    ret = drmPlugin->closeSession(sessionId);
+    EXPECT_TXN(ret);
+    EXPECT_NE(Status::OK, DrmErr(ret));
+}
+
+/**
+ * Test clearkey plugin offline key with mock error
+ */
+TEST_P(DrmHalClearkeyTest, OfflineLicenseInvalidState) {
+    auto sessionId = openSession();
+    vector<uint8_t> keySetId = loadKeys(sessionId, KeyType::OFFLINE);
+    auto ret = drmPlugin->setPropertyString(kDrmErrorTestKey, kDrmErrorInvalidState);
+    EXPECT_OK(ret);
+
+    // everything should start failing
+    const Status kInvalidState = Status::ERROR_DRM_INVALID_STATE;
+    vector<KeySetId> result;
+    ret = drmPlugin->getOfflineLicenseKeySetIds(&result);
+    EXPECT_TXN(ret);
+    EXPECT_EQ(kInvalidState, DrmErr(ret));
+    EXPECT_EQ(0u, result.size());
+
+    OfflineLicenseState state = OfflineLicenseState::UNKNOWN;
+    ret = drmPlugin->getOfflineLicenseState({keySetId}, &state);
+    EXPECT_TXN(ret);
+    EXPECT_EQ(kInvalidState, DrmErr(ret));
+    EXPECT_EQ(OfflineLicenseState::UNKNOWN, state);
+
+    ret = drmPlugin->removeOfflineLicense({keySetId});
+    EXPECT_TXN(ret);
+    EXPECT_EQ(kInvalidState, DrmErr(ret));
+    closeSession(sessionId);
+}
+
+/**
+ * Test listener is triggered on key response
+ */
+TEST_P(DrmHalClearkeyTest, ListenerCallbacks) {
+    auto listener = ndk::SharedRefBase::make<DrmHalPluginListener>();
+    auto res = drmPlugin->setListener(listener);
+    EXPECT_OK(res);
+
+    auto sessionId = openSession();
+    loadKeys(sessionId, KeyType::STREAMING);
+    closeSession(sessionId);
+
+    auto args = listener->getEventArgs();
+    EXPECT_EQ(EventType::VENDOR_DEFINED, args.eventType);
+    EXPECT_EQ(sessionId, args.data);
+    EXPECT_EQ(sessionId, args.sessionId);
+
+    args = listener->getExpirationUpdateArgs();
+    EXPECT_EQ(sessionId, args.sessionId);
+    EXPECT_EQ(100, args.expiryTimeInMS);
+
+    args = listener->getKeysChangeArgs();
+    const vector<KeyStatus> keyStatusList = {
+            {{0xa, 0xb, 0xc}, KeyStatusType::USABLE},
+            {{0xd, 0xe, 0xf}, KeyStatusType::EXPIRED},
+            {{0x0, 0x1, 0x2}, KeyStatusType::USABLEINFUTURE},
+    };
+    EXPECT_EQ(sessionId, args.sessionId);
+    EXPECT_EQ(keyStatusList, args.keyStatusList);
+    EXPECT_TRUE(args.hasNewUsableKey);
+}
+
+/**
+ * Test SessionLostState is triggered on error
+ */
+TEST_P(DrmHalClearkeyTest, SessionLostState) {
+    auto listener = ndk::SharedRefBase::make<DrmHalPluginListener>();
+    auto res = drmPlugin->setListener(listener);
+    EXPECT_OK(res);
+
+    res = drmPlugin->setPropertyString(kDrmErrorTestKey, kDrmErrorInvalidState);
+    EXPECT_OK(res);
+
+    auto sessionId = openSession();
+    auto ret = drmPlugin->closeSession(sessionId);
+
+    auto args = listener->getSessionLostStateArgs();
+    EXPECT_EQ(sessionId, args.sessionId);
+}
+
+/**
+ * Negative decrypt test. Decrypt with invalid key.
+ */
+TEST_P(DrmHalClearkeyTest, DecryptWithEmptyKey) {
+    vector<uint8_t> iv(AES_BLOCK_SIZE, 0);
+    const Pattern noPattern = {0, 0};
+    const uint32_t kClearBytes = 512;
+    const uint32_t kEncryptedBytes = 512;
+    const vector<SubSample> subSamples = {
+            {.numBytesOfClearData = kClearBytes, .numBytesOfEncryptedData = kEncryptedBytes}};
+
+    // base 64 encoded JSON response string, must not contain padding character '='
+    const string emptyKeyResponse =
+            "{\"keys\":["
+            "{"
+            "\"kty\":\"oct\""
+            "\"alg\":\"A128KW2\""
+            "\"k\":\"SGVsbG8gRnJpZW5kIQ\""
+            "\"kid\":\"Y2xlYXJrZXlrZXlpZDAyAy\""
+            "}"
+            "{"
+            "\"kty\":\"oct\","
+            "\"alg\":\"A128KW2\""
+            "\"kid\":\"Y2xlYXJrZXlrZXlpZDAzAy\","  // empty key follows
+            "\"k\":\"R\""
+            "}]"
+            "}";
+    const size_t kEmptyKeyResponseSize = emptyKeyResponse.size();
+
+    vector<uint8_t> invalidResponse;
+    invalidResponse.resize(kEmptyKeyResponseSize);
+    memcpy(invalidResponse.data(), emptyKeyResponse.c_str(), kEmptyKeyResponseSize);
+    decryptWithInvalidKeys(invalidResponse, iv, noPattern, subSamples);
+}
+
+/**
+ * Negative decrypt test. Decrypt with a key exceeds AES_BLOCK_SIZE.
+ */
+TEST_P(DrmHalClearkeyTest, DecryptWithKeyTooLong) {
+    vector<uint8_t> iv(AES_BLOCK_SIZE, 0);
+    const Pattern noPattern = {0, 0};
+    const uint32_t kClearBytes = 512;
+    const uint32_t kEncryptedBytes = 512;
+    const vector<SubSample> subSamples = {
+            {.numBytesOfClearData = kClearBytes, .numBytesOfEncryptedData = kEncryptedBytes}};
+
+    // base 64 encoded JSON response string, must not contain padding character '='
+    const string keyTooLongResponse =
+            "{\"keys\":["
+            "{"
+            "\"kty\":\"oct\","
+            "\"alg\":\"A128KW2\""
+            "\"kid\":\"Y2xlYXJrZXlrZXlpZDAzAy\","  // key too long
+            "\"k\":\"V2lubmllIHRoZSBwb29oIVdpbm5pZSB0aGUgcG9vaCE=\""
+            "}]"
+            "}";
+    const size_t kKeyTooLongResponseSize = keyTooLongResponse.size();
+
+    vector<uint8_t> invalidResponse;
+    invalidResponse.resize(kKeyTooLongResponseSize);
+    memcpy(invalidResponse.data(), keyTooLongResponse.c_str(), kKeyTooLongResponseSize);
+    decryptWithInvalidKeys(invalidResponse, iv, noPattern, subSamples);
+}
diff --git a/drm/aidl/vts/drm_hal_test_main.cpp b/drm/aidl/vts/drm_hal_test_main.cpp
new file mode 100644
index 0000000..dc0f6d7
--- /dev/null
+++ b/drm/aidl/vts/drm_hal_test_main.cpp
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+
+/**
+ * Instantiate the set of test cases for each vendor module
+ */
+
+#define LOG_TAG "drm_hal_test_main"
+
+#include <aidl/Gtest.h>
+#include <aidl/Vintf.h>
+#include <android/binder_process.h>
+#include <log/log.h>
+
+#include <gtest/gtest.h>
+
+#include <algorithm>
+#include <iterator>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "drm_hal_common.h"
+
+using ::aidl::android::hardware::drm::vts::DrmHalClearkeyTest;
+using ::aidl::android::hardware::drm::vts::DrmHalTest;
+using ::aidl::android::hardware::drm::vts::HalBaseName;
+using drm_vts::DrmHalTestParam;
+using drm_vts::PrintParamInstanceToString;
+
+static const std::vector<DrmHalTestParam> getAllInstances() {
+    using ::aidl::android::hardware::drm::ICryptoFactory;
+    using ::aidl::android::hardware::drm::IDrmFactory;
+
+    std::vector<std::string> drmInstances =
+            android::getAidlHalInstanceNames(IDrmFactory::descriptor);
+    std::vector<std::string> cryptoInstances =
+            android::getAidlHalInstanceNames(ICryptoFactory::descriptor);
+
+    std::set<std::string> allInstances;
+    for (auto svc : drmInstances) {
+        allInstances.insert(HalBaseName(svc));
+    }
+    for (auto svc : cryptoInstances) {
+        allInstances.insert(HalBaseName(svc));
+    }
+
+    std::vector<DrmHalTestParam> allInstanceUuidCombos;
+    auto noUUID = [](std::string s) { return DrmHalTestParam(s); };
+    std::transform(allInstances.begin(), allInstances.end(),
+                   std::back_inserter(allInstanceUuidCombos), noUUID);
+    return allInstanceUuidCombos;
+};
+
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DrmHalTest);
+INSTANTIATE_TEST_SUITE_P(PerInstance, DrmHalTest, testing::ValuesIn(getAllInstances()),
+                         PrintParamInstanceToString);
+GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DrmHalClearkeyTest);
+INSTANTIATE_TEST_SUITE_P(PerInstance, DrmHalClearkeyTest, testing::ValuesIn(getAllInstances()),
+                         PrintParamInstanceToString);
+
+int main(int argc, char** argv) {
+#if defined(__LP64__)
+    const char* kModulePath = "/data/local/tmp/64/lib";
+#else
+    const char* kModulePath = "/data/local/tmp/32/lib";
+#endif
+    DrmHalTest::gVendorModules = new drm_vts::VendorModules(kModulePath);
+    if (DrmHalTest::gVendorModules->getPathList().size() == 0) {
+        std::cerr << "WARNING: No vendor modules found in " << kModulePath
+                  << ", all vendor tests will be skipped" << std::endl;
+    }
+    ABinderProcess_setThreadPoolMaxThreadCount(1);
+    ABinderProcess_startThreadPool();
+    ::testing::InitGoogleTest(&argc, argv);
+    int status = RUN_ALL_TESTS();
+    ALOGI("Test result = %d", status);
+    return status;
+}
diff --git a/drm/aidl/vts/include/drm_hal_common.h b/drm/aidl/vts/include/drm_hal_common.h
new file mode 100644
index 0000000..4aac48b
--- /dev/null
+++ b/drm/aidl/vts/include/drm_hal_common.h
@@ -0,0 +1,214 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+
+#pragma once
+
+#include <aidl/android/hardware/common/Ashmem.h>
+#include <aidl/android/hardware/drm/BnDrmPluginListener.h>
+#include <aidl/android/hardware/drm/ICryptoFactory.h>
+#include <aidl/android/hardware/drm/ICryptoPlugin.h>
+#include <aidl/android/hardware/drm/IDrmFactory.h>
+#include <aidl/android/hardware/drm/IDrmPlugin.h>
+#include <aidl/android/hardware/drm/IDrmPluginListener.h>
+#include <aidl/android/hardware/drm/Status.h>
+
+#include <array>
+#include <chrono>
+#include <future>
+#include <iostream>
+#include <map>
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include <android/binder_auto_utils.h>
+
+#include "VtsHalHidlTargetCallbackBase.h"
+#include "drm_hal_vendor_module_api.h"
+#include "drm_vts_helper.h"
+#include "vendor_modules.h"
+
+using drm_vts::DrmHalTestParam;
+
+namespace {
+typedef vector<::aidl::android::hardware::drm::KeyValue> KeyedVector;
+typedef std::vector<uint8_t> SessionId;
+}  // namespace
+
+#define EXPECT_OK(ret) EXPECT_TRUE(::aidl::android::hardware::drm::vts::IsOk(ret))
+#define EXPECT_TXN(ret) EXPECT_TRUE(ret.isOk() || ret.getExceptionCode() == EX_SERVICE_SPECIFIC)
+
+namespace aidl {
+namespace android {
+namespace hardware {
+namespace drm {
+namespace vts {
+
+::aidl::android::hardware::drm::Status DrmErr(const ::ndk::ScopedAStatus& ret);
+std::string HalBaseName(const std::string& fullname);
+std::string HalFullName(const std::string& iface, const std::string& basename);
+testing::AssertionResult IsOk(const ::ndk::ScopedAStatus& ret);
+
+extern const char* kDrmIface;
+extern const char* kCryptoIface;
+
+class DrmHalTest : public ::testing::TestWithParam<DrmHalTestParam> {
+  public:
+    static drm_vts::VendorModules* gVendorModules;
+    DrmHalTest();
+    virtual void SetUp() override;
+    virtual void TearDown() override {}
+
+  protected:
+    ::aidl::android::hardware::drm::Uuid getAidlUUID();
+    std::vector<uint8_t> getUUID();
+    std::vector<uint8_t> getVendorUUID();
+    std::array<uint8_t, 16> GetParamUUID() { return GetParam().scheme_; }
+    std::string GetParamService() { return GetParam().instance_; }
+    ::aidl::android::hardware::drm::Uuid toAidlUuid(const std::vector<uint8_t>& in_uuid) {
+        ::aidl::android::hardware::drm::Uuid uuid;
+        uuid.uuid = in_uuid;
+        return uuid;
+    }
+
+    void provision();
+    SessionId openSession(::aidl::android::hardware::drm::SecurityLevel level,
+                          ::aidl::android::hardware::drm::Status* err);
+    SessionId openSession();
+    void closeSession(const SessionId& sessionId);
+    std::vector<uint8_t> loadKeys(
+            const SessionId& sessionId,
+            const ::aidl::android::hardware::drm::KeyType& type = KeyType::STREAMING);
+    std::vector<uint8_t> loadKeys(
+            const SessionId& sessionId, const DrmHalVTSVendorModule_V1::ContentConfiguration&,
+            const ::aidl::android::hardware::drm::KeyType& type = KeyType::STREAMING);
+    std::vector<uint8_t> getKeyRequest(const SessionId& sessionId,
+                                       const DrmHalVTSVendorModule_V1::ContentConfiguration&,
+                                       const ::aidl::android::hardware::drm::KeyType& type);
+    std::vector<uint8_t> provideKeyResponse(const SessionId& sessionId,
+                                            const std::vector<uint8_t>& keyResponse);
+    DrmHalVTSVendorModule_V1::ContentConfiguration getContent(
+            const ::aidl::android::hardware::drm::KeyType& type = KeyType::STREAMING) const;
+
+    KeyedVector toAidlKeyedVector(const std::map<std::string, std::string>& params);
+    std::array<uint8_t, 16> toStdArray(const std::vector<uint8_t>& vec);
+    void fillRandom(const ::aidl::android::hardware::common::Ashmem& ashmem);
+    ::aidl::android::hardware::common::Ashmem getDecryptMemory(size_t size, size_t index);
+
+    uint32_t decrypt(::aidl::android::hardware::drm::Mode mode, bool isSecure,
+                     const std::array<uint8_t, 16>& keyId, uint8_t* iv,
+                     const std::vector<::aidl::android::hardware::drm::SubSample>& subSamples,
+                     const ::aidl::android::hardware::drm::Pattern& pattern,
+                     const std::vector<uint8_t>& key,
+                     ::aidl::android::hardware::drm::Status expectedStatus);
+    void aes_ctr_decrypt(uint8_t* dest, uint8_t* src, uint8_t* iv,
+                         const std::vector<::aidl::android::hardware::drm::SubSample>& subSamples,
+                         const std::vector<uint8_t>& key);
+    void aes_cbc_decrypt(uint8_t* dest, uint8_t* src, uint8_t* iv,
+                         const std::vector<::aidl::android::hardware::drm::SubSample>& subSamples,
+                         const std::vector<uint8_t>& key);
+
+    std::shared_ptr<::aidl::android::hardware::drm::IDrmFactory> drmFactory;
+    std::shared_ptr<::aidl::android::hardware::drm::ICryptoFactory> cryptoFactory;
+    std::shared_ptr<::aidl::android::hardware::drm::IDrmPlugin> drmPlugin;
+    std::shared_ptr<::aidl::android::hardware::drm::ICryptoPlugin> cryptoPlugin;
+
+    unique_ptr<DrmHalVTSVendorModule_V1> vendorModule;
+    std::vector<DrmHalVTSVendorModule_V1::ContentConfiguration> contentConfigurations;
+
+  private:
+    std::shared_ptr<::aidl::android::hardware::drm::IDrmPlugin> createDrmPlugin();
+    std::shared_ptr<::aidl::android::hardware::drm::ICryptoPlugin> createCryptoPlugin();
+};
+
+class DrmHalClearkeyTest : public DrmHalTest {
+  public:
+    virtual void SetUp() override {
+        DrmHalTest::SetUp();
+        const std::vector<uint8_t> kClearKeyUUID = {0xE2, 0x71, 0x9D, 0x58, 0xA9, 0x85, 0xB3, 0xC9,
+                                                    0x78, 0x1A, 0xB0, 0x30, 0xAF, 0x78, 0xD3, 0x0E};
+        static const std::string kMimeType = "video/mp4";
+        static constexpr ::aidl::android::hardware::drm::SecurityLevel kSecurityLevel =
+                ::aidl::android::hardware::drm::SecurityLevel::SW_SECURE_CRYPTO;
+
+        bool drmClearkey = false;
+        auto ret = drmFactory->isCryptoSchemeSupported(toAidlUuid(kClearKeyUUID), kMimeType,
+                                                       kSecurityLevel, &drmClearkey);
+        if (!drmClearkey) {
+            GTEST_SKIP() << "ClearKey not supported by " << GetParamService();
+        }
+    }
+    virtual void TearDown() override {}
+    void decryptWithInvalidKeys(
+            std::vector<uint8_t>& invalidResponse, std::vector<uint8_t>& iv,
+            const ::aidl::android::hardware::drm::Pattern& noPattern,
+            const std::vector<::aidl::android::hardware::drm::SubSample>& subSamples);
+};
+
+/**
+ *  Event Handling tests
+ */
+extern const char* kCallbackLostState;
+extern const char* kCallbackKeysChange;
+
+struct ListenerArgs {
+    EventType eventType;
+    SessionId sessionId;
+    int64_t expiryTimeInMS;
+    std::vector<uint8_t> data;
+    std::vector<KeyStatus> keyStatusList;
+    bool hasNewUsableKey;
+};
+
+class DrmHalPluginListener : public BnDrmPluginListener {
+  public:
+    DrmHalPluginListener() {}
+    virtual ~DrmHalPluginListener() {}
+
+    virtual ::ndk::ScopedAStatus onEvent(
+            ::aidl::android::hardware::drm::EventType in_eventType,
+            const std::vector<uint8_t>& in_sessionId,
+            const std::vector<uint8_t>& in_data) override;
+
+    virtual ::ndk::ScopedAStatus onExpirationUpdate(
+            const std::vector<uint8_t>& in_sessionId,
+            int64_t in_expiryTimeInMS) override;
+
+    virtual ::ndk::ScopedAStatus onSessionLostState(
+            const std::vector<uint8_t>& in_sessionId) override;
+
+    virtual ::ndk::ScopedAStatus onKeysChange(
+            const std::vector<uint8_t>& in_sessionId,
+            const std::vector<::aidl::android::hardware::drm::KeyStatus>& in_keyStatusList,
+            bool in_hasNewUsableKey) override;
+
+    ListenerArgs getEventArgs();
+    ListenerArgs getExpirationUpdateArgs();
+    ListenerArgs getSessionLostStateArgs();
+    ListenerArgs getKeysChangeArgs();
+
+  private:
+    ListenerArgs getListenerArgs(std::promise<ListenerArgs>& promise);
+    std::promise<ListenerArgs> eventPromise, expirationUpdatePromise,
+            sessionLostStatePromise, keysChangePromise;
+};
+
+}  // namespace vts
+}  // namespace drm
+}  // namespace hardware
+}  // namespace android
+}  // namespace aidl
diff --git a/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/BufferAheadResult.aidl b/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/BufferAheadResult.aidl
new file mode 100644
index 0000000..94fd91b
--- /dev/null
+++ b/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/BufferAheadResult.aidl
@@ -0,0 +1,44 @@
+/**
+ * Copyright (c) 2022, 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.
+ */
+///////////////////////////////////////////////////////////////////////////////
+// THIS FILE IS IMMUTABLE. DO NOT EDIT IN ANY CASE.                          //
+///////////////////////////////////////////////////////////////////////////////
+
+// This file is a snapshot of an AIDL file. Do not edit it manually. There are
+// two cases:
+// 1). this is a frozen version file - do not edit this in any case.
+// 2). this is a 'current' file. If you make a backwards compatible change to
+//     the interface (from the latest frozen version), the build system will
+//     prompt you to update this file with `m <name>-update-api`.
+//
+// You must not make a backward incompatible change to any AIDL file built
+// with the aidl_interface module type with versions property set. The module
+// type is used to build AIDL files in a way that they can be used across
+// independently updatable components of the system. If a device is shipped
+// with such a backward incompatible change, it has a high risk of breaking
+// later when a module using the interface is updated, e.g., Mainline modules.
+
+package android.hardware.graphics.composer3;
+@VintfStability
+parcelable BufferAheadResult {
+  long display;
+  android.hardware.graphics.composer3.BufferAheadResult.Layer[] layers;
+  @VintfStability
+  parcelable Layer {
+    long layer;
+    boolean presented;
+  }
+}
diff --git a/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/Capability.aidl b/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/Capability.aidl
index 9c49583..e989b6c 100644
--- a/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/Capability.aidl
+++ b/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/Capability.aidl
@@ -39,4 +39,5 @@
   SKIP_CLIENT_COLOR_TRANSFORM = 2,
   PRESENT_FENCE_IS_NOT_RELIABLE = 3,
   SKIP_VALIDATE = 4,
+  BUFFER_AHEAD = 5,
 }
diff --git a/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/CommandResultPayload.aidl b/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/CommandResultPayload.aidl
index ebbb31e..fb39172 100644
--- a/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/CommandResultPayload.aidl
+++ b/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/CommandResultPayload.aidl
@@ -39,6 +39,7 @@
   android.hardware.graphics.composer3.DisplayRequest displayRequest;
   android.hardware.graphics.composer3.PresentFence presentFence;
   android.hardware.graphics.composer3.ReleaseFences releaseFences;
+  android.hardware.graphics.composer3.BufferAheadResult bufferAheadResult;
   android.hardware.graphics.composer3.PresentOrValidate presentOrValidateResult;
   android.hardware.graphics.composer3.ClientTargetPropertyWithNits clientTargetProperty;
 }
diff --git a/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/LayerCommand.aidl b/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/LayerCommand.aidl
index c1c0117..1429c35 100644
--- a/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/LayerCommand.aidl
+++ b/graphics/composer/aidl/aidl_api/android.hardware.graphics.composer3/current/android/hardware/graphics/composer3/LayerCommand.aidl
@@ -37,6 +37,7 @@
   long layer;
   @nullable android.hardware.graphics.common.Point cursorPosition;
   @nullable android.hardware.graphics.composer3.Buffer buffer;
+  @nullable android.hardware.graphics.composer3.Buffer bufferAhead;
   @nullable android.hardware.graphics.common.Rect[] damage;
   @nullable android.hardware.graphics.composer3.ParcelableBlendMode blendMode;
   @nullable android.hardware.graphics.composer3.Color color;
diff --git a/graphics/composer/aidl/android/hardware/graphics/composer3/BufferAheadResult.aidl b/graphics/composer/aidl/android/hardware/graphics/composer3/BufferAheadResult.aidl
new file mode 100644
index 0000000..7ca4578
--- /dev/null
+++ b/graphics/composer/aidl/android/hardware/graphics/composer3/BufferAheadResult.aidl
@@ -0,0 +1,46 @@
+/**
+ * Copyright (c) 2022, 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.
+ */
+
+package android.hardware.graphics.composer3;
+
+@VintfStability
+parcelable BufferAheadResult {
+    /**
+     * The display which this commands refers to.
+     * @see IComposer.createDisplay
+     */
+    long display;
+
+    @VintfStability
+    parcelable Layer {
+        /**
+         * The layer which this commands refers to.
+         * @see IComposer.createLayer
+         */
+        long layer;
+
+        /**
+         * Represents whether BufferAhead was presented as part of the last
+         * present or not.
+         */
+        boolean presented;
+    }
+
+    /**
+     * The layers which has BufferAheadResult populated.
+     */
+    Layer[] layers;
+}
diff --git a/graphics/composer/aidl/android/hardware/graphics/composer3/Capability.aidl b/graphics/composer/aidl/android/hardware/graphics/composer3/Capability.aidl
index ea619ae..77ad1e0 100644
--- a/graphics/composer/aidl/android/hardware/graphics/composer3/Capability.aidl
+++ b/graphics/composer/aidl/android/hardware/graphics/composer3/Capability.aidl
@@ -57,4 +57,9 @@
      * validateDisplay step is needed.
      */
     SKIP_VALIDATE = 4,
+    /**
+     * Specifies that a device is able to use the LayerCommand.bufferAhead
+     * when provided.
+     */
+    BUFFER_AHEAD = 5
 }
diff --git a/graphics/composer/aidl/android/hardware/graphics/composer3/CommandResultPayload.aidl b/graphics/composer/aidl/android/hardware/graphics/composer3/CommandResultPayload.aidl
index f2de68e..fd1e4cc 100644
--- a/graphics/composer/aidl/android/hardware/graphics/composer3/CommandResultPayload.aidl
+++ b/graphics/composer/aidl/android/hardware/graphics/composer3/CommandResultPayload.aidl
@@ -16,6 +16,7 @@
 
 package android.hardware.graphics.composer3;
 
+import android.hardware.graphics.composer3.BufferAheadResult;
 import android.hardware.graphics.composer3.ChangedCompositionTypes;
 import android.hardware.graphics.composer3.ClientTargetPropertyWithNits;
 import android.hardware.graphics.composer3.CommandError;
@@ -78,6 +79,13 @@
     ReleaseFences releaseFences;
 
     /**
+     * Represents the result of the LayerCommand.bufferAhead that was
+     * sent in the last presentDisplay call. That is, the presentDisplay
+     * call prior to this presentDisplay.
+     */
+    BufferAheadResult bufferAheadResult;
+
+    /**
      * Sets the state of PRESENT_OR_VALIDATE_DISPLAY command.
      */
     PresentOrValidate presentOrValidateResult;
diff --git a/graphics/composer/aidl/android/hardware/graphics/composer3/LayerCommand.aidl b/graphics/composer/aidl/android/hardware/graphics/composer3/LayerCommand.aidl
index 0a2711b..b7b45e2 100644
--- a/graphics/composer/aidl/android/hardware/graphics/composer3/LayerCommand.aidl
+++ b/graphics/composer/aidl/android/hardware/graphics/composer3/LayerCommand.aidl
@@ -79,6 +79,30 @@
     @nullable Buffer buffer;
 
     /**
+     * Sets a buffer handle to be displayed for this layer and a file descriptor
+     * referring to an acquire sync fence object, which must be signaled when it is
+     * safe to read from the given buffer.
+     *
+     * When bufferAhead is provided, the implementation should try to
+     * present it on the next scanout as long as its acquire sync fence
+     * is signaled by that time. Otherwise the bufferAhead should be dropped.
+     * This allows the client to set an
+     * unsignaled buffer on the layer without causing the entire display to miss
+     * an update if the buffer is not ready by the next scanout time.
+     *
+     * In case bufferAhead is dropped and LayerCommand.buffer is provided, LayerCommand.buffer
+     * should be used as the next layer buffer.
+     *
+     * The implementation is expected to populate the CommandResultPayload.bufferAheadResult
+     * with information about whether bufferAhead was presented or dropped.
+     * Since this information is not known at the current presentDisplay call
+     * of frame N (as the scanout happens after the call returns),
+     * the implementation should populate it when presentDisplay is
+     * called for frame N+1.
+     */
+    @nullable Buffer bufferAhead;
+
+    /**
      * Provides the region of the source buffer which has been modified since
      * the last frame. This region does not need to be validated before
      * calling presentDisplay.
diff --git a/graphics/composer/aidl/android/hardware/graphics/composer3/vts/functional/VtsHalGraphicsComposer3_TargetTest.cpp b/graphics/composer/aidl/android/hardware/graphics/composer3/vts/functional/VtsHalGraphicsComposer3_TargetTest.cpp
index 32a8ea8..026a431 100644
--- a/graphics/composer/aidl/android/hardware/graphics/composer3/vts/functional/VtsHalGraphicsComposer3_TargetTest.cpp
+++ b/graphics/composer/aidl/android/hardware/graphics/composer3/vts/functional/VtsHalGraphicsComposer3_TargetTest.cpp
@@ -1205,6 +1205,7 @@
         const auto errors = mReader.takeErrors();
         ASSERT_TRUE(mReader.takeErrors().empty());
         ASSERT_TRUE(mReader.takeChangedCompositionTypes(mPrimaryDisplay).empty());
+        ASSERT_TRUE(mReader.takeBufferAheadResultLayers(mPrimaryDisplay).empty());
 
         ASSERT_NO_FATAL_FAILURE(GraphicsComposerAidlTest::TearDown());
     }
diff --git a/graphics/composer/aidl/include/android/hardware/graphics/composer3/ComposerClientReader.h b/graphics/composer/aidl/include/android/hardware/graphics/composer3/ComposerClientReader.h
index f9e35e9..8f8c98f 100644
--- a/graphics/composer/aidl/include/android/hardware/graphics/composer3/ComposerClientReader.h
+++ b/graphics/composer/aidl/include/android/hardware/graphics/composer3/ComposerClientReader.h
@@ -77,6 +77,10 @@
                     parseSetClientTargetProperty(std::move(
                             result.get<CommandResultPayload::Tag::clientTargetProperty>()));
                     break;
+                case CommandResultPayload::Tag::bufferAheadResult:
+                    parseSetBufferAheadResultLayers(
+                            result.get<CommandResultPayload::Tag::bufferAheadResult>());
+                    break;
             }
         }
     }
@@ -168,6 +172,16 @@
         return std::move(data.clientTargetProperty);
     }
 
+    std::vector<BufferAheadResult::Layer> takeBufferAheadResultLayers(int64_t display) {
+        const auto found = mReturnData.find(display);
+
+        if (found == mReturnData.end()) {
+            return {};
+        }
+
+        return std::move(found->second.bufferAheadResultLayers);
+    }
+
   private:
     void resetData() {
         mErrors.clear();
@@ -206,12 +220,18 @@
         data.clientTargetProperty = std::move(clientTargetProperty);
     }
 
+    void parseSetBufferAheadResultLayers(const BufferAheadResult& bufferAheadResult) {
+        auto& data = mReturnData[bufferAheadResult.display];
+        data.bufferAheadResultLayers = std::move(bufferAheadResult.layers);
+    }
+
     struct ReturnData {
         DisplayRequest displayRequests;
         std::vector<ChangedCompositionLayer> changedLayers;
         ndk::ScopedFileDescriptor presentFence;
         std::vector<ReleaseFences::Layer> releasedLayers;
         PresentOrValidate::Result presentOrValidateState;
+        std::vector<BufferAheadResult::Layer> bufferAheadResultLayers;
 
         ClientTargetPropertyWithNits clientTargetProperty = {
                 .clientTargetProperty = {common::PixelFormat::RGBA_8888, Dataspace::UNKNOWN},
diff --git a/graphics/composer/aidl/include/android/hardware/graphics/composer3/ComposerClientWriter.h b/graphics/composer/aidl/include/android/hardware/graphics/composer3/ComposerClientWriter.h
index d3266e7..d429b76 100644
--- a/graphics/composer/aidl/include/android/hardware/graphics/composer3/ComposerClientWriter.h
+++ b/graphics/composer/aidl/include/android/hardware/graphics/composer3/ComposerClientWriter.h
@@ -131,6 +131,11 @@
         getLayerCommand(display, layer).buffer = getBuffer(slot, buffer, acquireFence);
     }
 
+    void setLayerBufferAhead(int64_t display, int64_t layer, uint32_t slot,
+                             const native_handle_t* buffer, int acquireFence) {
+        getLayerCommand(display, layer).bufferAhead = getBuffer(slot, buffer, acquireFence);
+    }
+
     void setLayerSurfaceDamage(int64_t display, int64_t layer, const std::vector<Rect>& damage) {
         getLayerCommand(display, layer).damage.emplace(damage.begin(), damage.end());
     }
diff --git a/identity/aidl/Android.bp b/identity/aidl/Android.bp
index dad3b8d..e3b8191 100644
--- a/identity/aidl/Android.bp
+++ b/identity/aidl/Android.bp
@@ -15,6 +15,7 @@
     ],
     imports: [
         "android.hardware.keymaster",
+        "android.hardware.security.keymint",
     ],
     stability: "vintf",
     backend: {
@@ -25,6 +26,7 @@
             vndk: {
                 enabled: true,
             },
+            apps_enabled: false,
         },
     },
     versions: [
diff --git a/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/HardwareInformation.aidl b/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/HardwareInformation.aidl
index cd8d56b..9b96ea8 100644
--- a/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/HardwareInformation.aidl
+++ b/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/HardwareInformation.aidl
@@ -39,4 +39,5 @@
   int dataChunkSize;
   boolean isDirectAccess;
   @utf8InCpp String[] supportedDocTypes;
+  boolean isRemoteKeyProvisioningSupported = false;
 }
diff --git a/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/IIdentityCredentialStore.aidl b/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/IIdentityCredentialStore.aidl
index c912c52..31ca8b1 100644
--- a/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/IIdentityCredentialStore.aidl
+++ b/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/IIdentityCredentialStore.aidl
@@ -38,6 +38,7 @@
   android.hardware.identity.IWritableIdentityCredential createCredential(in @utf8InCpp String docType, in boolean testCredential);
   android.hardware.identity.IIdentityCredential getCredential(in android.hardware.identity.CipherSuite cipherSuite, in byte[] credentialData);
   android.hardware.identity.IPresentationSession createPresentationSession(in android.hardware.identity.CipherSuite cipherSuite);
+  android.hardware.security.keymint.IRemotelyProvisionedComponent getRemotelyProvisionedComponent();
   const int STATUS_OK = 0;
   const int STATUS_FAILED = 1;
   const int STATUS_CIPHER_SUITE_NOT_SUPPORTED = 2;
diff --git a/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/IWritableIdentityCredential.aidl b/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/IWritableIdentityCredential.aidl
index 9a0fa9e..5377349 100644
--- a/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/IWritableIdentityCredential.aidl
+++ b/identity/aidl/aidl_api/android.hardware.identity/current/android/hardware/identity/IWritableIdentityCredential.aidl
@@ -41,4 +41,5 @@
   byte[] addEntryValue(in byte[] content);
   @SuppressWarnings(value={"out-array"}) void finishAddingEntries(out byte[] credentialData, out byte[] proofOfProvisioningSignature);
   void setExpectedProofOfProvisioningSize(in int expectedProofOfProvisioningSize);
+  void setRemotelyProvisionedAttestationKey(in byte[] attestationKeyBlob, in byte[] attestationCertificate);
 }
diff --git a/identity/aidl/android/hardware/identity/HardwareInformation.aidl b/identity/aidl/android/hardware/identity/HardwareInformation.aidl
index d67739d..acd13b6 100644
--- a/identity/aidl/android/hardware/identity/HardwareInformation.aidl
+++ b/identity/aidl/android/hardware/identity/HardwareInformation.aidl
@@ -51,4 +51,19 @@
      *
      */
     @utf8InCpp String[] supportedDocTypes;
+
+    /**
+     * isRemoteKeyProvisioningSupported indicates whether or not the underlying implementation
+     * supports a remotely provisioned key for attestation or not. If this field is false, then
+     * the implementation only uses a factory-installed, fixed attestation key. If this field is
+     * true, then an IRemotelyProvisionedComponent is associated with the IIdentityCredentialStore,
+     * and a remotely provisioned key blob may be provided for credential key attestation.
+     *
+     * Note that remote provisioning is not required, even when it is supported. Implementations
+     * MUST use a factory-installed attestation key as a fallback for when there are no
+     * remotely provisioned keys available. This behavior mirrors keystore key attestation.
+     *
+     * This field was added in API version 4.
+     */
+    boolean isRemoteKeyProvisioningSupported = false;
 }
diff --git a/identity/aidl/android/hardware/identity/IIdentityCredentialStore.aidl b/identity/aidl/android/hardware/identity/IIdentityCredentialStore.aidl
index 86be7f5..d3e4da0 100644
--- a/identity/aidl/android/hardware/identity/IIdentityCredentialStore.aidl
+++ b/identity/aidl/android/hardware/identity/IIdentityCredentialStore.aidl
@@ -21,6 +21,7 @@
 import android.hardware.identity.IIdentityCredential;
 import android.hardware.identity.IPresentationSession;
 import android.hardware.identity.IWritableIdentityCredential;
+import android.hardware.security.keymint.IRemotelyProvisionedComponent;
 
 /**
  * IIdentityCredentialStore provides an interface to a secure store for user identity documents.
@@ -215,16 +216,16 @@
      * @return an IWritableIdentityCredential interface that provides operations to
      *     provision a credential.
      */
-    IWritableIdentityCredential createCredential(in @utf8InCpp String docType,
-                                                 in boolean testCredential);
+    IWritableIdentityCredential createCredential(
+            in @utf8InCpp String docType, in boolean testCredential);
 
     /**
      * getCredential retrieves an IIdentityCredential interface which allows use of a stored
      * Credential.
      *
-     * The cipher suite used to communicate with the remote verifier must also be specified. Currently
-     * only a single cipher-suite is supported. Support for other cipher suites may be added in a
-     * future version of this HAL.
+     * The cipher suite used to communicate with the remote verifier must also be specified.
+     * Currently only a single cipher-suite is supported. Support for other cipher suites may be
+     * added in a future version of this HAL.
      *
      * This method fails with STATUS_INVALID_DATA if the passed in credentialData cannot be
      * decoded or decrypted.
@@ -263,4 +264,23 @@
      * @return an IPresentationSession interface.
      */
     IPresentationSession createPresentationSession(in CipherSuite cipherSuite);
+
+    /**
+     * Fetch the IRemotelyProvisionedComponent that is used to generate attestation keys for
+     * remote provisionining. Keys generated by this component are to be certified by a remote
+     * provisionined authority, then used to attest to credential keys via
+     * IWritableIdentityCredential.setRemotelyProvisionedAttestationKey.
+     *
+     * Support for this method is indicated by HardwareInformation. If the
+     * |isRemoteKeyProvisioningSupported| field is false, this method will fail with
+     * EX_UNSUPPORTED_OPERATION.
+     *
+     * This method was added in API version 4.
+     *
+     * @see
+     *         android.hardware.identity.IWritableIdentityCredential#setRemotelyProvisionedAttestationKey
+     *
+     * @return an IRemotelyProvisionedComponent that is used to generate attestation keys.
+     */
+    IRemotelyProvisionedComponent getRemotelyProvisionedComponent();
 }
diff --git a/identity/aidl/android/hardware/identity/IWritableIdentityCredential.aidl b/identity/aidl/android/hardware/identity/IWritableIdentityCredential.aidl
index 22bcf61..756b008 100644
--- a/identity/aidl/android/hardware/identity/IWritableIdentityCredential.aidl
+++ b/identity/aidl/android/hardware/identity/IWritableIdentityCredential.aidl
@@ -131,7 +131,8 @@
      *
      * @return the X.509 certificate chain for the credentialKey
      */
-    Certificate[] getAttestationCertificate(in byte[] attestationApplicationId, in byte[] attestationChallenge);
+    Certificate[] getAttestationCertificate(
+            in byte[] attestationApplicationId, in byte[] attestationChallenge);
 
     /**
      * Start the personalization process.
@@ -183,11 +184,11 @@
      *     in the secure environment. If this requirement is not met the call fails with
      *     STATUS_INVALID_DATA.
      *
-     * @return a structure with the passed-in data and MAC created with storageKey for authenticating
-     *     the data at a later point in time.
+     * @return a structure with the passed-in data and MAC created with storageKey for
+     *     authenticating the data at a later point in time.
      */
     SecureAccessControlProfile addAccessControlProfile(in int id, in Certificate readerCertificate,
-        in boolean userAuthenticationRequired, in long timeoutMillis, in long secureUserId);
+            in boolean userAuthenticationRequired, in long timeoutMillis, in long secureUserId);
 
     /**
      * Begins the process of adding an entry to the credential.  All access control profiles must be
@@ -209,7 +210,7 @@
      *     is not met this method fails with STATUS_INVALID_DATA.
      */
     void beginAddEntry(in int[] accessControlProfileIds, in @utf8InCpp String nameSpace,
-        in @utf8InCpp String name, in int entrySize);
+            in @utf8InCpp String name, in int entrySize);
 
     /**
      * Continues the process of adding an entry, providing a value or part of a value.
@@ -221,8 +222,8 @@
      * chunk sizes must equal the value of the beginAddEntry() entrySize argument. If this
      * requirement is not met the call fails with STATUS_INVALID_DATA.
      *
-     * @param content is the entry value, encoded as CBOR. In the case the content exceeds gcmChunkSize,
-     *     this may be partial content up to gcmChunkSize bytes long.
+     * @param content is the entry value, encoded as CBOR. In the case the content exceeds
+     *     gcmChunkSize, this may be partial content up to gcmChunkSize bytes long.
      *
      * @return the encrypted and MACed content.  For directly-available credentials the contents are
      *     implementation-defined. For other credentials, the result contains
@@ -321,8 +322,7 @@
      *          }
      */
     @SuppressWarnings(value={"out-array"})
-    void finishAddingEntries(out byte[] credentialData,
-        out byte[] proofOfProvisioningSignature);
+    void finishAddingEntries(out byte[] credentialData, out byte[] proofOfProvisioningSignature);
 
     /**
      * Sets the expected size of the ProofOfProvisioning returned by finishAddingEntries(). This
@@ -336,4 +336,35 @@
      */
     void setExpectedProofOfProvisioningSize(in int expectedProofOfProvisioningSize);
 
+    /**
+     * Sets the attestation key used to sign the credentialKey certificate. This method is used to
+     * support remotely provisioned attestation keys, removing the credential's dependency on any
+     * factory-provisioned attestation key.
+     *
+     * This method must be called before getAttestationCertificate. After this method is called,
+     * the certificate chain returned by getAttestationCertificate will contain a leaf certificate
+     * signed by attestationKeyBlob and the chain in attestationCertificate will make up the rest
+     * of the returned chain.
+     *
+     * Returns EX_UNSUPPORTED_FUNCTION if remote provisioning is not supported
+     * (see IIdentityCredentialStore.getHardwareInformation()).
+     *
+     * This method was added in API version 4.
+     *
+     * @param attestationKeyBlob is a key blob generated by the IRemotelyProvisionedComponent that
+     *     is returned by ICredentialStore.getRemotelyProvisionedComponent. The format is vendor-
+     *     specified, and matches the key blob returned by IKeyMintDevice.generateKey.
+     *
+     * @param attestationCertificate contains the X.509 certificate chain that certifies the
+     *     attestationKeyBlob. This certificate is expected to have been remotely provisioned
+     *     by a trusted authority. This parameter must contain a concatenated chain of DER-encoded
+     *     X.509 certificates. The certificates must be ordered such that the attestation key
+     *     certificate is first (starting at byte 0). The issuer certificate for the attestation
+     *     certificate immediately follows, continuing this chain to the final, root certificate.
+     *
+     * @see getAttestationCertificate
+     * @see android.hardware.identity.ICredentialStore#getRemotelyProvisionedComponent
+     */
+    void setRemotelyProvisionedAttestationKey(
+            in byte[] attestationKeyBlob, in byte[] attestationCertificate);
 }
diff --git a/identity/aidl/default/Android.bp b/identity/aidl/default/Android.bp
index ca24afa..32b3543 100644
--- a/identity/aidl/default/Android.bp
+++ b/identity/aidl/default/Android.bp
@@ -42,6 +42,7 @@
         "android.hardware.identity-support-lib",
         "android.hardware.identity-V4-ndk",
         "android.hardware.keymaster-V4-ndk",
+        "android.hardware.security.keymint-V2-ndk",
     ],
 }
 
@@ -81,6 +82,9 @@
     init_rc: ["identity-default.rc"],
     vintf_fragments: ["identity-default.xml"],
     vendor: true,
+    defaults: [
+        "keymint_use_latest_hal_aidl_ndk_static",
+    ],
     cflags: [
         "-Wall",
         "-Wextra",
diff --git a/identity/aidl/default/EicOpsImpl.cc b/identity/aidl/default/EicOpsImpl.cc
index c98a91e..3fd9f1d 100644
--- a/identity/aidl/default/EicOpsImpl.cc
+++ b/identity/aidl/default/EicOpsImpl.cc
@@ -267,25 +267,42 @@
 
 bool eicOpsCreateCredentialKey(uint8_t privateKey[EIC_P256_PRIV_KEY_SIZE], const uint8_t* challenge,
                                size_t challengeSize, const uint8_t* applicationId,
-                               size_t applicationIdSize, bool testCredential, uint8_t* cert,
-                               size_t* certSize) {
-    vector<uint8_t> challengeVec(challengeSize);
-    memcpy(challengeVec.data(), challenge, challengeSize);
-
-    vector<uint8_t> applicationIdVec(applicationIdSize);
-    memcpy(applicationIdVec.data(), applicationId, applicationIdSize);
-
-    optional<std::pair<vector<uint8_t>, vector<vector<uint8_t>>>> ret =
-            android::hardware::identity::support::createEcKeyPairAndAttestation(
-                    challengeVec, applicationIdVec, testCredential);
-    if (!ret) {
-        eicDebug("Error generating CredentialKey and attestation");
-        return false;
+                               size_t applicationIdSize, bool testCredential,
+                               const uint8_t* attestationKeyBlob, size_t attestationKeyBlobSize,
+                               const uint8_t* attestationKeyCert, size_t attestationKeyCertSize,
+                               uint8_t* cert, size_t* certSize) {
+    vector<uint8_t> flatChain;
+    vector<uint8_t> keyPair;
+    vector<uint8_t> challengeVec(challenge, challenge + challengeSize);
+    vector<uint8_t> applicationIdVec(applicationId, applicationId + applicationIdSize);
+    if (attestationKeyBlob && attestationKeyBlobSize > 0 && attestationKeyCert &&
+        attestationKeyCertSize > 0) {
+        vector<uint8_t> attestationKeyBlobVec(attestationKeyBlob,
+                                              attestationKeyBlob + attestationKeyBlobSize);
+        vector<uint8_t> attestationKeyCertVec(attestationKeyCert,
+                                              attestationKeyCert + attestationKeyCertSize);
+        optional<std::pair<vector<uint8_t>, vector<uint8_t>>> keyAndCert =
+                android::hardware::identity::support::createEcKeyPairWithAttestationKey(
+                        challengeVec, applicationIdVec, attestationKeyBlobVec,
+                        attestationKeyCertVec, testCredential);
+        if (!keyAndCert) {
+            eicDebug("Error generating CredentialKey and attestation");
+            return false;
+        }
+        keyPair = std::move(keyAndCert->first);
+        flatChain = std::move(keyAndCert->second);
+    } else {
+        optional<std::pair<vector<uint8_t>, vector<vector<uint8_t>>>> ret =
+                android::hardware::identity::support::createEcKeyPairAndAttestation(
+                        challengeVec, applicationIdVec, testCredential);
+        if (!ret) {
+            eicDebug("Error generating CredentialKey and attestation");
+            return false;
+        }
+        keyPair = std::move(ret->first);
+        flatChain = android::hardware::identity::support::certificateChainJoin(ret->second);
     }
 
-    // Extract certificate chain.
-    vector<uint8_t> flatChain =
-            android::hardware::identity::support::certificateChainJoin(ret.value().second);
     if (*certSize < flatChain.size()) {
         eicDebug("Buffer for certificate is only %zd bytes long, need %zd bytes", *certSize,
                  flatChain.size());
@@ -296,7 +313,7 @@
 
     // Extract private key.
     optional<vector<uint8_t>> privKey =
-            android::hardware::identity::support::ecKeyPairGetPrivateKey(ret.value().first);
+            android::hardware::identity::support::ecKeyPairGetPrivateKey(keyPair);
     if (!privKey) {
         eicDebug("Error extracting private key");
         return false;
@@ -520,10 +537,12 @@
 #ifdef EIC_DEBUG
 
 void eicPrint(const char* format, ...) {
+    char buf[1024];
     va_list args;
     va_start(args, format);
-    vfprintf(stderr, format, args);
+    vsnprintf(buf, sizeof(buf), format, args);
     va_end(args);
+    LOG(INFO) << buf;
 }
 
 void eicHexdump(const char* message, const uint8_t* data, size_t dataSize) {
diff --git a/identity/aidl/default/FakeSecureHardwareProxy.cpp b/identity/aidl/default/FakeSecureHardwareProxy.cpp
index 91e634c..9b9a749 100644
--- a/identity/aidl/default/FakeSecureHardwareProxy.cpp
+++ b/identity/aidl/default/FakeSecureHardwareProxy.cpp
@@ -155,7 +155,11 @@
     size_t publicKeyCertSize = sizeof publicKeyCert;
     if (!eicProvisioningCreateCredentialKey(&ctx_, challenge.data(), challenge.size(),
                                             applicationId.data(), applicationId.size(),
-                                            publicKeyCert, &publicKeyCertSize)) {
+                                            /*attestationKeyBlob=*/nullptr,
+                                            /*attestationKeyBlobSize=*/0,
+                                            /*attestationKeyCert=*/nullptr,
+                                            /*attestationKeyCertSize=*/0, publicKeyCert,
+                                            &publicKeyCertSize)) {
         return std::nullopt;
     }
     vector<uint8_t> pubKeyCert(publicKeyCertSize);
@@ -163,6 +167,23 @@
     return pubKeyCert;
 }
 
+optional<vector<uint8_t>> FakeSecureHardwareProvisioningProxy::createCredentialKeyUsingRkp(
+        const vector<uint8_t>& challenge, const vector<uint8_t>& applicationId,
+        const vector<uint8_t>& attestationKeyBlob, const vector<uint8_t>& attstationKeyCert) {
+    size_t publicKeyCertSize = 4096;
+    vector<uint8_t> publicKeyCert(publicKeyCertSize);
+    if (!eicProvisioningCreateCredentialKey(&ctx_, challenge.data(), challenge.size(),
+                                            applicationId.data(), applicationId.size(),
+                                            attestationKeyBlob.data(), attestationKeyBlob.size(),
+                                            attstationKeyCert.data(), attstationKeyCert.size(),
+                                            publicKeyCert.data(), &publicKeyCertSize)) {
+        LOG(ERROR) << "error creating credential key";
+        return std::nullopt;
+    }
+    publicKeyCert.resize(publicKeyCertSize);
+    return publicKeyCert;
+}
+
 bool FakeSecureHardwareProvisioningProxy::startPersonalization(
         int accessControlProfileCount, const vector<int>& entryCounts, const string& docType,
         size_t expectedProofOfProvisioningSize) {
diff --git a/identity/aidl/default/FakeSecureHardwareProxy.h b/identity/aidl/default/FakeSecureHardwareProxy.h
index df98c7a..2512074 100644
--- a/identity/aidl/default/FakeSecureHardwareProxy.h
+++ b/identity/aidl/default/FakeSecureHardwareProxy.h
@@ -43,6 +43,11 @@
     optional<vector<uint8_t>> createCredentialKey(const vector<uint8_t>& challenge,
                                                   const vector<uint8_t>& applicationId) override;
 
+    optional<vector<uint8_t>> createCredentialKeyUsingRkp(
+            const vector<uint8_t>& challenge, const vector<uint8_t>& applicationId,
+            const vector<uint8_t>& attestationKeyBlob,
+            const vector<uint8_t>& attestationKeyCert) override;
+
     bool startPersonalization(int accessControlProfileCount, const vector<int>& entryCounts,
                               const string& docType,
                               size_t expectedProofOfProvisioningSize) override;
diff --git a/identity/aidl/default/common/IdentityCredential.cpp b/identity/aidl/default/common/IdentityCredential.cpp
index 7678ecb..ff80752 100644
--- a/identity/aidl/default/common/IdentityCredential.cpp
+++ b/identity/aidl/default/common/IdentityCredential.cpp
@@ -1012,8 +1012,8 @@
                 IIdentityCredentialStore::STATUS_FAILED, "Error creating provisioning proxy"));
     }
     shared_ptr<WritableIdentityCredential> wc =
-            ndk::SharedRefBase::make<WritableIdentityCredential>(provisioningHwProxy, docType_,
-                                                                 testCredential_);
+            ndk::SharedRefBase::make<WritableIdentityCredential>(
+                    provisioningHwProxy, docType_, testCredential_, hardwareInformation_);
     if (!wc->initializeForUpdate(encryptedCredentialKeys_)) {
         return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(
                 IIdentityCredentialStore::STATUS_FAILED,
diff --git a/identity/aidl/default/common/IdentityCredential.h b/identity/aidl/default/common/IdentityCredential.h
index 2935fb8..5929829 100644
--- a/identity/aidl/default/common/IdentityCredential.h
+++ b/identity/aidl/default/common/IdentityCredential.h
@@ -48,11 +48,13 @@
   public:
     IdentityCredential(sp<SecureHardwareProxyFactory> hwProxyFactory,
                        const vector<uint8_t>& credentialData,
-                       std::shared_ptr<PresentationSession> session)
+                       std::shared_ptr<PresentationSession> session,
+                       HardwareInformation hardwareInformation)
         : hwProxyFactory_(hwProxyFactory),
           credentialData_(credentialData),
           session_(std::move(session)),
           numStartRetrievalCalls_(0),
+          hardwareInformation_(std::move(hardwareInformation)),
           expectedDeviceNameSpacesSize_(0) {}
 
     // Parses and decrypts credentialData_, return a status code from
@@ -103,6 +105,7 @@
     vector<uint8_t> credentialData_;
     shared_ptr<PresentationSession> session_;
     int numStartRetrievalCalls_;
+    HardwareInformation hardwareInformation_;
 
     // Set by initialize()
     string docType_;
diff --git a/identity/aidl/default/common/IdentityCredentialStore.cpp b/identity/aidl/default/common/IdentityCredentialStore.cpp
index 4703ffe..bbc2cef 100644
--- a/identity/aidl/default/common/IdentityCredentialStore.cpp
+++ b/identity/aidl/default/common/IdentityCredentialStore.cpp
@@ -17,6 +17,7 @@
 #define LOG_TAG "IdentityCredentialStore"
 
 #include <android-base/logging.h>
+#include <android/binder_manager.h>
 
 #include "IdentityCredential.h"
 #include "IdentityCredentialStore.h"
@@ -25,15 +26,24 @@
 
 namespace aidl::android::hardware::identity {
 
+using ::aidl::android::hardware::security::keymint::IRemotelyProvisionedComponent;
+
+IdentityCredentialStore::IdentityCredentialStore(sp<SecureHardwareProxyFactory> hwProxyFactory,
+                                                 optional<string> remotelyProvisionedComponent)
+    : hwProxyFactory_(hwProxyFactory),
+      remotelyProvisionedComponentName_(remotelyProvisionedComponent) {
+    hardwareInformation_.credentialStoreName = "Identity Credential Reference Implementation";
+    hardwareInformation_.credentialStoreAuthorName = "Google";
+    hardwareInformation_.dataChunkSize = kGcmChunkSize;
+    hardwareInformation_.isDirectAccess = false;
+    hardwareInformation_.supportedDocTypes = {};
+    hardwareInformation_.isRemoteKeyProvisioningSupported =
+            remotelyProvisionedComponentName_.has_value();
+}
+
 ndk::ScopedAStatus IdentityCredentialStore::getHardwareInformation(
         HardwareInformation* hardwareInformation) {
-    HardwareInformation hw;
-    hw.credentialStoreName = "Identity Credential Reference Implementation";
-    hw.credentialStoreAuthorName = "Google";
-    hw.dataChunkSize = kGcmChunkSize;
-    hw.isDirectAccess = false;
-    hw.supportedDocTypes = {};
-    *hardwareInformation = hw;
+    *hardwareInformation = hardwareInformation_;
     return ndk::ScopedAStatus::ok();
 }
 
@@ -42,7 +52,8 @@
         shared_ptr<IWritableIdentityCredential>* outWritableCredential) {
     sp<SecureHardwareProvisioningProxy> hwProxy = hwProxyFactory_->createProvisioningProxy();
     shared_ptr<WritableIdentityCredential> wc =
-            ndk::SharedRefBase::make<WritableIdentityCredential>(hwProxy, docType, testCredential);
+            ndk::SharedRefBase::make<WritableIdentityCredential>(hwProxy, docType, testCredential,
+                                                                 hardwareInformation_);
     if (!wc->initialize()) {
         return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(
                 IIdentityCredentialStore::STATUS_FAILED,
@@ -63,7 +74,7 @@
     }
 
     shared_ptr<IdentityCredential> credential = ndk::SharedRefBase::make<IdentityCredential>(
-            hwProxyFactory_, credentialData, nullptr /* session */);
+            hwProxyFactory_, credentialData, nullptr /* session */, hardwareInformation_);
     auto ret = credential->initialize();
     if (ret != IIdentityCredentialStore::STATUS_OK) {
         return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(
@@ -83,8 +94,8 @@
     }
 
     sp<SecureHardwareSessionProxy> hwProxy = hwProxyFactory_->createSessionProxy();
-    shared_ptr<PresentationSession> session =
-            ndk::SharedRefBase::make<PresentationSession>(hwProxyFactory_, hwProxy);
+    shared_ptr<PresentationSession> session = ndk::SharedRefBase::make<PresentationSession>(
+            hwProxyFactory_, hwProxy, hardwareInformation_);
     auto ret = session->initialize();
     if (ret != IIdentityCredentialStore::STATUS_OK) {
         return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(
@@ -94,4 +105,23 @@
     return ndk::ScopedAStatus::ok();
 }
 
+ndk::ScopedAStatus IdentityCredentialStore::getRemotelyProvisionedComponent(
+        shared_ptr<IRemotelyProvisionedComponent>* outRemotelyProvisionedComponent) {
+    if (!remotelyProvisionedComponentName_) {
+        return ndk::ScopedAStatus(AStatus_fromExceptionCodeWithMessage(
+                EX_UNSUPPORTED_OPERATION, "Remote key provisioning is not supported"));
+    }
+
+    ndk::SpAIBinder binder(
+            AServiceManager_waitForService(remotelyProvisionedComponentName_->c_str()));
+    if (binder.get() == nullptr) {
+        return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(
+                IIdentityCredentialStore::STATUS_FAILED,
+                "Unable to get remotely provisioned component"));
+    }
+
+    *outRemotelyProvisionedComponent = IRemotelyProvisionedComponent::fromBinder(binder);
+    return ndk::ScopedAStatus::ok();
+}
+
 }  // namespace aidl::android::hardware::identity
diff --git a/identity/aidl/default/common/IdentityCredentialStore.h b/identity/aidl/default/common/IdentityCredentialStore.h
index 77b894d..dd1261b 100644
--- a/identity/aidl/default/common/IdentityCredentialStore.h
+++ b/identity/aidl/default/common/IdentityCredentialStore.h
@@ -18,6 +18,7 @@
 #define ANDROID_HARDWARE_IDENTITY_IDENTITYCREDENTIALSTORE_H
 
 #include <aidl/android/hardware/identity/BnIdentityCredentialStore.h>
+#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
 
 #include "SecureHardwareProxy.h"
 
@@ -25,14 +26,18 @@
 
 using ::android::sp;
 using ::android::hardware::identity::SecureHardwareProxyFactory;
+using ::std::optional;
 using ::std::shared_ptr;
 using ::std::string;
 using ::std::vector;
 
 class IdentityCredentialStore : public BnIdentityCredentialStore {
   public:
-    IdentityCredentialStore(sp<SecureHardwareProxyFactory> hwProxyFactory)
-        : hwProxyFactory_(hwProxyFactory) {}
+    // If remote key provisioning is supported, pass the service name for the correct
+    // IRemotelyProvisionedComponent to the remotelyProvisionedComponent parameter. Else
+    // pass std::nullopt to indicate remote key provisioning is not supported.
+    IdentityCredentialStore(sp<SecureHardwareProxyFactory> hwProxyFactory,
+                            optional<string> remotelyProvisionedComponent);
 
     // The GCM chunk size used by this implementation is 64 KiB.
     static constexpr size_t kGcmChunkSize = 64 * 1024;
@@ -50,8 +55,14 @@
     ndk::ScopedAStatus createPresentationSession(
             CipherSuite cipherSuite, shared_ptr<IPresentationSession>* outSession) override;
 
+    ndk::ScopedAStatus getRemotelyProvisionedComponent(
+            shared_ptr<::aidl::android::hardware::security::keymint::IRemotelyProvisionedComponent>*
+                    outRemotelyProvisionedComponent) override;
+
   private:
     sp<SecureHardwareProxyFactory> hwProxyFactory_;
+    optional<string> remotelyProvisionedComponentName_;
+    HardwareInformation hardwareInformation_;
 };
 
 }  // namespace aidl::android::hardware::identity
diff --git a/identity/aidl/default/common/PresentationSession.cpp b/identity/aidl/default/common/PresentationSession.cpp
index fbd8972..2eb7f2e 100644
--- a/identity/aidl/default/common/PresentationSession.cpp
+++ b/identity/aidl/default/common/PresentationSession.cpp
@@ -122,8 +122,8 @@
 ndk::ScopedAStatus PresentationSession::getCredential(
         const vector<uint8_t>& credentialData, shared_ptr<IIdentityCredential>* outCredential) {
     shared_ptr<PresentationSession> p = ref<PresentationSession>();
-    shared_ptr<IdentityCredential> credential =
-            ndk::SharedRefBase::make<IdentityCredential>(hwProxyFactory_, credentialData, p);
+    shared_ptr<IdentityCredential> credential = ndk::SharedRefBase::make<IdentityCredential>(
+            hwProxyFactory_, credentialData, p, hardwareInformation_);
     int ret = credential->initialize();
     if (ret != IIdentityCredentialStore::STATUS_OK) {
         return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(
diff --git a/identity/aidl/default/common/PresentationSession.h b/identity/aidl/default/common/PresentationSession.h
index 76ca67b..4cb174a 100644
--- a/identity/aidl/default/common/PresentationSession.h
+++ b/identity/aidl/default/common/PresentationSession.h
@@ -38,8 +38,11 @@
 class PresentationSession : public BnPresentationSession {
   public:
     PresentationSession(sp<SecureHardwareProxyFactory> hwProxyFactory,
-                        sp<SecureHardwareSessionProxy> hwProxy)
-        : hwProxyFactory_(std::move(hwProxyFactory)), hwProxy_(std::move(hwProxy)) {}
+                        sp<SecureHardwareSessionProxy> hwProxy,
+                        HardwareInformation hardwareInformation)
+        : hwProxyFactory_(std::move(hwProxyFactory)),
+          hwProxy_(std::move(hwProxy)),
+          hardwareInformation_(std::move(hardwareInformation)) {}
 
     virtual ~PresentationSession();
 
@@ -65,6 +68,7 @@
     // Set by constructor
     sp<SecureHardwareProxyFactory> hwProxyFactory_;
     sp<SecureHardwareSessionProxy> hwProxy_;
+    HardwareInformation hardwareInformation_;
 
     // Set by initialize()
     uint64_t id_;
diff --git a/identity/aidl/default/common/SecureHardwareProxy.h b/identity/aidl/default/common/SecureHardwareProxy.h
index a580444..9f63ad8 100644
--- a/identity/aidl/default/common/SecureHardwareProxy.h
+++ b/identity/aidl/default/common/SecureHardwareProxy.h
@@ -82,6 +82,18 @@
     virtual optional<vector<uint8_t>> createCredentialKey(const vector<uint8_t>& challenge,
                                                           const vector<uint8_t>& applicationId) = 0;
 
+    // Returns public key certificate with a remotely provisioned attestation key.
+    //
+    // This returns a single certificate that is signed by the given |attestationKeyBlob|.
+    // The implementation of eicOpsCreateCredentialKey() on the TA side must coordinate
+    // with its corresponding keymint implementation to sign using the attestation key. The
+    // |attestationKeyCert| parameter is the certificates for |attestationKeyBlob|,
+    // formatted as concatenated, DER-encoded, X.509 certificates.
+    virtual optional<vector<uint8_t>> createCredentialKeyUsingRkp(
+            const vector<uint8_t>& challenge, const vector<uint8_t>& applicationId,
+            const vector<uint8_t>& attestationKeyBlob,
+            const vector<uint8_t>& attestationKeyCert) = 0;
+
     virtual bool startPersonalization(int accessControlProfileCount, const vector<int>& entryCounts,
                                       const string& docType,
                                       size_t expectedProofOfProvisioningSize) = 0;
diff --git a/identity/aidl/default/common/WritableIdentityCredential.cpp b/identity/aidl/default/common/WritableIdentityCredential.cpp
index 200ee61..e420a7b 100644
--- a/identity/aidl/default/common/WritableIdentityCredential.cpp
+++ b/identity/aidl/default/common/WritableIdentityCredential.cpp
@@ -79,8 +79,15 @@
                 IIdentityCredentialStore::STATUS_INVALID_DATA, "Challenge can not be empty"));
     }
 
-    optional<vector<uint8_t>> certChain =
-            hwProxy_->createCredentialKey(attestationChallenge, attestationApplicationId);
+    optional<vector<uint8_t>> certChain;
+    if (attestationKeyBlob_ && attestationCertificateChain_) {
+        certChain = hwProxy_->createCredentialKeyUsingRkp(
+                attestationChallenge, attestationApplicationId, *attestationKeyBlob_,
+                attestationCertificateChain_->at(0));
+    } else {
+        certChain = hwProxy_->createCredentialKey(attestationChallenge, attestationApplicationId);
+    }
+
     if (!certChain) {
         return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(
                 IIdentityCredentialStore::STATUS_FAILED,
@@ -95,8 +102,14 @@
     }
 
     *outCertificateChain = vector<Certificate>();
-    for (const vector<uint8_t>& cert : certs.value()) {
-        Certificate c = Certificate();
+    for (vector<uint8_t>& cert : certs.value()) {
+        Certificate c;
+        c.encodedCertificate = std::move(cert);
+        outCertificateChain->push_back(std::move(c));
+    }
+
+    for (const vector<uint8_t>& cert : *attestationCertificateChain_) {
+        Certificate c;
         c.encodedCertificate = cert;
         outCertificateChain->push_back(std::move(c));
     }
@@ -402,4 +415,36 @@
     return ndk::ScopedAStatus::ok();
 }
 
+ndk::ScopedAStatus WritableIdentityCredential::setRemotelyProvisionedAttestationKey(
+        const vector<uint8_t>& attestationKeyBlob,
+        const vector<uint8_t>& attestationCertificateChain) {
+    if (!hardwareInformation_.isRemoteKeyProvisioningSupported) {
+        return ndk::ScopedAStatus(AStatus_fromExceptionCodeWithMessage(
+                EX_UNSUPPORTED_OPERATION, "Remote key provisioning is not supported"));
+    }
+
+    if (attestationKeyBlob.empty() || attestationCertificateChain.empty()) {
+        return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(
+                IIdentityCredentialStore::STATUS_FAILED,
+                "Empty data passed to setRemotlyProvisionedAttestationKey"));
+    }
+
+    if (attestationKeyBlob_.has_value()) {
+        return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(
+                IIdentityCredentialStore::STATUS_FAILED, "Attestation key already set"));
+    }
+
+    optional<vector<vector<uint8_t>>> certs =
+            support::certificateChainSplit(attestationCertificateChain);
+    if (!certs) {
+        return ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(
+                IIdentityCredentialStore::STATUS_FAILED,
+                "Error splitting chain into separate certificates"));
+    }
+
+    attestationKeyBlob_ = attestationKeyBlob;
+    attestationCertificateChain_ = *certs;
+    return ndk::ScopedAStatus::ok();
+}
+
 }  // namespace aidl::android::hardware::identity
diff --git a/identity/aidl/default/common/WritableIdentityCredential.h b/identity/aidl/default/common/WritableIdentityCredential.h
index 36ad430..39d32c9 100644
--- a/identity/aidl/default/common/WritableIdentityCredential.h
+++ b/identity/aidl/default/common/WritableIdentityCredential.h
@@ -30,6 +30,7 @@
 
 using ::android::sp;
 using ::android::hardware::identity::SecureHardwareProvisioningProxy;
+using ::std::optional;
 using ::std::set;
 using ::std::string;
 using ::std::vector;
@@ -41,8 +42,11 @@
     // For an updated credential, call initializeForUpdate() right after construction.
     //
     WritableIdentityCredential(sp<SecureHardwareProvisioningProxy> hwProxy, const string& docType,
-                               bool testCredential)
-        : hwProxy_(hwProxy), docType_(docType), testCredential_(testCredential) {}
+                               bool testCredential, HardwareInformation hardwareInformation)
+        : hwProxy_(hwProxy),
+          docType_(docType),
+          testCredential_(testCredential),
+          hardwareInformation_(std::move(hardwareInformation)) {}
 
     ~WritableIdentityCredential();
 
@@ -78,11 +82,16 @@
             vector<uint8_t>* outCredentialData,
             vector<uint8_t>* outProofOfProvisioningSignature) override;
 
+    ndk::ScopedAStatus setRemotelyProvisionedAttestationKey(
+            const vector<uint8_t>& attestationKeyBlob,
+            const vector<uint8_t>& attestationCertificateChain) override;
+
   private:
     // Set by constructor.
     sp<SecureHardwareProvisioningProxy> hwProxy_;
     string docType_;
     bool testCredential_;
+    HardwareInformation hardwareInformation_;
 
     // This is set in initialize().
     bool startPersonalizationCalled_;
@@ -109,6 +118,10 @@
     vector<int32_t> entryAccessControlProfileIds_;
     vector<uint8_t> entryBytes_;
     set<string> allNameSpaces_;
+
+    // Remotely provisioned attestation data, set via setRemotelyProvisionedAttestationKey
+    optional<vector<uint8_t>> attestationKeyBlob_;
+    optional<vector<vector<uint8_t>>> attestationCertificateChain_;
 };
 
 }  // namespace aidl::android::hardware::identity
diff --git a/identity/aidl/default/libeic/EicOps.h b/identity/aidl/default/libeic/EicOps.h
index aa26e62..df96c7d 100644
--- a/identity/aidl/default/libeic/EicOps.h
+++ b/identity/aidl/default/libeic/EicOps.h
@@ -196,13 +196,19 @@
 
 // Generates CredentialKey plus an attestation certificate.
 //
-// The attestation certificate will be signed by the attestation keys the secure
-// area has been provisioned with. The given |challenge| and |applicationId|
-// will be used as will |testCredential|.
+// If |attestationKeyBlob| is non-NULL, the certificate must be signed by the
+// the provided attestation key. Else, the certificate must be signed by the
+// attestation key that the secure area has been factory provisioned with. The
+// given |challenge|, |applicationId|, and |testCredential| must be signed
+// into the attestation.
 //
-// The generated certificate will be in X.509 format and returned in |cert|
-// and |certSize| must be set to the size of this array and this function will
-// set it to the size of the certification chain on successfully return.
+// When |attestationKeyBlob| is non-NULL, then |attestationKeyCert| must
+// also be passed so that the underlying implementation can properly chain up
+// the newly-generated certificate to the existing chain.
+//
+// The generated certificate must be in X.509 format and returned in |cert|
+// and |certSize| must be set to the size of this array. This function must
+// set |certSize| to the size of the certification chain on successfully return.
 //
 // This may return either a single certificate or an entire certificate
 // chain. If it returns only a single certificate, the implementation of
@@ -211,8 +217,10 @@
 //
 bool eicOpsCreateCredentialKey(uint8_t privateKey[EIC_P256_PRIV_KEY_SIZE], const uint8_t* challenge,
                                size_t challengeSize, const uint8_t* applicationId,
-                               size_t applicationIdSize, bool testCredential, uint8_t* cert,
-                               size_t* certSize);  // inout
+                               size_t applicationIdSize, bool testCredential,
+                               const uint8_t* attestationKeyBlob, size_t attestationKeyBlobSize,
+                               const uint8_t* attestationKeyCert, size_t attestationKeyCertSize,
+                               uint8_t* /*out*/ cert, size_t* /*inout*/ certSize);
 
 // Generate an X.509 certificate for the key identified by |publicKey| which
 // must be of the form returned by eicOpsCreateEcKey().
diff --git a/identity/aidl/default/libeic/EicProvisioning.c b/identity/aidl/default/libeic/EicProvisioning.c
index a241b71..ff009dd 100644
--- a/identity/aidl/default/libeic/EicProvisioning.c
+++ b/identity/aidl/default/libeic/EicProvisioning.c
@@ -133,7 +133,10 @@
 
 bool eicProvisioningCreateCredentialKey(EicProvisioning* ctx, const uint8_t* challenge,
                                         size_t challengeSize, const uint8_t* applicationId,
-                                        size_t applicationIdSize, uint8_t* publicKeyCert,
+                                        size_t applicationIdSize, const uint8_t* attestationKeyBlob,
+                                        size_t attestationKeyBlobSize,
+                                        const uint8_t* attestationKeyCert,
+                                        size_t attestationKeyCertSize, uint8_t* publicKeyCert,
                                         size_t* publicKeyCertSize) {
     if (ctx->isUpdate) {
         eicDebug("Cannot create CredentialKey on update");
@@ -142,7 +145,9 @@
 
     if (!eicOpsCreateCredentialKey(ctx->credentialPrivateKey, challenge, challengeSize,
                                    applicationId, applicationIdSize, ctx->testCredential,
-                                   publicKeyCert, publicKeyCertSize)) {
+                                   attestationKeyBlob, attestationKeyBlobSize, attestationKeyCert,
+                                   attestationKeyCertSize, publicKeyCert, publicKeyCertSize)) {
+        eicDebug("Error creating credential key");
         return false;
     }
     return true;
diff --git a/identity/aidl/default/libeic/EicProvisioning.h b/identity/aidl/default/libeic/EicProvisioning.h
index d94f8f1..2619bfc 100644
--- a/identity/aidl/default/libeic/EicProvisioning.h
+++ b/identity/aidl/default/libeic/EicProvisioning.h
@@ -77,7 +77,10 @@
 
 bool eicProvisioningCreateCredentialKey(EicProvisioning* ctx, const uint8_t* challenge,
                                         size_t challengeSize, const uint8_t* applicationId,
-                                        size_t applicationIdSize, uint8_t* publicKeyCert,
+                                        size_t applicationIdSize, const uint8_t* attestationKeyBlob,
+                                        size_t attestationKeyBlobSize,
+                                        const uint8_t* attestationKeyCert,
+                                        size_t attestationKeyCertSize, uint8_t* publicKeyCert,
                                         size_t* publicKeyCertSize);
 
 bool eicProvisioningStartPersonalization(EicProvisioning* ctx, int accessControlProfileCount,
diff --git a/identity/aidl/default/service.cpp b/identity/aidl/default/service.cpp
index 78f4fbc..ed3c4cb 100644
--- a/identity/aidl/default/service.cpp
+++ b/identity/aidl/default/service.cpp
@@ -16,6 +16,7 @@
 
 #define LOG_TAG "android.hardware.identity-service"
 
+#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
 #include <android-base/logging.h>
 #include <android/binder_manager.h>
 #include <android/binder_process.h>
@@ -26,20 +27,35 @@
 
 using ::android::sp;
 using ::android::base::InitLogging;
+using ::android::base::LogdLogger;
+using ::android::base::LogId;
+using ::android::base::LogSeverity;
 using ::android::base::StderrLogger;
 
 using ::aidl::android::hardware::identity::IdentityCredentialStore;
+using ::aidl::android::hardware::security::keymint::IRemotelyProvisionedComponent;
 using ::android::hardware::identity::FakeSecureHardwareProxyFactory;
 using ::android::hardware::identity::SecureHardwareProxyFactory;
 
+void ComboLogger(LogId id, LogSeverity severity, const char* tag, const char* file,
+                 unsigned int line, const char* message) {
+    StderrLogger(id, severity, tag, file, line, message);
+
+    static LogdLogger logdLogger;
+    logdLogger(id, severity, tag, file, line, message);
+}
+
 int main(int /*argc*/, char* argv[]) {
-    InitLogging(argv, StderrLogger);
+    InitLogging(argv, ComboLogger);
 
     sp<SecureHardwareProxyFactory> hwProxyFactory = new FakeSecureHardwareProxyFactory();
+    const std::string remotelyProvisionedComponentName =
+            std::string(IRemotelyProvisionedComponent::descriptor) + "/default";
 
     ABinderProcess_setThreadPoolMaxThreadCount(0);
     std::shared_ptr<IdentityCredentialStore> store =
-            ndk::SharedRefBase::make<IdentityCredentialStore>(hwProxyFactory);
+            ndk::SharedRefBase::make<IdentityCredentialStore>(hwProxyFactory,
+                                                              remotelyProvisionedComponentName);
 
     const std::string instance = std::string() + IdentityCredentialStore::descriptor + "/default";
     binder_status_t status = AServiceManager_addService(store->asBinder().get(), instance.c_str());
diff --git a/identity/aidl/vts/Android.bp b/identity/aidl/vts/Android.bp
index 7b6f2c8..c5b84a1 100644
--- a/identity/aidl/vts/Android.bp
+++ b/identity/aidl/vts/Android.bp
@@ -11,6 +11,8 @@
     name: "VtsHalIdentityTargetTest",
     defaults: [
         "VtsHalTargetTestDefaults",
+        "keymint_use_latest_hal_aidl_cpp_static",
+        "keymint_use_latest_hal_aidl_ndk_static",
         "use_libaidlvintf_gtest_helper_static",
     ],
     cflags: [
@@ -32,12 +34,15 @@
     ],
     shared_libs: [
         "libbinder",
+        "libbinder_ndk",
         "libcrypto",
     ],
     static_libs: [
+        "android.hardware.security.secureclock-V1-ndk",
         "libcppbor_external",
         "libcppcose_rkp",
         "libkeymaster_portable",
+        "libkeymint_vts_test_utils",
         "libpuresoftkeymasterdevice",
         "android.hardware.keymaster@4.0",
         "android.hardware.identity-support-lib",
@@ -46,6 +51,7 @@
         "android.hardware.keymaster-V4-ndk",
         "libkeymaster4support",
         "libkeymaster4_1support",
+        "libkeymint_remote_prov_support",
     ],
     test_suites: [
         "general-tests",
diff --git a/identity/aidl/vts/Util.cpp b/identity/aidl/vts/Util.cpp
index 1148cb0..f3d7c30 100644
--- a/identity/aidl/vts/Util.cpp
+++ b/identity/aidl/vts/Util.cpp
@@ -20,12 +20,16 @@
 
 #include <android-base/logging.h>
 
+#include <KeyMintAidlTestBase.h>
 #include <aidl/Gtest.h>
+#include <aidl/android/hardware/security/keymint/MacedPublicKey.h>
 #include <android-base/stringprintf.h>
 #include <keymaster/km_openssl/openssl_utils.h>
 #include <keymasterV4_1/attestation_record.h>
-#include <charconv>
+#include <keymint_support/openssl_utils.h>
+#include <openssl/evp.h>
 
+#include <charconv>
 #include <map>
 
 namespace android::hardware::identity::test_utils {
@@ -36,10 +40,13 @@
 using std::string;
 using std::vector;
 
+using ::aidl::android::hardware::security::keymint::test::check_maced_pubkey;
+using ::aidl::android::hardware::security::keymint::test::p256_pub_key;
 using ::android::sp;
 using ::android::String16;
 using ::android::base::StringPrintf;
 using ::android::binder::Status;
+using ::android::hardware::security::keymint::MacedPublicKey;
 using ::keymaster::X509_Ptr;
 
 bool setupWritableCredential(sp<IWritableIdentityCredential>& writableCredential,
@@ -58,6 +65,77 @@
     }
 }
 
+optional<vector<vector<uint8_t>>> createFakeRemotelyProvisionedCertificateChain(
+        const MacedPublicKey& macedPublicKey) {
+    // The helper library uses the NDK symbols, so play a little trickery here to convert
+    // the data into the proper type so we can reuse the helper function to get the pubkey.
+    ::aidl::android::hardware::security::keymint::MacedPublicKey ndkMacedPublicKey;
+    ndkMacedPublicKey.macedKey = macedPublicKey.macedKey;
+
+    vector<uint8_t> publicKeyBits;
+    check_maced_pubkey(ndkMacedPublicKey, /*testMode=*/true, &publicKeyBits);
+
+    ::aidl::android::hardware::security::keymint::EVP_PKEY_Ptr publicKey;
+    p256_pub_key(publicKeyBits, &publicKey);
+
+    // Generate an arbitrary root key for our chain
+    bssl::UniquePtr<EC_KEY> ecRootKey(EC_KEY_new());
+    bssl::UniquePtr<EVP_PKEY> rootKey(EVP_PKEY_new());
+    if (ecRootKey.get() == nullptr || rootKey.get() == nullptr) {
+        LOG(ERROR) << "Memory allocation failed";
+        return {};
+    }
+
+    bssl::UniquePtr<EC_GROUP> group(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
+    if (group.get() == nullptr) {
+        LOG(ERROR) << "Error creating EC group by curve name";
+        return {};
+    }
+
+    if (EC_KEY_set_group(ecRootKey.get(), group.get()) != 1 ||
+        EC_KEY_generate_key(ecRootKey.get()) != 1 || EC_KEY_check_key(ecRootKey.get()) < 0) {
+        LOG(ERROR) << "Error generating key";
+        return {};
+    }
+
+    if (EVP_PKEY_set1_EC_KEY(rootKey.get(), ecRootKey.get()) != 1) {
+        LOG(ERROR) << "Error getting private key";
+        return {};
+    }
+
+    // The VTS test does not fully validate the chain, so we're ok without the proper CA extensions.
+    map<string, vector<uint8_t>> extensions;
+
+    // Now make a self-signed cert
+    optional<vector<uint8_t>> root = support::ecPublicKeyGenerateCertificate(
+            rootKey.get(), rootKey.get(),
+            /*serialDecimal=*/"31415",
+            /*subject=*/"Android IdentityCredential VTS Test Root Certificate",
+            /*subject=*/"Android IdentityCredential VTS Test Root Certificate",
+            /*validityNotBefore=*/time(nullptr),
+            /*validityNotAfter=*/time(nullptr) + 365 * 24 * 3600, extensions);
+    if (!root) {
+        LOG(ERROR) << "Error generating root cert";
+        return std::nullopt;
+    }
+
+    // Now sign a CA cert so that we have a chain that's good enough to satisfy
+    // the VTS tests.
+    optional<vector<uint8_t>> intermediate = support::ecPublicKeyGenerateCertificate(
+            publicKey.get(), rootKey.get(),
+            /*serialDecimal=*/"42",
+            /*subject=*/"Android IdentityCredential VTS Test Root Certificate",
+            /*subject=*/"Android IdentityCredential VTS Test Attestation Certificate",
+            /*validityNotBefore=*/time(nullptr),
+            /*validityNotAfter=*/time(nullptr) + 365 * 24 * 3600, extensions);
+    if (!intermediate) {
+        LOG(ERROR) << "Error generating intermediate cert";
+        return std::nullopt;
+    }
+
+    return vector<vector<uint8_t>>{std::move(*intermediate), std::move(*root)};
+}
+
 optional<vector<uint8_t>> generateReaderCertificate(string serialDecimal) {
     vector<uint8_t> privKey;
     return generateReaderCertificate(serialDecimal, &privKey);
diff --git a/identity/aidl/vts/Util.h b/identity/aidl/vts/Util.h
index 80e52a2..b120dc9 100644
--- a/identity/aidl/vts/Util.h
+++ b/identity/aidl/vts/Util.h
@@ -19,6 +19,7 @@
 
 #include <android/hardware/identity/IIdentityCredentialStore.h>
 #include <android/hardware/identity/support/IdentityCredentialSupport.h>
+#include <android/hardware/security/keymint/MacedPublicKey.h>
 #include <cppbor.h>
 #include <cppbor_parse.h>
 #include <gtest/gtest.h>
@@ -97,6 +98,9 @@
 bool setupWritableCredential(sp<IWritableIdentityCredential>& writableCredential,
                              sp<IIdentityCredentialStore>& credentialStore, bool testCredential);
 
+optional<vector<vector<uint8_t>>> createFakeRemotelyProvisionedCertificateChain(
+        const ::android::hardware::security::keymint::MacedPublicKey& macedPublicKey);
+
 optional<vector<uint8_t>> generateReaderCertificate(string serialDecimal);
 
 optional<vector<uint8_t>> generateReaderCertificate(string serialDecimal,
diff --git a/identity/aidl/vts/VtsIWritableIdentityCredentialTests.cpp b/identity/aidl/vts/VtsIWritableIdentityCredentialTests.cpp
index bc37020..94d4c88 100644
--- a/identity/aidl/vts/VtsIWritableIdentityCredentialTests.cpp
+++ b/identity/aidl/vts/VtsIWritableIdentityCredentialTests.cpp
@@ -18,6 +18,8 @@
 
 #include <aidl/Gtest.h>
 #include <aidl/Vintf.h>
+#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
+#include <aidl/android/hardware/security/keymint/MacedPublicKey.h>
 #include <android-base/logging.h>
 #include <android/hardware/identity/IIdentityCredentialStore.h>
 #include <android/hardware/identity/support/IdentityCredentialSupport.h>
@@ -42,6 +44,8 @@
 using ::android::sp;
 using ::android::String16;
 using ::android::binder::Status;
+using ::android::hardware::security::keymint::IRemotelyProvisionedComponent;
+using ::android::hardware::security::keymint::MacedPublicKey;
 
 class IdentityCredentialTests : public testing::TestWithParam<string> {
   public:
@@ -101,6 +105,103 @@
                                                attestationApplicationId, false);
 }
 
+TEST_P(IdentityCredentialTests, verifyAttestationSuccessWithRemoteProvisioning) {
+    HardwareInformation hwInfo;
+    ASSERT_TRUE(credentialStore_->getHardwareInformation(&hwInfo).isOk());
+
+    if (!hwInfo.isRemoteKeyProvisioningSupported) {
+        GTEST_SKIP() << "Remote provisioning is not supported";
+    }
+
+    Status result;
+
+    sp<IWritableIdentityCredential> writableCredential;
+    ASSERT_TRUE(test_utils::setupWritableCredential(writableCredential, credentialStore_,
+                                                    false /* testCredential */));
+
+    sp<IRemotelyProvisionedComponent> rpc;
+    result = credentialStore_->getRemotelyProvisionedComponent(&rpc);
+    ASSERT_TRUE(result.isOk()) << result.exceptionCode() << "; " << result.exceptionMessage();
+
+    MacedPublicKey macedPublicKey;
+    std::vector<uint8_t> attestationKey;
+    result = rpc->generateEcdsaP256KeyPair(/*testMode=*/true, &macedPublicKey, &attestationKey);
+    ASSERT_TRUE(result.isOk()) << result.exceptionCode() << "; " << result.exceptionMessage();
+
+    optional<vector<vector<uint8_t>>> remotelyProvisionedCertChain =
+            test_utils::createFakeRemotelyProvisionedCertificateChain(macedPublicKey);
+    ASSERT_TRUE(remotelyProvisionedCertChain);
+
+    vector<uint8_t> concatenatedCerts;
+    for (const vector<uint8_t>& cert : *remotelyProvisionedCertChain) {
+        concatenatedCerts.insert(concatenatedCerts.end(), cert.begin(), cert.end());
+    }
+    result = writableCredential->setRemotelyProvisionedAttestationKey(attestationKey,
+                                                                      concatenatedCerts);
+    ASSERT_TRUE(result.isOk()) << result.exceptionCode() << "; " << result.exceptionMessage();
+
+    string challenge = "NotSoRandomChallenge1NotSoRandomChallenge1NotSoRandomChallenge1";
+    vector<uint8_t> attestationChallenge(challenge.begin(), challenge.end());
+    vector<Certificate> attestationCertificate;
+    vector<uint8_t> attestationApplicationId = {1};
+
+    result = writableCredential->getAttestationCertificate(
+            attestationApplicationId, attestationChallenge, &attestationCertificate);
+
+    ASSERT_TRUE(result.isOk()) << result.exceptionCode() << "; " << result.exceptionMessage();
+
+    test_utils::validateAttestationCertificate(attestationCertificate, attestationChallenge,
+                                               attestationApplicationId, false);
+
+    ASSERT_EQ(remotelyProvisionedCertChain->size() + 1, attestationCertificate.size());
+    for (size_t i = 0; i < remotelyProvisionedCertChain->size(); ++i) {
+        ASSERT_EQ(remotelyProvisionedCertChain->at(i),
+                  attestationCertificate[i + 1].encodedCertificate)
+                << "Certificate mismatch (cert index " << i + 1 << " out of "
+                << attestationCertificate.size() << " total certs)";
+    }
+}
+
+TEST_P(IdentityCredentialTests, verifyRemotelyProvisionedKeyMayOnlyBeSetOnce) {
+    HardwareInformation hwInfo;
+    ASSERT_TRUE(credentialStore_->getHardwareInformation(&hwInfo).isOk());
+
+    if (!hwInfo.isRemoteKeyProvisioningSupported) {
+        GTEST_SKIP() << "Remote provisioning is not supported";
+    }
+
+    sp<IRemotelyProvisionedComponent> rpc;
+    Status result = credentialStore_->getRemotelyProvisionedComponent(&rpc);
+    ASSERT_TRUE(result.isOk()) << result.exceptionCode() << "; " << result.exceptionMessage();
+
+    MacedPublicKey macedPublicKey;
+    std::vector<uint8_t> attestationKey;
+    result = rpc->generateEcdsaP256KeyPair(/*testMode=*/true, &macedPublicKey, &attestationKey);
+    ASSERT_TRUE(result.isOk()) << result.exceptionCode() << "; " << result.exceptionMessage();
+
+    optional<vector<vector<uint8_t>>> remotelyProvisionedCertChain =
+            test_utils::createFakeRemotelyProvisionedCertificateChain(macedPublicKey);
+    ASSERT_TRUE(remotelyProvisionedCertChain);
+
+    vector<uint8_t> concatenatedCerts;
+    for (const vector<uint8_t>& cert : *remotelyProvisionedCertChain) {
+        concatenatedCerts.insert(concatenatedCerts.end(), cert.begin(), cert.end());
+    }
+
+    sp<IWritableIdentityCredential> writableCredential;
+    ASSERT_TRUE(test_utils::setupWritableCredential(writableCredential, credentialStore_,
+                                                    /*testCredential=*/false));
+
+    result = writableCredential->setRemotelyProvisionedAttestationKey(attestationKey,
+                                                                      concatenatedCerts);
+    ASSERT_TRUE(result.isOk()) << result.exceptionCode() << "; " << result.exceptionMessage();
+
+    // Now try again, and verify that the implementation rejects it.
+    result = writableCredential->setRemotelyProvisionedAttestationKey(attestationKey,
+                                                                      concatenatedCerts);
+    EXPECT_FALSE(result.isOk());
+}
+
 TEST_P(IdentityCredentialTests, verifyAttestationDoubleCallFails) {
     Status result;
 
diff --git a/identity/support/include/android/hardware/identity/support/IdentityCredentialSupport.h b/identity/support/include/android/hardware/identity/support/IdentityCredentialSupport.h
index 3b91de6..82746d6 100644
--- a/identity/support/include/android/hardware/identity/support/IdentityCredentialSupport.h
+++ b/identity/support/include/android/hardware/identity/support/IdentityCredentialSupport.h
@@ -17,6 +17,8 @@
 #ifndef IDENTITY_SUPPORT_INCLUDE_IDENTITY_CREDENTIAL_UTILS_H_
 #define IDENTITY_SUPPORT_INCLUDE_IDENTITY_CREDENTIAL_UTILS_H_
 
+#include <openssl/evp.h>
+
 #include <cstdint>
 #include <map>
 #include <optional>
@@ -128,6 +130,15 @@
         const vector<uint8_t>& challenge, const vector<uint8_t>& applicationId,
         bool isTestCredential);
 
+// Alternate version of createEcKeyPairAndAttestation that accepts an attestation key
+// blob to sign the generated key. Only a single certificate is returned, rather than
+// a full chain.
+//
+optional<std::pair<vector<uint8_t>, vector<uint8_t>>> createEcKeyPairWithAttestationKey(
+        const vector<uint8_t>& challenge, const vector<uint8_t>& applicationId,
+        const vector<uint8_t>& attestationKeyBlob, const vector<uint8_t>& attestationKeyCert,
+        bool isTestCredential);
+
 // (TODO: remove when no longer used by 3rd party.)
 optional<vector<vector<uint8_t>>> createAttestationForEcPublicKey(
         const vector<uint8_t>& publicKey, const vector<uint8_t>& challenge,
@@ -240,6 +251,13 @@
         time_t validityNotBefore, time_t validityNotAfter,
         const map<string, vector<uint8_t>>& extensions);
 
+// Identical behavior to the above version of ecPublicKeyGenerateCertificate, except this
+// overload takes OpenSSL key parameters instead of key bitstrings as inputs.
+optional<vector<uint8_t>> ecPublicKeyGenerateCertificate(
+        EVP_PKEY* publicKey, EVP_PKEY* signingKey, const string& serialDecimal,
+        const string& issuer, const string& subject, time_t validityNotBefore,
+        time_t validityNotAfter, const map<string, vector<uint8_t>>& extensions);
+
 // Performs Elliptic-curve Diffie-Helman using |publicKey| (which must be in the
 // format returned by ecKeyPairGetPublicKey()) and |privateKey| (which must be
 // in the format returned by ecKeyPairGetPrivateKey()).
diff --git a/identity/support/src/IdentityCredentialSupport.cpp b/identity/support/src/IdentityCredentialSupport.cpp
index 7f4674d..36ecdb0 100644
--- a/identity/support/src/IdentityCredentialSupport.cpp
+++ b/identity/support/src/IdentityCredentialSupport.cpp
@@ -54,6 +54,7 @@
 #include <keymaster/contexts/pure_soft_keymaster_context.h>
 #include <keymaster/contexts/soft_attestation_cert.h>
 #include <keymaster/keymaster_tags.h>
+#include <keymaster/km_openssl/asymmetric_key.h>
 #include <keymaster/km_openssl/attestation_utils.h>
 #include <keymaster/km_openssl/certificate_utils.h>
 
@@ -168,6 +169,286 @@
 using X509_NAME_Ptr = bssl::UniquePtr<X509_NAME>;
 using X509_EXTENSION_Ptr = bssl::UniquePtr<X509_EXTENSION>;
 
+namespace {
+
+EVP_PKEY_Ptr generateP256Key() {
+    EC_KEY_Ptr ec_key(EC_KEY_new());
+    EVP_PKEY_Ptr pkey(EVP_PKEY_new());
+    EC_GROUP_Ptr group(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
+
+    if (ec_key.get() == nullptr || pkey.get() == nullptr) {
+        LOG(ERROR) << "Memory allocation failed";
+        return {};
+    }
+
+    if (EC_KEY_set_group(ec_key.get(), group.get()) != 1 ||
+        EC_KEY_generate_key(ec_key.get()) != 1 || EC_KEY_check_key(ec_key.get()) < 0) {
+        LOG(ERROR) << "Error generating key";
+        return {};
+    }
+
+    if (EVP_PKEY_set1_EC_KEY(pkey.get(), ec_key.get()) != 1) {
+        LOG(ERROR) << "Error getting private key";
+        return {};
+    }
+
+    return pkey;
+}
+
+optional<vector<uint8_t>> derEncodeKeyPair(const EVP_PKEY& pkey) {
+    int size = i2d_PrivateKey(&pkey, nullptr);
+    if (size == 0) {
+        LOG(ERROR) << "Error generating public key encoding";
+        return std::nullopt;
+    }
+
+    vector<uint8_t> keyPair(size);
+    unsigned char* p = keyPair.data();
+    i2d_PrivateKey(&pkey, &p);
+
+    return keyPair;
+}
+
+// Extract the issuer subject name from the leaf cert in the given chain,
+// returning it as DER-encoded bytes.
+optional<vector<uint8_t>> extractDerSubjectFromCertificate(const vector<uint8_t>& certificate) {
+    const uint8_t* input = certificate.data();
+    X509_Ptr cert(d2i_X509(/*cert=*/nullptr, &input, certificate.size()));
+    if (!cert) {
+        LOG(ERROR) << "Failed to parse certificate";
+        return std::nullopt;
+    }
+
+    X509_NAME* subject = X509_get_subject_name(cert.get());
+    if (!subject) {
+        LOG(ERROR) << "Failed to retrieve subject name";
+        return std::nullopt;
+    }
+
+    int encodedSubjectLength = i2d_X509_NAME(subject, /*out=*/nullptr);
+    if (encodedSubjectLength < 0) {
+        LOG(ERROR) << "Error obtaining encoded subject name length";
+        return std::nullopt;
+    }
+
+    vector<uint8_t> encodedSubject(encodedSubjectLength);
+    uint8_t* out = encodedSubject.data();
+    if (encodedSubjectLength != i2d_X509_NAME(subject, &out)) {
+        LOG(ERROR) << "Error encoding subject name";
+        return std::nullopt;
+    }
+
+    return encodedSubject;
+}
+
+// Generates the attestation certificate with the parameters passed in.  Note
+// that the passed in |activeTimeMilliSeconds| |expireTimeMilliSeconds| are in
+// milli seconds since epoch.  We are setting them to milliseconds due to
+// requirement in AuthorizationSet KM_DATE fields.  The certificate created is
+// actually in seconds.
+//
+optional<vector<vector<uint8_t>>> signAttestationCertificate(
+        const ::keymaster::PureSoftKeymasterContext& context, const EVP_PKEY* key,
+        const vector<uint8_t>& applicationId, const vector<uint8_t>& challenge,
+        const vector<uint8_t>& attestationKeyBlob,
+        const vector<uint8_t>& derAttestationCertSubjectName, uint64_t activeTimeMilliSeconds,
+        uint64_t expireTimeMilliSeconds, bool isTestCredential) {
+    ::keymaster::X509_NAME_Ptr subjectName;
+    if (KM_ERROR_OK !=
+        ::keymaster::make_name_from_str("Android Identity Credential Key", &subjectName)) {
+        LOG(ERROR) << "Cannot create attestation subject";
+        return {};
+    }
+
+    vector<uint8_t> subject(i2d_X509_NAME(subjectName.get(), NULL));
+    unsigned char* subjectPtr = subject.data();
+
+    i2d_X509_NAME(subjectName.get(), &subjectPtr);
+
+    ::keymaster::AuthorizationSet auth_set(
+            ::keymaster::AuthorizationSetBuilder()
+                    .Authorization(::keymaster::TAG_CERTIFICATE_NOT_BEFORE, activeTimeMilliSeconds)
+                    .Authorization(::keymaster::TAG_CERTIFICATE_NOT_AFTER, expireTimeMilliSeconds)
+                    .Authorization(::keymaster::TAG_ATTESTATION_CHALLENGE, challenge.data(),
+                                   challenge.size())
+                    .Authorization(::keymaster::TAG_ACTIVE_DATETIME, activeTimeMilliSeconds)
+                    // Even though identity attestation hal said the application
+                    // id should be in software enforced authentication set,
+                    // keymaster portable lib expect the input in this
+                    // parameter because the software enforced in input to keymaster
+                    // refers to the key software enforced properties. And this
+                    // parameter refers to properties of the attestation which
+                    // includes app id.
+                    .Authorization(::keymaster::TAG_ATTESTATION_APPLICATION_ID,
+                                   applicationId.data(), applicationId.size())
+                    .Authorization(::keymaster::TAG_CERTIFICATE_SUBJECT, subject.data(),
+                                   subject.size())
+                    .Authorization(::keymaster::TAG_USAGE_EXPIRE_DATETIME, expireTimeMilliSeconds));
+
+    // Unique id and device id is not applicable for identity credential attestation,
+    // so we don't need to set those or application id.
+    ::keymaster::AuthorizationSet swEnforced(::keymaster::AuthorizationSetBuilder().Authorization(
+            ::keymaster::TAG_CREATION_DATETIME, activeTimeMilliSeconds));
+
+    ::keymaster::AuthorizationSetBuilder hwEnforcedBuilder =
+            ::keymaster::AuthorizationSetBuilder()
+                    .Authorization(::keymaster::TAG_PURPOSE, KM_PURPOSE_SIGN)
+                    .Authorization(::keymaster::TAG_KEY_SIZE, 256)
+                    .Authorization(::keymaster::TAG_ALGORITHM, KM_ALGORITHM_EC)
+                    .Authorization(::keymaster::TAG_NO_AUTH_REQUIRED)
+                    .Authorization(::keymaster::TAG_DIGEST, KM_DIGEST_SHA_2_256)
+                    .Authorization(::keymaster::TAG_EC_CURVE, KM_EC_CURVE_P_256)
+                    .Authorization(::keymaster::TAG_OS_VERSION, 42)
+                    .Authorization(::keymaster::TAG_OS_PATCHLEVEL, 43);
+
+    // Only include TAG_IDENTITY_CREDENTIAL_KEY if it's not a test credential
+    if (!isTestCredential) {
+        hwEnforcedBuilder.Authorization(::keymaster::TAG_IDENTITY_CREDENTIAL_KEY);
+    }
+    ::keymaster::AuthorizationSet hwEnforced(hwEnforcedBuilder);
+
+    keymaster_error_t error;
+    ::keymaster::AttestKeyInfo attestKeyInfo;
+    ::keymaster::KeymasterBlob issuerSubjectNameBlob;
+    if (!attestationKeyBlob.empty()) {
+        ::keymaster::KeymasterKeyBlob blob(attestationKeyBlob.data(), attestationKeyBlob.size());
+        ::keymaster::UniquePtr<::keymaster::Key> parsedKey;
+        error = context.ParseKeyBlob(blob, /*additional_params=*/{}, &parsedKey);
+        if (error != KM_ERROR_OK) {
+            LOG(ERROR) << "Error loading attestation key: " << error;
+            return std::nullopt;
+        }
+
+        attestKeyInfo.signing_key =
+                static_cast<::keymaster::AsymmetricKey&>(*parsedKey).InternalToEvp();
+        issuerSubjectNameBlob = ::keymaster::KeymasterBlob(derAttestationCertSubjectName.data(),
+                                                           derAttestationCertSubjectName.size());
+        attestKeyInfo.issuer_subject = &issuerSubjectNameBlob;
+    }
+
+    ::keymaster::CertificateChain certChain = generate_attestation(
+            key, swEnforced, hwEnforced, auth_set, std::move(attestKeyInfo), context, &error);
+
+    if (KM_ERROR_OK != error) {
+        LOG(ERROR) << "Error generating attestation from EVP key: " << error;
+        return std::nullopt;
+    }
+
+    vector<vector<uint8_t>> vectors(certChain.entry_count);
+    for (std::size_t i = 0; i < certChain.entry_count; i++) {
+        vectors[i] = {certChain.entries[i].data,
+                      certChain.entries[i].data + certChain.entries[i].data_length};
+    }
+    return vectors;
+}
+
+int parseDigits(const char** s, int numDigits) {
+    int result;
+    auto [_, ec] = std::from_chars(*s, *s + numDigits, result);
+    if (ec != std::errc()) {
+        LOG(ERROR) << "Error parsing " << numDigits << " digits "
+                   << " from " << s;
+        return 0;
+    }
+    *s += numDigits;
+    return result;
+}
+
+bool parseAsn1Time(const ASN1_TIME* asn1Time, time_t* outTime) {
+    struct tm tm;
+
+    memset(&tm, '\0', sizeof(tm));
+    const char* timeStr = (const char*)asn1Time->data;
+    const char* s = timeStr;
+    if (asn1Time->type == V_ASN1_UTCTIME) {
+        tm.tm_year = parseDigits(&s, 2);
+        if (tm.tm_year < 70) {
+            tm.tm_year += 100;
+        }
+    } else if (asn1Time->type == V_ASN1_GENERALIZEDTIME) {
+        tm.tm_year = parseDigits(&s, 4) - 1900;
+        tm.tm_year -= 1900;
+    } else {
+        LOG(ERROR) << "Unsupported ASN1_TIME type " << asn1Time->type;
+        return false;
+    }
+    tm.tm_mon = parseDigits(&s, 2) - 1;
+    tm.tm_mday = parseDigits(&s, 2);
+    tm.tm_hour = parseDigits(&s, 2);
+    tm.tm_min = parseDigits(&s, 2);
+    tm.tm_sec = parseDigits(&s, 2);
+    // This may need to be updated if someone create certificates using +/- instead of Z.
+    //
+    if (*s != 'Z') {
+        LOG(ERROR) << "Expected Z in string '" << timeStr << "' at offset " << (s - timeStr);
+        return false;
+    }
+
+    time_t t = timegm(&tm);
+    if (t == -1) {
+        LOG(ERROR) << "Error converting broken-down time to time_t";
+        return false;
+    }
+    *outTime = t;
+    return true;
+}
+
+optional<uint64_t> getCertificateExpiryAsMillis(const uint8_t* derCert, size_t derCertSize) {
+    X509_Ptr x509Cert(d2i_X509(nullptr, &derCert, derCertSize));
+    if (!x509Cert) {
+        LOG(ERROR) << "Error parsing certificate";
+        return std::nullopt;
+    }
+
+    time_t notAfter;
+    if (!parseAsn1Time(X509_get0_notAfter(x509Cert.get()), &notAfter)) {
+        LOG(ERROR) << "Error getting notAfter from batch certificate";
+        return std::nullopt;
+    }
+
+    return notAfter * 1000;
+}
+
+optional<vector<vector<uint8_t>>> createAttestation(EVP_PKEY* pkey,
+                                                    const vector<uint8_t>& challenge,
+                                                    const vector<uint8_t>& applicationId,
+                                                    bool isTestCredential) {
+    // Pretend to be implemented in a trusted environment just so we can pass
+    // the VTS tests. Of course, this is a pretend-only game since hopefully no
+    // relying party is ever going to trust our batch key and those keys above
+    // it.
+    ::keymaster::PureSoftKeymasterContext context(::keymaster::KmVersion::KEYMINT_1,
+                                                  KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT);
+
+    keymaster_error_t error;
+    ::keymaster::CertificateChain attestation_chain =
+            context.GetAttestationChain(KM_ALGORITHM_EC, &error);
+    if (KM_ERROR_OK != error) {
+        LOG(ERROR) << "Error getting attestation chain " << error;
+        return std::nullopt;
+    }
+
+    if (attestation_chain.entry_count < 1) {
+        LOG(ERROR) << "Expected at least one entry in attestation chain";
+        return std::nullopt;
+    }
+
+    uint64_t activeTimeMs = time(nullptr) * 1000;
+    optional<uint64_t> expireTimeMs = getCertificateExpiryAsMillis(
+            attestation_chain.entries[0].data, attestation_chain.entries[0].data_length);
+    if (!expireTimeMs) {
+        LOG(ERROR) << "Error getting expiration time for batch cert";
+        return std::nullopt;
+    }
+
+    return signAttestationCertificate(context, pkey, applicationId, challenge,
+                                      /*attestationKeyBlob=*/{},
+                                      /*derAttestationCertSubjectName=*/{}, activeTimeMs,
+                                      *expireTimeMs, isTestCredential);
+}
+
+}  // namespace
+
 // bool getRandom(size_t numBytes, vector<uint8_t>& output) {
 optional<vector<uint8_t>> getRandom(size_t numBytes) {
     vector<uint8_t> output;
@@ -577,69 +858,30 @@
     return hmac;
 }
 
-int parseDigits(const char** s, int numDigits) {
-    int result;
-    auto [_, ec] = std::from_chars(*s, *s + numDigits, result);
-    if (ec != std::errc()) {
-        LOG(ERROR) << "Error parsing " << numDigits << " digits "
-                   << " from " << s;
-        return 0;
+optional<std::pair<vector<uint8_t>, vector<vector<uint8_t>>>> createEcKeyPairAndAttestation(
+        const vector<uint8_t>& challenge, const vector<uint8_t>& applicationId,
+        bool isTestCredential) {
+    EVP_PKEY_Ptr pkey = generateP256Key();
+
+    optional<vector<vector<uint8_t>>> attestationCertChain =
+            createAttestation(pkey.get(), challenge, applicationId, isTestCredential);
+    if (!attestationCertChain) {
+        LOG(ERROR) << "Error create attestation from key and challenge";
+        return {};
     }
-    *s += numDigits;
-    return result;
+
+    optional<vector<uint8_t>> keyPair = derEncodeKeyPair(*pkey);
+    if (!keyPair) {
+        return std::nullopt;
+    }
+
+    return make_pair(*keyPair, *attestationCertChain);
 }
 
-bool parseAsn1Time(const ASN1_TIME* asn1Time, time_t* outTime) {
-    struct tm tm;
-
-    memset(&tm, '\0', sizeof(tm));
-    const char* timeStr = (const char*)asn1Time->data;
-    const char* s = timeStr;
-    if (asn1Time->type == V_ASN1_UTCTIME) {
-        tm.tm_year = parseDigits(&s, 2);
-        if (tm.tm_year < 70) {
-            tm.tm_year += 100;
-        }
-    } else if (asn1Time->type == V_ASN1_GENERALIZEDTIME) {
-        tm.tm_year = parseDigits(&s, 4) - 1900;
-        tm.tm_year -= 1900;
-    } else {
-        LOG(ERROR) << "Unsupported ASN1_TIME type " << asn1Time->type;
-        return false;
-    }
-    tm.tm_mon = parseDigits(&s, 2) - 1;
-    tm.tm_mday = parseDigits(&s, 2);
-    tm.tm_hour = parseDigits(&s, 2);
-    tm.tm_min = parseDigits(&s, 2);
-    tm.tm_sec = parseDigits(&s, 2);
-    // This may need to be updated if someone create certificates using +/- instead of Z.
-    //
-    if (*s != 'Z') {
-        LOG(ERROR) << "Expected Z in string '" << timeStr << "' at offset " << (s - timeStr);
-        return false;
-    }
-
-    time_t t = timegm(&tm);
-    if (t == -1) {
-        LOG(ERROR) << "Error converting broken-down time to time_t";
-        return false;
-    }
-    *outTime = t;
-    return true;
-}
-
-// Generates the attestation certificate with the parameters passed in.  Note
-// that the passed in |activeTimeMilliSeconds| |expireTimeMilliSeconds| are in
-// milli seconds since epoch.  We are setting them to milliseconds due to
-// requirement in AuthorizationSet KM_DATE fields.  The certificate created is
-// actually in seconds.
-//
-// If 0 is passed for expiration time, the expiration time from batch
-// certificate will be used.
-//
-optional<vector<vector<uint8_t>>> createAttestation(
-        const EVP_PKEY* key, const vector<uint8_t>& applicationId, const vector<uint8_t>& challenge,
-        uint64_t activeTimeMilliSeconds, uint64_t expireTimeMilliSeconds, bool isTestCredential) {
+optional<std::pair<vector<uint8_t>, vector<uint8_t>>> createEcKeyPairWithAttestationKey(
+        const vector<uint8_t>& challenge, const vector<uint8_t>& applicationId,
+        const vector<uint8_t>& attestationKeyBlob, const vector<uint8_t>& attestationKeyCert,
+        bool isTestCredential) {
     // Pretend to be implemented in a trusted environment just so we can pass
     // the VTS tests. Of course, this is a pretend-only game since hopefully no
     // relying party is ever going to trust our batch key and those keys above
@@ -647,148 +889,45 @@
     ::keymaster::PureSoftKeymasterContext context(::keymaster::KmVersion::KEYMINT_1,
                                                   KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT);
 
-    keymaster_error_t error;
-    ::keymaster::CertificateChain attestation_chain =
-            context.GetAttestationChain(KM_ALGORITHM_EC, &error);
-    if (KM_ERROR_OK != error) {
-        LOG(ERROR) << "Error getting attestation chain " << error;
-        return {};
-    }
-    if (expireTimeMilliSeconds == 0) {
-        if (attestation_chain.entry_count < 1) {
-            LOG(ERROR) << "Expected at least one entry in attestation chain";
-            return {};
-        }
-        keymaster_blob_t* bcBlob = &(attestation_chain.entries[0]);
-        const uint8_t* bcData = bcBlob->data;
-        auto bc = X509_Ptr(d2i_X509(nullptr, &bcData, bcBlob->data_length));
-        time_t bcNotAfter;
-        if (!parseAsn1Time(X509_get0_notAfter(bc.get()), &bcNotAfter)) {
-            LOG(ERROR) << "Error getting notAfter from batch certificate";
-            return {};
-        }
-        expireTimeMilliSeconds = bcNotAfter * 1000;
+    EVP_PKEY_Ptr pkey = generateP256Key();
+
+    uint64_t validFromMs = time(nullptr) * 1000;
+    optional<uint64_t> notAfterMs =
+            getCertificateExpiryAsMillis(attestationKeyCert.data(), attestationKeyCert.size());
+    if (!notAfterMs) {
+        LOG(ERROR) << "Error getting expiration time for attestation cert";
+        return std::nullopt;
     }
 
-    ::keymaster::X509_NAME_Ptr subjectName;
-    if (KM_ERROR_OK !=
-        ::keymaster::make_name_from_str("Android Identity Credential Key", &subjectName)) {
-        LOG(ERROR) << "Cannot create attestation subject";
-        return {};
+    optional<vector<uint8_t>> derIssuerSubject =
+            extractDerSubjectFromCertificate(attestationKeyCert);
+    if (!derIssuerSubject) {
+        LOG(ERROR) << "Error error extracting issuer name from the given certificate chain";
+        return std::nullopt;
     }
 
-    vector<uint8_t> subject(i2d_X509_NAME(subjectName.get(), NULL));
-    unsigned char* subjectPtr = subject.data();
-
-    i2d_X509_NAME(subjectName.get(), &subjectPtr);
-
-    ::keymaster::AuthorizationSet auth_set(
-            ::keymaster::AuthorizationSetBuilder()
-                    .Authorization(::keymaster::TAG_CERTIFICATE_NOT_BEFORE, activeTimeMilliSeconds)
-                    .Authorization(::keymaster::TAG_CERTIFICATE_NOT_AFTER, expireTimeMilliSeconds)
-                    .Authorization(::keymaster::TAG_ATTESTATION_CHALLENGE, challenge.data(),
-                                   challenge.size())
-                    .Authorization(::keymaster::TAG_ACTIVE_DATETIME, activeTimeMilliSeconds)
-                    // Even though identity attestation hal said the application
-                    // id should be in software enforced authentication set,
-                    // keymaster portable lib expect the input in this
-                    // parameter because the software enforced in input to keymaster
-                    // refers to the key software enforced properties. And this
-                    // parameter refers to properties of the attestation which
-                    // includes app id.
-                    .Authorization(::keymaster::TAG_ATTESTATION_APPLICATION_ID,
-                                   applicationId.data(), applicationId.size())
-                    .Authorization(::keymaster::TAG_CERTIFICATE_SUBJECT, subject.data(),
-                                   subject.size())
-                    .Authorization(::keymaster::TAG_USAGE_EXPIRE_DATETIME, expireTimeMilliSeconds));
-
-    // Unique id and device id is not applicable for identity credential attestation,
-    // so we don't need to set those or application id.
-    ::keymaster::AuthorizationSet swEnforced(::keymaster::AuthorizationSetBuilder().Authorization(
-            ::keymaster::TAG_CREATION_DATETIME, activeTimeMilliSeconds));
-
-    ::keymaster::AuthorizationSetBuilder hwEnforcedBuilder =
-            ::keymaster::AuthorizationSetBuilder()
-                    .Authorization(::keymaster::TAG_PURPOSE, KM_PURPOSE_SIGN)
-                    .Authorization(::keymaster::TAG_KEY_SIZE, 256)
-                    .Authorization(::keymaster::TAG_ALGORITHM, KM_ALGORITHM_EC)
-                    .Authorization(::keymaster::TAG_NO_AUTH_REQUIRED)
-                    .Authorization(::keymaster::TAG_DIGEST, KM_DIGEST_SHA_2_256)
-                    .Authorization(::keymaster::TAG_EC_CURVE, KM_EC_CURVE_P_256)
-                    .Authorization(::keymaster::TAG_OS_VERSION, 42)
-                    .Authorization(::keymaster::TAG_OS_PATCHLEVEL, 43);
-
-    // Only include TAG_IDENTITY_CREDENTIAL_KEY if it's not a test credential
-    if (!isTestCredential) {
-        hwEnforcedBuilder.Authorization(::keymaster::TAG_IDENTITY_CREDENTIAL_KEY);
+    optional<vector<vector<uint8_t>>> attestationCertChain = signAttestationCertificate(
+            context, pkey.get(), applicationId, challenge, attestationKeyBlob, *derIssuerSubject,
+            validFromMs, *notAfterMs, isTestCredential);
+    if (!attestationCertChain) {
+        LOG(ERROR) << "Error signing attestation certificate";
+        return std::nullopt;
     }
-    ::keymaster::AuthorizationSet hwEnforced(hwEnforcedBuilder);
-
-    ::keymaster::CertificateChain cert_chain_out = generate_attestation(
-            key, swEnforced, hwEnforced, auth_set, {} /* attest_key */, context, &error);
-
-    if (KM_ERROR_OK != error) {
-        LOG(ERROR) << "Error generating attestation from EVP key: " << error;
-        return {};
-    }
-
-    // translate certificate format from keymaster_cert_chain_t to vector<vector<uint8_t>>.
-    vector<vector<uint8_t>> attestationCertificate;
-    for (std::size_t i = 0; i < cert_chain_out.entry_count; i++) {
-        attestationCertificate.insert(
-                attestationCertificate.end(),
-                vector<uint8_t>(
-                        cert_chain_out.entries[i].data,
-                        cert_chain_out.entries[i].data + cert_chain_out.entries[i].data_length));
-    }
-
-    return attestationCertificate;
-}
-
-optional<std::pair<vector<uint8_t>, vector<vector<uint8_t>>>> createEcKeyPairAndAttestation(
-        const vector<uint8_t>& challenge, const vector<uint8_t>& applicationId,
-        bool isTestCredential) {
-    auto ec_key = ::keymaster::EC_KEY_Ptr(EC_KEY_new());
-    auto pkey = ::keymaster::EVP_PKEY_Ptr(EVP_PKEY_new());
-    auto group = ::keymaster::EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
-
-    if (ec_key.get() == nullptr || pkey.get() == nullptr) {
-        LOG(ERROR) << "Memory allocation failed";
-        return {};
-    }
-
-    if (EC_KEY_set_group(ec_key.get(), group.get()) != 1 ||
-        EC_KEY_generate_key(ec_key.get()) != 1 || EC_KEY_check_key(ec_key.get()) < 0) {
-        LOG(ERROR) << "Error generating key";
-        return {};
-    }
-
-    if (EVP_PKEY_set1_EC_KEY(pkey.get(), ec_key.get()) != 1) {
-        LOG(ERROR) << "Error getting private key";
-        return {};
-    }
-
-    uint64_t nowMs = time(nullptr) * 1000;
-    uint64_t expireTimeMs = 0;  // Set to same as batch certificate
-
-    optional<vector<vector<uint8_t>>> attestationCert = createAttestation(
-            pkey.get(), applicationId, challenge, nowMs, expireTimeMs, isTestCredential);
-    if (!attestationCert) {
+    if (!attestationCertChain) {
         LOG(ERROR) << "Error create attestation from key and challenge";
-        return {};
+        return std::nullopt;
+    }
+    if (attestationCertChain->size() != 1) {
+        LOG(ERROR) << "Expected exactly one attestation cert, got " << attestationCertChain->size();
+        return std::nullopt;
     }
 
-    int size = i2d_PrivateKey(pkey.get(), nullptr);
-    if (size == 0) {
-        LOG(ERROR) << "Error generating public key encoding";
-        return {};
+    optional<vector<uint8_t>> keyPair = derEncodeKeyPair(*pkey);
+    if (!keyPair) {
+        return std::nullopt;
     }
 
-    vector<uint8_t> keyPair(size);
-    unsigned char* p = keyPair.data();
-    i2d_PrivateKey(pkey.get(), &p);
-
-    return make_pair(keyPair, attestationCert.value());
+    return make_pair(*keyPair, attestationCertChain->at(0));
 }
 
 optional<vector<vector<uint8_t>>> createAttestationForEcPublicKey(
@@ -820,12 +959,8 @@
         return {};
     }
 
-    uint64_t nowMs = time(nullptr) * 1000;
-    uint64_t expireTimeMs = 0;  // Set to same as batch certificate
-
     optional<vector<vector<uint8_t>>> attestationCert =
-            createAttestation(pkey.get(), applicationId, challenge, nowMs, expireTimeMs,
-                              false /* isTestCredential */);
+            createAttestation(pkey.get(), applicationId, challenge, false /* isTestCredential */);
     if (!attestationCert) {
         LOG(ERROR) << "Error create attestation from key and challenge";
         return {};
@@ -1134,6 +1269,14 @@
         return {};
     }
 
+    return ecPublicKeyGenerateCertificate(pkey.get(), privPkey.get(), serialDecimal, issuer,
+                                          subject, validityNotBefore, validityNotAfter, extensions);
+}
+
+optional<vector<uint8_t>> ecPublicKeyGenerateCertificate(
+        EVP_PKEY* publicKey, EVP_PKEY* signingKey, const string& serialDecimal,
+        const string& issuer, const string& subject, time_t validityNotBefore,
+        time_t validityNotAfter, const map<string, vector<uint8_t>>& extensions) {
     auto x509 = X509_Ptr(X509_new());
     if (!x509.get()) {
         LOG(ERROR) << "Error creating X509 certificate";
@@ -1145,7 +1288,7 @@
         return {};
     }
 
-    if (X509_set_pubkey(x509.get(), pkey.get()) != 1) {
+    if (X509_set_pubkey(x509.get(), publicKey) != 1) {
         LOG(ERROR) << "Error setting public key";
         return {};
     }
@@ -1220,7 +1363,7 @@
         }
     }
 
-    if (X509_sign(x509.get(), privPkey.get(), EVP_sha256()) == 0) {
+    if (X509_sign(x509.get(), signingKey, EVP_sha256()) == 0) {
         LOG(ERROR) << "Error signing X509 certificate";
         return {};
     }
diff --git a/nfc/aidl/Android.bp b/nfc/aidl/Android.bp
index d390c7e..30365f6 100644
--- a/nfc/aidl/Android.bp
+++ b/nfc/aidl/Android.bp
@@ -12,6 +12,15 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "hardware_interfaces_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["hardware_interfaces_license"],
+}
+
 aidl_interface {
     name: "android.hardware.nfc",
     vendor_available: true,
diff --git a/nfc/aidl/default/Android.bp b/nfc/aidl/default/Android.bp
index 907d23d..6daebe5 100644
--- a/nfc/aidl/default/Android.bp
+++ b/nfc/aidl/default/Android.bp
@@ -1,3 +1,12 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "hardware_interfaces_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["hardware_interfaces_license"],
+}
+
 cc_binary {
     name: "android.hardware.nfc-service.example",
     relative_install_path: "hw",
diff --git a/security/keymint/aidl/Android.bp b/security/keymint/aidl/Android.bp
index fb736e3..c9ee1b3 100644
--- a/security/keymint/aidl/Android.bp
+++ b/security/keymint/aidl/Android.bp
@@ -55,6 +55,13 @@
     ],
 }
 
+cc_defaults {
+    name: "keymint_use_latest_hal_aidl_cpp_static",
+    static_libs: [
+        "android.hardware.security.keymint-V2-cpp",
+    ],
+}
+
 // A rust_defaults that includes the latest KeyMint AIDL library.
 // Modules that depend on KeyMint directly can include this cc_defaults to avoid
 // managing dependency versions explicitly.
diff --git a/security/keymint/aidl/vts/functional/Android.bp b/security/keymint/aidl/vts/functional/Android.bp
index 2d2d701..91db3c8 100644
--- a/security/keymint/aidl/vts/functional/Android.bp
+++ b/security/keymint/aidl/vts/functional/Android.bp
@@ -75,6 +75,9 @@
     export_include_dirs: [
         ".",
     ],
+    export_static_lib_headers: [
+        "libkeymint_support",
+    ],
     static_libs: [
         "libgmock_ndk",
     ],
diff --git a/sensors/common/default/2.X/multihal/HalProxy.cpp b/sensors/common/default/2.X/multihal/HalProxy.cpp
index 73b0594..f44f5c4 100644
--- a/sensors/common/default/2.X/multihal/HalProxy.cpp
+++ b/sensors/common/default/2.X/multihal/HalProxy.cpp
@@ -261,8 +261,8 @@
         Result currRes = mSubHalList[i]->initialize(this, this, i);
         if (currRes != Result::OK) {
             result = currRes;
-            ALOGE("Subhal '%s' failed to initialize.", mSubHalList[i]->getName().c_str());
-            break;
+            ALOGE("Subhal '%s' failed to initialize with reason %" PRId32 ".",
+                  mSubHalList[i]->getName().c_str(), static_cast<int32_t>(currRes));
         }
     }
 
diff --git a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionSetAppConfigCmdParams.aidl b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionSetAppConfigCmdParams.aidl
index f449c60..0d53431 100644
--- a/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionSetAppConfigCmdParams.aidl
+++ b/uwb/aidl/aidl_api/android.hardware.uwb.fira_android/current/android/hardware/uwb/fira_android/UwbVendorSessionSetAppConfigCmdParams.aidl
@@ -34,6 +34,8 @@
 package android.hardware.uwb.fira_android;
 @Backing(type="int") @VintfStability
 enum UwbVendorSessionSetAppConfigCmdParams {
+  CCC_HOP_MODE_KEY = 160,
+  CCC_UWB_TIME0 = 161,
   CCC_RANGING_PROTOCOL_VER = 163,
   CCC_UWB_CONFIG_ID = 164,
   CCC_PULSESHAPE_COMBO = 165,
diff --git a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionSetAppConfigCmdParams.aidl b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionSetAppConfigCmdParams.aidl
index f5e02c0..eb1f5ac 100644
--- a/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionSetAppConfigCmdParams.aidl
+++ b/uwb/aidl/android/hardware/uwb/fira_android/UwbVendorSessionSetAppConfigCmdParams.aidl
@@ -33,9 +33,17 @@
      * Added in vendor version 0.
      * Range 0xA0 - 0xDF reserved for CCC use.
      */
+    /** 16 byte data */
+    CCC_HOP_MODE_KEY = 0xA0,
+    /** 8 byte data */
+    CCC_UWB_TIME0 = 0xA1,
+    /** 2 byte data */
     CCC_RANGING_PROTOCOL_VER = 0xA3,
+    /** 2 byte data */
     CCC_UWB_CONFIG_ID = 0xA4,
+    /** 1 byte data */
     CCC_PULSESHAPE_COMBO = 0xA5,
+    /** 2 byte data */
     CCC_URSK_TTL = 0xA6,
 
     /**
@@ -51,7 +59,10 @@
      * Supported only if the value returned by getSupportedAndroidCapabilities()
      * has the bit of UwbAndroidCapabilities.ANTENNAE_INTERLEAVING set to 1.
      */
+    /** 2 byte data */
     NB_OF_RANGE_MEASUREMENTS = 0xE3,
+    /** 2 byte data */
     NB_OF_AZIMUTH_MEASUREMENTS = 0xE4,
+    /** 2 byte data */
     NB_OF_ELEVATION_MEASUREMENTS = 0xE5,
 }