Merge changes from topic "ks2_aidl_autogen"

* changes:
  Keystore 2.0: Add globals.rs and utils.rs
  Update prebuilt keymint interface.
  Keystore 2.0: Adopt associated const enum variants.
  Keystore 2.0: Switch to autogenerated AIDL bindings.
diff --git a/keystore2/Android.bp b/keystore2/Android.bp
index b5728a3..f4b153c 100644
--- a/keystore2/Android.bp
+++ b/keystore2/Android.bp
@@ -18,8 +18,8 @@
     srcs: ["src/lib.rs"],
 
     rustlibs: [
+        "android.system.keystore2-rust",
         "libandroid_hardware_keymint",
-        "libandroid_security_keystore2",
         "libanyhow",
         "libbinder_rs",
         "libkeystore2_selinux",
@@ -39,9 +39,9 @@
     test_suites: ["general-tests"],
     auto_gen_config: true,
     rustlibs: [
+        "android.system.keystore2-rust",
         "libandroid_logger",
         "libandroid_hardware_keymint",
-        "libandroid_security_keystore2",
         "libanyhow",
         "libbinder_rs",
         "libkeystore2_selinux",
@@ -66,18 +66,3 @@
         "liblazy_static",
     ],
 }
-
-// This is a placeholder for the libraries that will be generated from the AIDL specs
-// eventually.
-rust_library {
-    name: "libandroid_security_keystore2",
-    crate_name: "android_security_keystore2",
-
-    srcs: ["src/android_security_keystore2.rs"],
-
-    rustlibs: [
-        "libandroid_hardware_keymint",
-        "libbinder_rs",
-        "liblazy_static",
-    ],
-}
diff --git a/keystore2/src/android_hardware_keymint.rs b/keystore2/src/android_hardware_keymint.rs
index deb9f7b..103b9b9 100644
--- a/keystore2/src/android_hardware_keymint.rs
+++ b/keystore2/src/android_hardware_keymint.rs
@@ -10,15 +10,18 @@
       pub mod keymint {
         pub mod Algorithm {
           #![allow(non_upper_case_globals)]
-          pub type Algorithm = i32;
-          pub const RSA: Algorithm = 1;
-          pub const EC: Algorithm = 3;
-          pub const AES: Algorithm = 32;
-          pub const TRIPLE_DES: Algorithm = 33;
-          pub const HMAC: Algorithm = 128;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { Algorithm : i32 {
+            RSA = 1,
+            EC = 3,
+            AES = 32,
+            TRIPLE_DES = 33,
+            HMAC = 128,
+          } }
           pub(crate) mod mangled { pub use super::Algorithm as _7_android_8_hardware_7_keymint_9_Algorithm; }
         }
         pub mod BeginResult {
+          #[derive(Debug)]
           pub struct BeginResult {
             pub challenge: i64, 
             pub params: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter>, 
@@ -79,18 +82,15 @@
               if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
               let mut result = Self::default();
               result.challenge = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.params = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.operation = Some(parcel.read()?);
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               Ok(Some(result))
@@ -99,14 +99,17 @@
         }
         pub mod BlockMode {
           #![allow(non_upper_case_globals)]
-          pub type BlockMode = i32;
-          pub const ECB: BlockMode = 1;
-          pub const CBC: BlockMode = 2;
-          pub const CTR: BlockMode = 3;
-          pub const GCM: BlockMode = 32;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { BlockMode : i32 {
+            ECB = 1,
+            CBC = 2,
+            CTR = 3,
+            GCM = 32,
+          } }
           pub(crate) mod mangled { pub use super::BlockMode as _7_android_8_hardware_7_keymint_9_BlockMode; }
         }
         pub mod Certificate {
+          #[derive(Debug)]
           pub struct Certificate {
             pub encodedCertificate: Vec<u8>, 
           }
@@ -160,8 +163,7 @@
               if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
               let mut result = Self::default();
               result.encodedCertificate = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               Ok(Some(result))
@@ -170,116 +172,125 @@
         }
         pub mod Constants {
           #![allow(non_upper_case_globals)]
-          pub type Constants = i32;
-          pub const AUTH_TOKEN_MAC_LENGTH: Constants = 32;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { Constants : i32 {
+            AUTH_TOKEN_MAC_LENGTH = 32,
+          } }
           pub(crate) mod mangled { pub use super::Constants as _7_android_8_hardware_7_keymint_9_Constants; }
         }
         pub mod Digest {
           #![allow(non_upper_case_globals)]
-          pub type Digest = i32;
-          pub const NONE: Digest = 0;
-          pub const MD5: Digest = 1;
-          pub const SHA1: Digest = 2;
-          pub const SHA_2_224: Digest = 3;
-          pub const SHA_2_256: Digest = 4;
-          pub const SHA_2_384: Digest = 5;
-          pub const SHA_2_512: Digest = 6;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { Digest : i32 {
+            NONE = 0,
+            MD5 = 1,
+            SHA1 = 2,
+            SHA_2_224 = 3,
+            SHA_2_256 = 4,
+            SHA_2_384 = 5,
+            SHA_2_512 = 6,
+          } }
           pub(crate) mod mangled { pub use super::Digest as _7_android_8_hardware_7_keymint_6_Digest; }
         }
         pub mod EcCurve {
           #![allow(non_upper_case_globals)]
-          pub type EcCurve = i32;
-          pub const P_224: EcCurve = 0;
-          pub const P_256: EcCurve = 1;
-          pub const P_384: EcCurve = 2;
-          pub const P_521: EcCurve = 3;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { EcCurve : i32 {
+            P_224 = 0,
+            P_256 = 1,
+            P_384 = 2,
+            P_521 = 3,
+          } }
           pub(crate) mod mangled { pub use super::EcCurve as _7_android_8_hardware_7_keymint_7_EcCurve; }
         }
         pub mod ErrorCode {
           #![allow(non_upper_case_globals)]
-          pub type ErrorCode = i32;
-          pub const OK: ErrorCode = 0;
-          pub const ROOT_OF_TRUST_ALREADY_SET: ErrorCode = -1;
-          pub const UNSUPPORTED_PURPOSE: ErrorCode = -2;
-          pub const INCOMPATIBLE_PURPOSE: ErrorCode = -3;
-          pub const UNSUPPORTED_ALGORITHM: ErrorCode = -4;
-          pub const INCOMPATIBLE_ALGORITHM: ErrorCode = -5;
-          pub const UNSUPPORTED_KEY_SIZE: ErrorCode = -6;
-          pub const UNSUPPORTED_BLOCK_MODE: ErrorCode = -7;
-          pub const INCOMPATIBLE_BLOCK_MODE: ErrorCode = -8;
-          pub const UNSUPPORTED_MAC_LENGTH: ErrorCode = -9;
-          pub const UNSUPPORTED_PADDING_MODE: ErrorCode = -10;
-          pub const INCOMPATIBLE_PADDING_MODE: ErrorCode = -11;
-          pub const UNSUPPORTED_DIGEST: ErrorCode = -12;
-          pub const INCOMPATIBLE_DIGEST: ErrorCode = -13;
-          pub const INVALID_EXPIRATION_TIME: ErrorCode = -14;
-          pub const INVALID_USER_ID: ErrorCode = -15;
-          pub const INVALID_AUTHORIZATION_TIMEOUT: ErrorCode = -16;
-          pub const UNSUPPORTED_KEY_FORMAT: ErrorCode = -17;
-          pub const INCOMPATIBLE_KEY_FORMAT: ErrorCode = -18;
-          pub const UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM: ErrorCode = -19;
-          pub const UNSUPPORTED_KEY_VERIFICATION_ALGORITHM: ErrorCode = -20;
-          pub const INVALID_INPUT_LENGTH: ErrorCode = -21;
-          pub const KEY_EXPORT_OPTIONS_INVALID: ErrorCode = -22;
-          pub const DELEGATION_NOT_ALLOWED: ErrorCode = -23;
-          pub const KEY_NOT_YET_VALID: ErrorCode = -24;
-          pub const KEY_EXPIRED: ErrorCode = -25;
-          pub const KEY_USER_NOT_AUTHENTICATED: ErrorCode = -26;
-          pub const OUTPUT_PARAMETER_NULL: ErrorCode = -27;
-          pub const INVALID_OPERATION_HANDLE: ErrorCode = -28;
-          pub const INSUFFICIENT_BUFFER_SPACE: ErrorCode = -29;
-          pub const VERIFICATION_FAILED: ErrorCode = -30;
-          pub const TOO_MANY_OPERATIONS: ErrorCode = -31;
-          pub const UNEXPECTED_NULL_POINTER: ErrorCode = -32;
-          pub const INVALID_KEY_BLOB: ErrorCode = -33;
-          pub const IMPORTED_KEY_NOT_ENCRYPTED: ErrorCode = -34;
-          pub const IMPORTED_KEY_DECRYPTION_FAILED: ErrorCode = -35;
-          pub const IMPORTED_KEY_NOT_SIGNED: ErrorCode = -36;
-          pub const IMPORTED_KEY_VERIFICATION_FAILED: ErrorCode = -37;
-          pub const INVALID_ARGUMENT: ErrorCode = -38;
-          pub const UNSUPPORTED_TAG: ErrorCode = -39;
-          pub const INVALID_TAG: ErrorCode = -40;
-          pub const MEMORY_ALLOCATION_FAILED: ErrorCode = -41;
-          pub const IMPORT_PARAMETER_MISMATCH: ErrorCode = -44;
-          pub const SECURE_HW_ACCESS_DENIED: ErrorCode = -45;
-          pub const OPERATION_CANCELLED: ErrorCode = -46;
-          pub const CONCURRENT_ACCESS_CONFLICT: ErrorCode = -47;
-          pub const SECURE_HW_BUSY: ErrorCode = -48;
-          pub const SECURE_HW_COMMUNICATION_FAILED: ErrorCode = -49;
-          pub const UNSUPPORTED_EC_FIELD: ErrorCode = -50;
-          pub const MISSING_NONCE: ErrorCode = -51;
-          pub const INVALID_NONCE: ErrorCode = -52;
-          pub const MISSING_MAC_LENGTH: ErrorCode = -53;
-          pub const KEY_RATE_LIMIT_EXCEEDED: ErrorCode = -54;
-          pub const CALLER_NONCE_PROHIBITED: ErrorCode = -55;
-          pub const KEY_MAX_OPS_EXCEEDED: ErrorCode = -56;
-          pub const INVALID_MAC_LENGTH: ErrorCode = -57;
-          pub const MISSING_MIN_MAC_LENGTH: ErrorCode = -58;
-          pub const UNSUPPORTED_MIN_MAC_LENGTH: ErrorCode = -59;
-          pub const UNSUPPORTED_KDF: ErrorCode = -60;
-          pub const UNSUPPORTED_EC_CURVE: ErrorCode = -61;
-          pub const KEY_REQUIRES_UPGRADE: ErrorCode = -62;
-          pub const ATTESTATION_CHALLENGE_MISSING: ErrorCode = -63;
-          pub const KEYMINT_NOT_CONFIGURED: ErrorCode = -64;
-          pub const ATTESTATION_APPLICATION_ID_MISSING: ErrorCode = -65;
-          pub const CANNOT_ATTEST_IDS: ErrorCode = -66;
-          pub const ROLLBACK_RESISTANCE_UNAVAILABLE: ErrorCode = -67;
-          pub const HARDWARE_TYPE_UNAVAILABLE: ErrorCode = -68;
-          pub const PROOF_OF_PRESENCE_REQUIRED: ErrorCode = -69;
-          pub const CONCURRENT_PROOF_OF_PRESENCE_REQUESTED: ErrorCode = -70;
-          pub const NO_USER_CONFIRMATION: ErrorCode = -71;
-          pub const DEVICE_LOCKED: ErrorCode = -72;
-          pub const EARLY_BOOT_ENDED: ErrorCode = -73;
-          pub const ATTESTATION_KEYS_NOT_PROVISIONED: ErrorCode = -74;
-          pub const ATTESTATION_IDS_NOT_PROVISIONED: ErrorCode = -75;
-          pub const INVALID_OPERATION: ErrorCode = -76;
-          pub const STORAGE_KEY_UNSUPPORTED: ErrorCode = -77;
-          pub const UNIMPLEMENTED: ErrorCode = -100;
-          pub const VERSION_MISMATCH: ErrorCode = -101;
-          pub const UNKNOWN_ERROR: ErrorCode = -1000;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { ErrorCode : i32 {
+            OK = 0,
+            ROOT_OF_TRUST_ALREADY_SET = -1,
+            UNSUPPORTED_PURPOSE = -2,
+            INCOMPATIBLE_PURPOSE = -3,
+            UNSUPPORTED_ALGORITHM = -4,
+            INCOMPATIBLE_ALGORITHM = -5,
+            UNSUPPORTED_KEY_SIZE = -6,
+            UNSUPPORTED_BLOCK_MODE = -7,
+            INCOMPATIBLE_BLOCK_MODE = -8,
+            UNSUPPORTED_MAC_LENGTH = -9,
+            UNSUPPORTED_PADDING_MODE = -10,
+            INCOMPATIBLE_PADDING_MODE = -11,
+            UNSUPPORTED_DIGEST = -12,
+            INCOMPATIBLE_DIGEST = -13,
+            INVALID_EXPIRATION_TIME = -14,
+            INVALID_USER_ID = -15,
+            INVALID_AUTHORIZATION_TIMEOUT = -16,
+            UNSUPPORTED_KEY_FORMAT = -17,
+            INCOMPATIBLE_KEY_FORMAT = -18,
+            UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM = -19,
+            UNSUPPORTED_KEY_VERIFICATION_ALGORITHM = -20,
+            INVALID_INPUT_LENGTH = -21,
+            KEY_EXPORT_OPTIONS_INVALID = -22,
+            DELEGATION_NOT_ALLOWED = -23,
+            KEY_NOT_YET_VALID = -24,
+            KEY_EXPIRED = -25,
+            KEY_USER_NOT_AUTHENTICATED = -26,
+            OUTPUT_PARAMETER_NULL = -27,
+            INVALID_OPERATION_HANDLE = -28,
+            INSUFFICIENT_BUFFER_SPACE = -29,
+            VERIFICATION_FAILED = -30,
+            TOO_MANY_OPERATIONS = -31,
+            UNEXPECTED_NULL_POINTER = -32,
+            INVALID_KEY_BLOB = -33,
+            IMPORTED_KEY_NOT_ENCRYPTED = -34,
+            IMPORTED_KEY_DECRYPTION_FAILED = -35,
+            IMPORTED_KEY_NOT_SIGNED = -36,
+            IMPORTED_KEY_VERIFICATION_FAILED = -37,
+            INVALID_ARGUMENT = -38,
+            UNSUPPORTED_TAG = -39,
+            INVALID_TAG = -40,
+            MEMORY_ALLOCATION_FAILED = -41,
+            IMPORT_PARAMETER_MISMATCH = -44,
+            SECURE_HW_ACCESS_DENIED = -45,
+            OPERATION_CANCELLED = -46,
+            CONCURRENT_ACCESS_CONFLICT = -47,
+            SECURE_HW_BUSY = -48,
+            SECURE_HW_COMMUNICATION_FAILED = -49,
+            UNSUPPORTED_EC_FIELD = -50,
+            MISSING_NONCE = -51,
+            INVALID_NONCE = -52,
+            MISSING_MAC_LENGTH = -53,
+            KEY_RATE_LIMIT_EXCEEDED = -54,
+            CALLER_NONCE_PROHIBITED = -55,
+            KEY_MAX_OPS_EXCEEDED = -56,
+            INVALID_MAC_LENGTH = -57,
+            MISSING_MIN_MAC_LENGTH = -58,
+            UNSUPPORTED_MIN_MAC_LENGTH = -59,
+            UNSUPPORTED_KDF = -60,
+            UNSUPPORTED_EC_CURVE = -61,
+            KEY_REQUIRES_UPGRADE = -62,
+            ATTESTATION_CHALLENGE_MISSING = -63,
+            KEYMINT_NOT_CONFIGURED = -64,
+            ATTESTATION_APPLICATION_ID_MISSING = -65,
+            CANNOT_ATTEST_IDS = -66,
+            ROLLBACK_RESISTANCE_UNAVAILABLE = -67,
+            HARDWARE_TYPE_UNAVAILABLE = -68,
+            PROOF_OF_PRESENCE_REQUIRED = -69,
+            CONCURRENT_PROOF_OF_PRESENCE_REQUESTED = -70,
+            NO_USER_CONFIRMATION = -71,
+            DEVICE_LOCKED = -72,
+            EARLY_BOOT_ENDED = -73,
+            ATTESTATION_KEYS_NOT_PROVISIONED = -74,
+            ATTESTATION_IDS_NOT_PROVISIONED = -75,
+            INVALID_OPERATION = -76,
+            STORAGE_KEY_UNSUPPORTED = -77,
+            UNIMPLEMENTED = -100,
+            VERSION_MISMATCH = -101,
+            UNKNOWN_ERROR = -1000,
+          } }
           pub(crate) mod mangled { pub use super::ErrorCode as _7_android_8_hardware_7_keymint_9_ErrorCode; }
         }
         pub mod HardwareAuthToken {
+          #[derive(Debug)]
           pub struct HardwareAuthToken {
             pub challenge: i64, 
             pub userId: i64, 
@@ -348,33 +359,27 @@
               if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
               let mut result = Self::default();
               result.challenge = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.userId = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.authenticatorId = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.authenticatorType = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.timestamp = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.mac = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               Ok(Some(result))
@@ -383,14 +388,17 @@
         }
         pub mod HardwareAuthenticatorType {
           #![allow(non_upper_case_globals)]
-          pub type HardwareAuthenticatorType = i32;
-          pub const NONE: HardwareAuthenticatorType = 0;
-          pub const PASSWORD: HardwareAuthenticatorType = 1;
-          pub const FINGERPRINT: HardwareAuthenticatorType = 2;
-          pub const ANY: HardwareAuthenticatorType = -1;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { HardwareAuthenticatorType : i32 {
+            NONE = 0,
+            PASSWORD = 1,
+            FINGERPRINT = 2,
+            ANY = -1,
+          } }
           pub(crate) mod mangled { pub use super::HardwareAuthenticatorType as _7_android_8_hardware_7_keymint_25_HardwareAuthenticatorType; }
         }
         pub mod HmacSharingParameters {
+          #[derive(Debug)]
           pub struct HmacSharingParameters {
             pub seed: Vec<u8>, 
             pub nonce: Vec<u8>, 
@@ -447,13 +455,11 @@
               if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
               let mut result = Self::default();
               result.seed = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.nonce = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               Ok(Some(result))
@@ -507,33 +513,36 @@
             fn begin(&self, _arg_inPurpose: crate::mangled::_7_android_8_hardware_7_keymint_10_KeyPurpose, _arg_inKeyBlob: &[u8], _arg_inParams: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_inAuthToken: &crate::mangled::_7_android_8_hardware_7_keymint_17_HardwareAuthToken) -> binder::public_api::Result<crate::mangled::_7_android_8_hardware_7_keymint_11_BeginResult> {
               Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
             }
-            fn getDefaultImpl() -> DefaultImpl where Self: Sized {
+            fn getDefaultImpl() -> IKeyMintDeviceDefault where Self: Sized {
               DEFAULT_IMPL.lock().unwrap().clone()
             }
-            fn setDefaultImpl(d: DefaultImpl) -> DefaultImpl where Self: Sized {
+            fn setDefaultImpl(d: IKeyMintDeviceDefault) -> IKeyMintDeviceDefault where Self: Sized {
               std::mem::replace(&mut *DEFAULT_IMPL.lock().unwrap(), d)
             }
           }
-          pub const TRANSACTION_getHardwareInfo: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 0;
-          pub const TRANSACTION_verifyAuthorization: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 1;
-          pub const TRANSACTION_addRngEntropy: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 2;
-          pub const TRANSACTION_generateKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 3;
-          pub const TRANSACTION_importKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 4;
-          pub const TRANSACTION_importWrappedKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 5;
-          pub const TRANSACTION_upgradeKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 6;
-          pub const TRANSACTION_deleteKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 7;
-          pub const TRANSACTION_deleteAllKeys: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 8;
-          pub const TRANSACTION_destroyAttestationIds: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 9;
-          pub const TRANSACTION_begin: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 10;
-          pub type DefaultImpl = Option<std::sync::Arc<dyn IKeyMintDevice + Sync>>;
+          pub mod transactions {
+            #[allow(unused_imports)] use binder::IBinder;
+            pub const getHardwareInfo: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 0;
+            pub const verifyAuthorization: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 1;
+            pub const addRngEntropy: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 2;
+            pub const generateKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 3;
+            pub const importKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 4;
+            pub const importWrappedKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 5;
+            pub const upgradeKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 6;
+            pub const deleteKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 7;
+            pub const deleteAllKeys: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 8;
+            pub const destroyAttestationIds: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 9;
+            pub const begin: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 10;
+          }
+          pub type IKeyMintDeviceDefault = Option<std::sync::Arc<dyn IKeyMintDevice + Sync>>;
           use lazy_static::lazy_static;
           lazy_static! {
-            static ref DEFAULT_IMPL: std::sync::Mutex<DefaultImpl> = std::sync::Mutex::new(None);
+            static ref DEFAULT_IMPL: std::sync::Mutex<IKeyMintDeviceDefault> = std::sync::Mutex::new(None);
           }
           pub(crate) mod mangled { pub use super::IKeyMintDevice as _7_android_8_hardware_7_keymint_14_IKeyMintDevice; }
           impl IKeyMintDevice for BpKeyMintDevice {
             fn getHardwareInfo(&self) -> binder::public_api::Result<crate::mangled::_7_android_8_hardware_7_keymint_19_KeyMintHardwareInfo> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_getHardwareInfo, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::getHardwareInfo, 0, |_aidl_data| {
                 Ok(())
               });
               if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
@@ -548,7 +557,7 @@
               Ok(_aidl_return)
             }
             fn verifyAuthorization(&self, _arg_challenge: i64, _arg_parametersToVerify: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_token: &crate::mangled::_7_android_8_hardware_7_keymint_17_HardwareAuthToken) -> binder::public_api::Result<crate::mangled::_7_android_8_hardware_7_keymint_17_VerificationToken> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_verifyAuthorization, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::verifyAuthorization, 0, |_aidl_data| {
                 _aidl_data.write(&_arg_challenge)?;
                 _aidl_data.write(_arg_parametersToVerify)?;
                 _aidl_data.write(_arg_token)?;
@@ -566,7 +575,7 @@
               Ok(_aidl_return)
             }
             fn addRngEntropy(&self, _arg_data: &[u8]) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_addRngEntropy, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::addRngEntropy, 0, |_aidl_data| {
                 _aidl_data.write(_arg_data)?;
                 Ok(())
               });
@@ -581,7 +590,7 @@
               Ok(())
             }
             fn generateKey(&self, _arg_keyParams: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_generatedKeyBlob: &mut Vec<u8>, _arg_generatedKeyCharacteristics: &mut crate::mangled::_7_android_8_hardware_7_keymint_18_KeyCharacteristics, _arg_outCertChain: &mut Vec<crate::mangled::_7_android_8_hardware_7_keymint_11_Certificate>) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_generateKey, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::generateKey, 0, |_aidl_data| {
                 _aidl_data.write(_arg_keyParams)?;
                 _aidl_data.write_slice_size(Some(_arg_generatedKeyBlob))?;
                 _aidl_data.write_slice_size(Some(_arg_outCertChain))?;
@@ -601,7 +610,7 @@
               Ok(())
             }
             fn importKey(&self, _arg_inKeyParams: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_inKeyFormat: crate::mangled::_7_android_8_hardware_7_keymint_9_KeyFormat, _arg_inKeyData: &[u8], _arg_outImportedKeyBlob: &mut Vec<u8>, _arg_outImportedKeyCharacteristics: &mut crate::mangled::_7_android_8_hardware_7_keymint_18_KeyCharacteristics, _arg_outCertChain: &mut Vec<crate::mangled::_7_android_8_hardware_7_keymint_11_Certificate>) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_importKey, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::importKey, 0, |_aidl_data| {
                 _aidl_data.write(_arg_inKeyParams)?;
                 _aidl_data.write(&_arg_inKeyFormat)?;
                 _aidl_data.write(_arg_inKeyData)?;
@@ -623,7 +632,7 @@
               Ok(())
             }
             fn importWrappedKey(&self, _arg_inWrappedKeyData: &[u8], _arg_inWrappingKeyBlob: &[u8], _arg_inMaskingKey: &[u8], _arg_inUnwrappingParams: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_inPasswordSid: i64, _arg_inBiometricSid: i64, _arg_outImportedKeyBlob: &mut Vec<u8>, _arg_outImportedKeyCharacteristics: &mut crate::mangled::_7_android_8_hardware_7_keymint_18_KeyCharacteristics) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_importWrappedKey, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::importWrappedKey, 0, |_aidl_data| {
                 _aidl_data.write(_arg_inWrappedKeyData)?;
                 _aidl_data.write(_arg_inWrappingKeyBlob)?;
                 _aidl_data.write(_arg_inMaskingKey)?;
@@ -646,7 +655,7 @@
               Ok(())
             }
             fn upgradeKey(&self, _arg_inKeyBlobToUpgrade: &[u8], _arg_inUpgradeParams: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter]) -> binder::public_api::Result<Vec<u8>> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_upgradeKey, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::upgradeKey, 0, |_aidl_data| {
                 _aidl_data.write(_arg_inKeyBlobToUpgrade)?;
                 _aidl_data.write(_arg_inUpgradeParams)?;
                 Ok(())
@@ -663,7 +672,7 @@
               Ok(_aidl_return)
             }
             fn deleteKey(&self, _arg_inKeyBlob: &[u8]) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_deleteKey, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::deleteKey, 0, |_aidl_data| {
                 _aidl_data.write(_arg_inKeyBlob)?;
                 Ok(())
               });
@@ -678,7 +687,7 @@
               Ok(())
             }
             fn deleteAllKeys(&self) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_deleteAllKeys, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::deleteAllKeys, 0, |_aidl_data| {
                 Ok(())
               });
               if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
@@ -692,7 +701,7 @@
               Ok(())
             }
             fn destroyAttestationIds(&self) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_destroyAttestationIds, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::destroyAttestationIds, 0, |_aidl_data| {
                 Ok(())
               });
               if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
@@ -706,7 +715,7 @@
               Ok(())
             }
             fn begin(&self, _arg_inPurpose: crate::mangled::_7_android_8_hardware_7_keymint_10_KeyPurpose, _arg_inKeyBlob: &[u8], _arg_inParams: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_inAuthToken: &crate::mangled::_7_android_8_hardware_7_keymint_17_HardwareAuthToken) -> binder::public_api::Result<crate::mangled::_7_android_8_hardware_7_keymint_11_BeginResult> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_begin, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::begin, 0, |_aidl_data| {
                 _aidl_data.write(&_arg_inPurpose)?;
                 _aidl_data.write(_arg_inKeyBlob)?;
                 _aidl_data.write(_arg_inParams)?;
@@ -740,7 +749,7 @@
           }
           fn on_transact(_aidl_service: &dyn IKeyMintDevice, _aidl_code: binder::TransactionCode, _aidl_data: &binder::parcel::Parcel, _aidl_reply: &mut binder::parcel::Parcel) -> binder::Result<()> {
             match _aidl_code {
-              TRANSACTION_getHardwareInfo => {
+              transactions::getHardwareInfo => {
                 let _aidl_return = _aidl_service.getHardwareInfo();
                 match &_aidl_return {
                   Ok(_aidl_return) => {
@@ -751,7 +760,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_verifyAuthorization => {
+              transactions::verifyAuthorization => {
                 let _arg_challenge: i64 = _aidl_data.read()?;
                 let _arg_parametersToVerify: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter> = _aidl_data.read()?;
                 let _arg_token: crate::mangled::_7_android_8_hardware_7_keymint_17_HardwareAuthToken = _aidl_data.read()?;
@@ -765,7 +774,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_addRngEntropy => {
+              transactions::addRngEntropy => {
                 let _arg_data: Vec<u8> = _aidl_data.read()?;
                 let _aidl_return = _aidl_service.addRngEntropy(&_arg_data);
                 match &_aidl_return {
@@ -776,7 +785,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_generateKey => {
+              transactions::generateKey => {
                 let _arg_keyParams: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter> = _aidl_data.read()?;
                 let mut _arg_generatedKeyBlob: Vec<u8> = Default::default();
                 _aidl_data.resize_out_vec(&mut _arg_generatedKeyBlob)?;
@@ -795,7 +804,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_importKey => {
+              transactions::importKey => {
                 let _arg_inKeyParams: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter> = _aidl_data.read()?;
                 let _arg_inKeyFormat: crate::mangled::_7_android_8_hardware_7_keymint_9_KeyFormat = _aidl_data.read()?;
                 let _arg_inKeyData: Vec<u8> = _aidl_data.read()?;
@@ -816,7 +825,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_importWrappedKey => {
+              transactions::importWrappedKey => {
                 let _arg_inWrappedKeyData: Vec<u8> = _aidl_data.read()?;
                 let _arg_inWrappingKeyBlob: Vec<u8> = _aidl_data.read()?;
                 let _arg_inMaskingKey: Vec<u8> = _aidl_data.read()?;
@@ -837,7 +846,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_upgradeKey => {
+              transactions::upgradeKey => {
                 let _arg_inKeyBlobToUpgrade: Vec<u8> = _aidl_data.read()?;
                 let _arg_inUpgradeParams: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter> = _aidl_data.read()?;
                 let _aidl_return = _aidl_service.upgradeKey(&_arg_inKeyBlobToUpgrade, &_arg_inUpgradeParams);
@@ -850,7 +859,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_deleteKey => {
+              transactions::deleteKey => {
                 let _arg_inKeyBlob: Vec<u8> = _aidl_data.read()?;
                 let _aidl_return = _aidl_service.deleteKey(&_arg_inKeyBlob);
                 match &_aidl_return {
@@ -861,7 +870,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_deleteAllKeys => {
+              transactions::deleteAllKeys => {
                 let _aidl_return = _aidl_service.deleteAllKeys();
                 match &_aidl_return {
                   Ok(_aidl_return) => {
@@ -871,7 +880,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_destroyAttestationIds => {
+              transactions::destroyAttestationIds => {
                 let _aidl_return = _aidl_service.destroyAttestationIds();
                 match &_aidl_return {
                   Ok(_aidl_return) => {
@@ -881,7 +890,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_begin => {
+              transactions::begin => {
                 let _arg_inPurpose: crate::mangled::_7_android_8_hardware_7_keymint_10_KeyPurpose = _aidl_data.read()?;
                 let _arg_inKeyBlob: Vec<u8> = _aidl_data.read()?;
                 let _arg_inParams: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter> = _aidl_data.read()?;
@@ -923,25 +932,28 @@
             fn abort(&self) -> binder::public_api::Result<()> {
               Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
             }
-            fn getDefaultImpl() -> DefaultImpl where Self: Sized {
+            fn getDefaultImpl() -> IKeyMintOperationDefault where Self: Sized {
               DEFAULT_IMPL.lock().unwrap().clone()
             }
-            fn setDefaultImpl(d: DefaultImpl) -> DefaultImpl where Self: Sized {
+            fn setDefaultImpl(d: IKeyMintOperationDefault) -> IKeyMintOperationDefault where Self: Sized {
               std::mem::replace(&mut *DEFAULT_IMPL.lock().unwrap(), d)
             }
           }
-          pub const TRANSACTION_update: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 0;
-          pub const TRANSACTION_finish: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 1;
-          pub const TRANSACTION_abort: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 2;
-          pub type DefaultImpl = Option<std::sync::Arc<dyn IKeyMintOperation + Sync>>;
+          pub mod transactions {
+            #[allow(unused_imports)] use binder::IBinder;
+            pub const update: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 0;
+            pub const finish: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 1;
+            pub const abort: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 2;
+          }
+          pub type IKeyMintOperationDefault = Option<std::sync::Arc<dyn IKeyMintOperation + Sync>>;
           use lazy_static::lazy_static;
           lazy_static! {
-            static ref DEFAULT_IMPL: std::sync::Mutex<DefaultImpl> = std::sync::Mutex::new(None);
+            static ref DEFAULT_IMPL: std::sync::Mutex<IKeyMintOperationDefault> = std::sync::Mutex::new(None);
           }
           pub(crate) mod mangled { pub use super::IKeyMintOperation as _7_android_8_hardware_7_keymint_17_IKeyMintOperation; }
           impl IKeyMintOperation for BpKeyMintOperation {
             fn update(&self, _arg_inParams: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_input: &[u8], _arg_inVerificationToken: &crate::mangled::_7_android_8_hardware_7_keymint_17_VerificationToken, _arg_outParams: &mut Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter>, _arg_output: &mut Vec<u8>) -> binder::public_api::Result<i32> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_update, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::update, 0, |_aidl_data| {
                 _aidl_data.write(_arg_inParams)?;
                 _aidl_data.write(_arg_input)?;
                 _aidl_data.write(_arg_inVerificationToken)?;
@@ -963,7 +975,7 @@
               Ok(_aidl_return)
             }
             fn finish(&self, _arg_inParams: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_input: &[u8], _arg_inSignature: &[u8], _arg_authToken: &crate::mangled::_7_android_8_hardware_7_keymint_17_HardwareAuthToken, _arg_inVerificationToken: &crate::mangled::_7_android_8_hardware_7_keymint_17_VerificationToken, _arg_outParams: &mut Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter>, _arg_output: &mut Vec<u8>) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_finish, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::finish, 0, |_aidl_data| {
                 _aidl_data.write(_arg_inParams)?;
                 _aidl_data.write(_arg_input)?;
                 _aidl_data.write(_arg_inSignature)?;
@@ -986,7 +998,7 @@
               Ok(())
             }
             fn abort(&self) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_abort, 0, |_aidl_data| {
+              let _aidl_reply = self.binder.transact(transactions::abort, 0, |_aidl_data| {
                 Ok(())
               });
               if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
@@ -1007,7 +1019,7 @@
           }
           fn on_transact(_aidl_service: &dyn IKeyMintOperation, _aidl_code: binder::TransactionCode, _aidl_data: &binder::parcel::Parcel, _aidl_reply: &mut binder::parcel::Parcel) -> binder::Result<()> {
             match _aidl_code {
-              TRANSACTION_update => {
+              transactions::update => {
                 let _arg_inParams: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter> = _aidl_data.read()?;
                 let _arg_input: Vec<u8> = _aidl_data.read()?;
                 let _arg_inVerificationToken: crate::mangled::_7_android_8_hardware_7_keymint_17_VerificationToken = _aidl_data.read()?;
@@ -1027,7 +1039,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_finish => {
+              transactions::finish => {
                 let _arg_inParams: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter> = _aidl_data.read()?;
                 let _arg_input: Vec<u8> = _aidl_data.read()?;
                 let _arg_inSignature: Vec<u8> = _aidl_data.read()?;
@@ -1048,7 +1060,7 @@
                 }
                 Ok(())
               }
-              TRANSACTION_abort => {
+              transactions::abort => {
                 let _aidl_return = _aidl_service.abort();
                 match &_aidl_return {
                   Ok(_aidl_return) => {
@@ -1063,6 +1075,7 @@
           }
         }
         pub mod KeyCharacteristics {
+          #[derive(Debug)]
           pub struct KeyCharacteristics {
             pub softwareEnforced: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter>, 
             pub hardwareEnforced: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter>, 
@@ -1119,13 +1132,11 @@
               if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
               let mut result = Self::default();
               result.softwareEnforced = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.hardwareEnforced = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               Ok(Some(result))
@@ -1134,24 +1145,29 @@
         }
         pub mod KeyDerivationFunction {
           #![allow(non_upper_case_globals)]
-          pub type KeyDerivationFunction = i32;
-          pub const NONE: KeyDerivationFunction = 0;
-          pub const RFC5869_SHA256: KeyDerivationFunction = 1;
-          pub const ISO18033_2_KDF1_SHA1: KeyDerivationFunction = 2;
-          pub const ISO18033_2_KDF1_SHA256: KeyDerivationFunction = 3;
-          pub const ISO18033_2_KDF2_SHA1: KeyDerivationFunction = 4;
-          pub const ISO18033_2_KDF2_SHA256: KeyDerivationFunction = 5;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { KeyDerivationFunction : i32 {
+            NONE = 0,
+            RFC5869_SHA256 = 1,
+            ISO18033_2_KDF1_SHA1 = 2,
+            ISO18033_2_KDF1_SHA256 = 3,
+            ISO18033_2_KDF2_SHA1 = 4,
+            ISO18033_2_KDF2_SHA256 = 5,
+          } }
           pub(crate) mod mangled { pub use super::KeyDerivationFunction as _7_android_8_hardware_7_keymint_21_KeyDerivationFunction; }
         }
         pub mod KeyFormat {
           #![allow(non_upper_case_globals)]
-          pub type KeyFormat = i32;
-          pub const X509: KeyFormat = 0;
-          pub const PKCS8: KeyFormat = 1;
-          pub const RAW: KeyFormat = 3;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { KeyFormat : i32 {
+            X509 = 0,
+            PKCS8 = 1,
+            RAW = 3,
+          } }
           pub(crate) mod mangled { pub use super::KeyFormat as _7_android_8_hardware_7_keymint_9_KeyFormat; }
         }
         pub mod KeyMintHardwareInfo {
+          #[derive(Debug)]
           pub struct KeyMintHardwareInfo {
             pub versionNumber: i32, 
             pub securityLevel: crate::mangled::_7_android_8_hardware_7_keymint_13_SecurityLevel, 
@@ -1214,23 +1230,19 @@
               if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
               let mut result = Self::default();
               result.versionNumber = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.securityLevel = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.keyMintName = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.keyMintAuthorName = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               Ok(Some(result))
@@ -1239,15 +1251,18 @@
         }
         pub mod KeyOrigin {
           #![allow(non_upper_case_globals)]
-          pub type KeyOrigin = i32;
-          pub const GENERATED: KeyOrigin = 0;
-          pub const DERIVED: KeyOrigin = 1;
-          pub const IMPORTED: KeyOrigin = 2;
-          pub const RESERVED: KeyOrigin = 3;
-          pub const SECURELY_IMPORTED: KeyOrigin = 4;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { KeyOrigin : i32 {
+            GENERATED = 0,
+            DERIVED = 1,
+            IMPORTED = 2,
+            RESERVED = 3,
+            SECURELY_IMPORTED = 4,
+          } }
           pub(crate) mod mangled { pub use super::KeyOrigin as _7_android_8_hardware_7_keymint_9_KeyOrigin; }
         }
         pub mod KeyParameter {
+          #[derive(Debug)]
           pub struct KeyParameter {
             pub tag: crate::mangled::_7_android_8_hardware_7_keymint_3_Tag, 
             pub boolValue: bool, 
@@ -1316,33 +1331,27 @@
               if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
               let mut result = Self::default();
               result.tag = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.boolValue = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.integer = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.longInteger = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.dateTime = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.blob = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               Ok(Some(result))
@@ -1351,114 +1360,125 @@
         }
         pub mod KeyPurpose {
           #![allow(non_upper_case_globals)]
-          pub type KeyPurpose = i32;
-          pub const ENCRYPT: KeyPurpose = 0;
-          pub const DECRYPT: KeyPurpose = 1;
-          pub const SIGN: KeyPurpose = 2;
-          pub const VERIFY: KeyPurpose = 3;
-          pub const WRAP_KEY: KeyPurpose = 5;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { KeyPurpose : i32 {
+            ENCRYPT = 0,
+            DECRYPT = 1,
+            SIGN = 2,
+            VERIFY = 3,
+            WRAP_KEY = 5,
+          } }
           pub(crate) mod mangled { pub use super::KeyPurpose as _7_android_8_hardware_7_keymint_10_KeyPurpose; }
         }
         pub mod PaddingMode {
           #![allow(non_upper_case_globals)]
-          pub type PaddingMode = i32;
-          pub const NONE: PaddingMode = 1;
-          pub const RSA_OAEP: PaddingMode = 2;
-          pub const RSA_PSS: PaddingMode = 3;
-          pub const RSA_PKCS1_1_5_ENCRYPT: PaddingMode = 4;
-          pub const RSA_PKCS1_1_5_SIGN: PaddingMode = 5;
-          pub const PKCS7: PaddingMode = 64;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { PaddingMode : i32 {
+            NONE = 1,
+            RSA_OAEP = 2,
+            RSA_PSS = 3,
+            RSA_PKCS1_1_5_ENCRYPT = 4,
+            RSA_PKCS1_1_5_SIGN = 5,
+            PKCS7 = 64,
+          } }
           pub(crate) mod mangled { pub use super::PaddingMode as _7_android_8_hardware_7_keymint_11_PaddingMode; }
         }
         pub mod SecurityLevel {
           #![allow(non_upper_case_globals)]
-          pub type SecurityLevel = i32;
-          pub const SOFTWARE: SecurityLevel = 0;
-          pub const TRUSTED_ENVIRONMENT: SecurityLevel = 1;
-          pub const STRONGBOX: SecurityLevel = 2;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { SecurityLevel : i32 {
+            SOFTWARE = 0,
+            TRUSTED_ENVIRONMENT = 1,
+            STRONGBOX = 2,
+          } }
           pub(crate) mod mangled { pub use super::SecurityLevel as _7_android_8_hardware_7_keymint_13_SecurityLevel; }
         }
         pub mod Tag {
           #![allow(non_upper_case_globals)]
-          pub type Tag = i32;
-          pub const INVALID: Tag = 0;
-          pub const PURPOSE: Tag = 536870913;
-          pub const ALGORITHM: Tag = 268435458;
-          pub const KEY_SIZE: Tag = 805306371;
-          pub const BLOCK_MODE: Tag = 536870916;
-          pub const DIGEST: Tag = 536870917;
-          pub const PADDING: Tag = 536870918;
-          pub const CALLER_NONCE: Tag = 1879048199;
-          pub const MIN_MAC_LENGTH: Tag = 805306376;
-          pub const EC_CURVE: Tag = 268435466;
-          pub const RSA_PUBLIC_EXPONENT: Tag = 1342177480;
-          pub const INCLUDE_UNIQUE_ID: Tag = 1879048394;
-          pub const BLOB_USAGE_REQUIREMENTS: Tag = 268435757;
-          pub const BOOTLOADER_ONLY: Tag = 1879048494;
-          pub const ROLLBACK_RESISTANCE: Tag = 1879048495;
-          pub const HARDWARE_TYPE: Tag = 268435760;
-          pub const EARLY_BOOT_ONLY: Tag = 1879048497;
-          pub const ACTIVE_DATETIME: Tag = 1610613136;
-          pub const ORIGINATION_EXPIRE_DATETIME: Tag = 1610613137;
-          pub const USAGE_EXPIRE_DATETIME: Tag = 1610613138;
-          pub const MIN_SECONDS_BETWEEN_OPS: Tag = 805306771;
-          pub const MAX_USES_PER_BOOT: Tag = 805306772;
-          pub const USER_ID: Tag = 805306869;
-          pub const USER_SECURE_ID: Tag = 1073742326;
-          pub const NO_AUTH_REQUIRED: Tag = 1879048695;
-          pub const USER_AUTH_TYPE: Tag = 268435960;
-          pub const AUTH_TIMEOUT: Tag = 805306873;
-          pub const ALLOW_WHILE_ON_BODY: Tag = 1879048698;
-          pub const TRUSTED_USER_PRESENCE_REQUIRED: Tag = 1879048699;
-          pub const TRUSTED_CONFIRMATION_REQUIRED: Tag = 1879048700;
-          pub const UNLOCKED_DEVICE_REQUIRED: Tag = 1879048701;
-          pub const APPLICATION_ID: Tag = -1879047591;
-          pub const APPLICATION_DATA: Tag = -1879047492;
-          pub const CREATION_DATETIME: Tag = 1610613437;
-          pub const ORIGIN: Tag = 268436158;
-          pub const ROOT_OF_TRUST: Tag = -1879047488;
-          pub const OS_VERSION: Tag = 805307073;
-          pub const OS_PATCHLEVEL: Tag = 805307074;
-          pub const UNIQUE_ID: Tag = -1879047485;
-          pub const ATTESTATION_CHALLENGE: Tag = -1879047484;
-          pub const ATTESTATION_APPLICATION_ID: Tag = -1879047483;
-          pub const ATTESTATION_ID_BRAND: Tag = -1879047482;
-          pub const ATTESTATION_ID_DEVICE: Tag = -1879047481;
-          pub const ATTESTATION_ID_PRODUCT: Tag = -1879047480;
-          pub const ATTESTATION_ID_SERIAL: Tag = -1879047479;
-          pub const ATTESTATION_ID_IMEI: Tag = -1879047478;
-          pub const ATTESTATION_ID_MEID: Tag = -1879047477;
-          pub const ATTESTATION_ID_MANUFACTURER: Tag = -1879047476;
-          pub const ATTESTATION_ID_MODEL: Tag = -1879047475;
-          pub const VENDOR_PATCHLEVEL: Tag = 805307086;
-          pub const BOOT_PATCHLEVEL: Tag = 805307087;
-          pub const DEVICE_UNIQUE_ATTESTATION: Tag = 1879048912;
-          pub const IDENTITY_CREDENTIAL_KEY: Tag = 1879048913;
-          pub const STORAGE_KEY: Tag = 1879048914;
-          pub const ASSOCIATED_DATA: Tag = -1879047192;
-          pub const NONCE: Tag = -1879047191;
-          pub const MAC_LENGTH: Tag = 805307371;
-          pub const RESET_SINCE_ID_ROTATION: Tag = 1879049196;
-          pub const CONFIRMATION_TOKEN: Tag = -1879047187;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { Tag : i32 {
+            INVALID = 0,
+            PURPOSE = 536870913,
+            ALGORITHM = 268435458,
+            KEY_SIZE = 805306371,
+            BLOCK_MODE = 536870916,
+            DIGEST = 536870917,
+            PADDING = 536870918,
+            CALLER_NONCE = 1879048199,
+            MIN_MAC_LENGTH = 805306376,
+            EC_CURVE = 268435466,
+            RSA_PUBLIC_EXPONENT = 1342177480,
+            INCLUDE_UNIQUE_ID = 1879048394,
+            BLOB_USAGE_REQUIREMENTS = 268435757,
+            BOOTLOADER_ONLY = 1879048494,
+            ROLLBACK_RESISTANCE = 1879048495,
+            HARDWARE_TYPE = 268435760,
+            EARLY_BOOT_ONLY = 1879048497,
+            ACTIVE_DATETIME = 1610613136,
+            ORIGINATION_EXPIRE_DATETIME = 1610613137,
+            USAGE_EXPIRE_DATETIME = 1610613138,
+            MIN_SECONDS_BETWEEN_OPS = 805306771,
+            MAX_USES_PER_BOOT = 805306772,
+            USER_ID = 805306869,
+            USER_SECURE_ID = 1073742326,
+            NO_AUTH_REQUIRED = 1879048695,
+            USER_AUTH_TYPE = 268435960,
+            AUTH_TIMEOUT = 805306873,
+            ALLOW_WHILE_ON_BODY = 1879048698,
+            TRUSTED_USER_PRESENCE_REQUIRED = 1879048699,
+            TRUSTED_CONFIRMATION_REQUIRED = 1879048700,
+            UNLOCKED_DEVICE_REQUIRED = 1879048701,
+            APPLICATION_ID = -1879047591,
+            APPLICATION_DATA = -1879047492,
+            CREATION_DATETIME = 1610613437,
+            ORIGIN = 268436158,
+            ROOT_OF_TRUST = -1879047488,
+            OS_VERSION = 805307073,
+            OS_PATCHLEVEL = 805307074,
+            UNIQUE_ID = -1879047485,
+            ATTESTATION_CHALLENGE = -1879047484,
+            ATTESTATION_APPLICATION_ID = -1879047483,
+            ATTESTATION_ID_BRAND = -1879047482,
+            ATTESTATION_ID_DEVICE = -1879047481,
+            ATTESTATION_ID_PRODUCT = -1879047480,
+            ATTESTATION_ID_SERIAL = -1879047479,
+            ATTESTATION_ID_IMEI = -1879047478,
+            ATTESTATION_ID_MEID = -1879047477,
+            ATTESTATION_ID_MANUFACTURER = -1879047476,
+            ATTESTATION_ID_MODEL = -1879047475,
+            VENDOR_PATCHLEVEL = 805307086,
+            BOOT_PATCHLEVEL = 805307087,
+            DEVICE_UNIQUE_ATTESTATION = 1879048912,
+            IDENTITY_CREDENTIAL_KEY = 1879048913,
+            STORAGE_KEY = 1879048914,
+            ASSOCIATED_DATA = -1879047192,
+            NONCE = -1879047191,
+            MAC_LENGTH = 805307371,
+            RESET_SINCE_ID_ROTATION = 1879049196,
+            CONFIRMATION_TOKEN = -1879047187,
+          } }
           pub(crate) mod mangled { pub use super::Tag as _7_android_8_hardware_7_keymint_3_Tag; }
         }
         pub mod TagType {
           #![allow(non_upper_case_globals)]
-          pub type TagType = i32;
-          pub const INVALID: TagType = 0;
-          pub const ENUM: TagType = 268435456;
-          pub const ENUM_REP: TagType = 536870912;
-          pub const UINT: TagType = 805306368;
-          pub const UINT_REP: TagType = 1073741824;
-          pub const ULONG: TagType = 1342177280;
-          pub const DATE: TagType = 1610612736;
-          pub const BOOL: TagType = 1879048192;
-          pub const BIGNUM: TagType = -2147483648;
-          pub const BYTES: TagType = -1879048192;
-          pub const ULONG_REP: TagType = -1610612736;
+          use binder::declare_binder_enum;
+          declare_binder_enum! { TagType : i32 {
+            INVALID = 0,
+            ENUM = 268435456,
+            ENUM_REP = 536870912,
+            UINT = 805306368,
+            UINT_REP = 1073741824,
+            ULONG = 1342177280,
+            DATE = 1610612736,
+            BOOL = 1879048192,
+            BIGNUM = -2147483648,
+            BYTES = -1879048192,
+            ULONG_REP = -1610612736,
+          } }
           pub(crate) mod mangled { pub use super::TagType as _7_android_8_hardware_7_keymint_7_TagType; }
         }
         pub mod Timestamp {
+          #[derive(Debug)]
           pub struct Timestamp {
             pub milliSeconds: i64, 
           }
@@ -1512,8 +1532,7 @@
               if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
               let mut result = Self::default();
               result.milliSeconds = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               Ok(Some(result))
@@ -1521,6 +1540,7 @@
           }
         }
         pub mod VerificationToken {
+          #[derive(Debug)]
           pub struct VerificationToken {
             pub challenge: i64, 
             pub timestamp: crate::mangled::_7_android_8_hardware_7_keymint_9_Timestamp, 
@@ -1583,23 +1603,19 @@
               if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
               let mut result = Self::default();
               result.challenge = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.timestamp = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.securityLevel = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               result.mac = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
+              if (parcel.get_data_position() - start_pos) == parcelable_size {
                 return Ok(Some(result));
               }
               Ok(Some(result))
diff --git a/keystore2/src/android_security_keystore2.rs b/keystore2/src/android_security_keystore2.rs
deleted file mode 100644
index d22a593..0000000
--- a/keystore2/src/android_security_keystore2.rs
+++ /dev/null
@@ -1,1143 +0,0 @@
-#![allow(non_snake_case)]
-#![allow(missing_docs)]
-#![allow(clippy::identity_op)]
-#![allow(clippy::excessive_precision)]
-#![allow(clippy::too_many_arguments)]
-pub use binder::public_api as binder;
-pub mod aidl {
-  pub mod android {
-    pub mod security {
-      pub mod keystore2 {
-        pub mod AuthenticatorSpec {
-          pub struct AuthenticatorSpec {
-            pub authenticatorType: crate::mangled::_7_android_8_hardware_7_keymint_25_HardwareAuthenticatorType, 
-            pub authenticatorId: i64, 
-          }
-          pub(crate) mod mangled { pub use super::AuthenticatorSpec as _7_android_8_security_9_keystore2_17_AuthenticatorSpec; }
-          impl Default for AuthenticatorSpec {
-            fn default() -> Self {
-              Self {
-                authenticatorType: Default::default(),
-                authenticatorId: 0,
-              }
-            }
-          }
-          impl binder::parcel::Serialize for AuthenticatorSpec {
-            fn serialize(&self, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              <Self as binder::parcel::SerializeOption>::serialize_option(Some(self), parcel)
-            }
-          }
-          impl binder::parcel::SerializeArray for AuthenticatorSpec {}
-          impl binder::parcel::SerializeOption for AuthenticatorSpec {
-            fn serialize_option(this: Option<&Self>, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              let this = if let Some(this) = this {
-                parcel.write(&1i32)?;
-                this
-              } else {
-                return parcel.write(&0i32);
-              };
-              let start_pos = parcel.get_data_position();
-              parcel.write(&0i32)?;
-              parcel.write(&this.authenticatorType)?;
-              parcel.write(&this.authenticatorId)?;
-              let end_pos = parcel.get_data_position();
-              let parcelable_size = (end_pos - start_pos) as i32;
-              unsafe { parcel.set_data_position(start_pos)?; }
-              parcel.write(&parcelable_size)?;
-              unsafe { parcel.set_data_position(end_pos)?; }
-              Ok(())
-            }
-          }
-          impl binder::parcel::Deserialize for AuthenticatorSpec {
-            fn deserialize(parcel: &binder::parcel::Parcel) -> binder::Result<Self> {
-              <Self as binder::parcel::DeserializeOption>::deserialize_option(parcel)
-                 .transpose()
-                 .unwrap_or(Err(binder::StatusCode::UNEXPECTED_NULL))
-            }
-          }
-          impl binder::parcel::DeserializeArray for AuthenticatorSpec {}
-          impl binder::parcel::DeserializeOption for AuthenticatorSpec {
-            fn deserialize_option(parcel: &binder::parcel::Parcel) -> binder::Result<Option<Self>> {
-              let status: i32 = parcel.read()?;
-              if status == 0 { return Ok(None); }
-              let start_pos = parcel.get_data_position();
-              let parcelable_size: i32 = parcel.read()?;
-              if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
-              let mut result = Self::default();
-              result.authenticatorType = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              result.authenticatorId = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              Ok(Some(result))
-            }
-          }
-        }
-        pub mod Certificate {
-          pub struct Certificate {
-            pub data: Vec<u8>, 
-          }
-          pub(crate) mod mangled { pub use super::Certificate as _7_android_8_security_9_keystore2_11_Certificate; }
-          impl Default for Certificate {
-            fn default() -> Self {
-              Self {
-                data: Default::default(),
-              }
-            }
-          }
-          impl binder::parcel::Serialize for Certificate {
-            fn serialize(&self, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              <Self as binder::parcel::SerializeOption>::serialize_option(Some(self), parcel)
-            }
-          }
-          impl binder::parcel::SerializeArray for Certificate {}
-          impl binder::parcel::SerializeOption for Certificate {
-            fn serialize_option(this: Option<&Self>, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              let this = if let Some(this) = this {
-                parcel.write(&1i32)?;
-                this
-              } else {
-                return parcel.write(&0i32);
-              };
-              let start_pos = parcel.get_data_position();
-              parcel.write(&0i32)?;
-              parcel.write(&this.data)?;
-              let end_pos = parcel.get_data_position();
-              let parcelable_size = (end_pos - start_pos) as i32;
-              unsafe { parcel.set_data_position(start_pos)?; }
-              parcel.write(&parcelable_size)?;
-              unsafe { parcel.set_data_position(end_pos)?; }
-              Ok(())
-            }
-          }
-          impl binder::parcel::Deserialize for Certificate {
-            fn deserialize(parcel: &binder::parcel::Parcel) -> binder::Result<Self> {
-              <Self as binder::parcel::DeserializeOption>::deserialize_option(parcel)
-                 .transpose()
-                 .unwrap_or(Err(binder::StatusCode::UNEXPECTED_NULL))
-            }
-          }
-          impl binder::parcel::DeserializeArray for Certificate {}
-          impl binder::parcel::DeserializeOption for Certificate {
-            fn deserialize_option(parcel: &binder::parcel::Parcel) -> binder::Result<Option<Self>> {
-              let status: i32 = parcel.read()?;
-              if status == 0 { return Ok(None); }
-              let start_pos = parcel.get_data_position();
-              let parcelable_size: i32 = parcel.read()?;
-              if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
-              let mut result = Self::default();
-              result.data = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              Ok(Some(result))
-            }
-          }
-        }
-        pub mod CertificateChain {
-          pub struct CertificateChain {
-            pub data: Vec<u8>, 
-          }
-          pub(crate) mod mangled { pub use super::CertificateChain as _7_android_8_security_9_keystore2_16_CertificateChain; }
-          impl Default for CertificateChain {
-            fn default() -> Self {
-              Self {
-                data: Default::default(),
-              }
-            }
-          }
-          impl binder::parcel::Serialize for CertificateChain {
-            fn serialize(&self, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              <Self as binder::parcel::SerializeOption>::serialize_option(Some(self), parcel)
-            }
-          }
-          impl binder::parcel::SerializeArray for CertificateChain {}
-          impl binder::parcel::SerializeOption for CertificateChain {
-            fn serialize_option(this: Option<&Self>, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              let this = if let Some(this) = this {
-                parcel.write(&1i32)?;
-                this
-              } else {
-                return parcel.write(&0i32);
-              };
-              let start_pos = parcel.get_data_position();
-              parcel.write(&0i32)?;
-              parcel.write(&this.data)?;
-              let end_pos = parcel.get_data_position();
-              let parcelable_size = (end_pos - start_pos) as i32;
-              unsafe { parcel.set_data_position(start_pos)?; }
-              parcel.write(&parcelable_size)?;
-              unsafe { parcel.set_data_position(end_pos)?; }
-              Ok(())
-            }
-          }
-          impl binder::parcel::Deserialize for CertificateChain {
-            fn deserialize(parcel: &binder::parcel::Parcel) -> binder::Result<Self> {
-              <Self as binder::parcel::DeserializeOption>::deserialize_option(parcel)
-                 .transpose()
-                 .unwrap_or(Err(binder::StatusCode::UNEXPECTED_NULL))
-            }
-          }
-          impl binder::parcel::DeserializeArray for CertificateChain {}
-          impl binder::parcel::DeserializeOption for CertificateChain {
-            fn deserialize_option(parcel: &binder::parcel::Parcel) -> binder::Result<Option<Self>> {
-              let status: i32 = parcel.read()?;
-              if status == 0 { return Ok(None); }
-              let start_pos = parcel.get_data_position();
-              let parcelable_size: i32 = parcel.read()?;
-              if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
-              let mut result = Self::default();
-              result.data = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              Ok(Some(result))
-            }
-          }
-        }
-        pub mod Domain {
-          #![allow(non_upper_case_globals)]
-          pub type Domain = i32;
-          pub const App: Domain = 0;
-          pub const Grant: Domain = 1;
-          pub const SELinux: Domain = 2;
-          pub const Blob: Domain = 3;
-          pub const KeyId: Domain = 4;
-          pub(crate) mod mangled { pub use super::Domain as _7_android_8_security_9_keystore2_6_Domain; }
-        }
-        pub mod IKeystoreOperation {
-          #![allow(non_upper_case_globals)]
-          #![allow(non_snake_case)]
-          #[allow(unused_imports)] use binder::IBinder;
-          use binder::declare_binder_interface;
-          declare_binder_interface! {
-            IKeystoreOperation["android.security.keystore2.IKeystoreOperation"] {
-              native: BnKeystoreOperation(on_transact),
-              proxy: BpKeystoreOperation {
-              },
-            }
-          }
-          pub trait IKeystoreOperation: binder::Interface + Send {
-            fn get_descriptor() -> &'static str where Self: Sized { "android.security.keystore2.IKeystoreOperation" }
-            fn update(&self, _arg_input: Option<&[u8]>, _arg_aadInput: Option<&[u8]>, _arg_output: &mut Option<Vec<u8>>) -> binder::public_api::Result<()> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn finish(&self, _arg_input: Option<&[u8]>, _arg_signature: Option<&[u8]>, _arg_entropy: Option<&[u8]>, _arg_output: &mut Option<Vec<u8>>) -> binder::public_api::Result<()> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn abort(&self) -> binder::public_api::Result<()> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn getDefaultImpl() -> DefaultImpl where Self: Sized {
-              DEFAULT_IMPL.lock().unwrap().clone()
-            }
-            fn setDefaultImpl(d: DefaultImpl) -> DefaultImpl where Self: Sized {
-              std::mem::replace(&mut *DEFAULT_IMPL.lock().unwrap(), d)
-            }
-          }
-          pub const TRANSACTION_update: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 0;
-          pub const TRANSACTION_finish: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 1;
-          pub const TRANSACTION_abort: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 2;
-          pub type DefaultImpl = Option<std::sync::Arc<dyn IKeystoreOperation + Sync>>;
-          use lazy_static::lazy_static;
-          lazy_static! {
-            static ref DEFAULT_IMPL: std::sync::Mutex<DefaultImpl> = std::sync::Mutex::new(None);
-          }
-          pub(crate) mod mangled { pub use super::IKeystoreOperation as _7_android_8_security_9_keystore2_18_IKeystoreOperation; }
-          impl IKeystoreOperation for BpKeystoreOperation {
-            fn update(&self, _arg_input: Option<&[u8]>, _arg_aadInput: Option<&[u8]>, _arg_output: &mut Option<Vec<u8>>) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_update, 0, |_aidl_data| {
-                _aidl_data.write(&_arg_input)?;
-                _aidl_data.write(&_arg_aadInput)?;
-                _aidl_data.write_slice_size(_arg_output.as_deref())?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreOperation>::getDefaultImpl() {
-                  return _aidl_default_impl.update(_arg_input, _arg_aadInput, _arg_output);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              *_arg_output = _aidl_reply.read()?;
-              Ok(())
-            }
-            fn finish(&self, _arg_input: Option<&[u8]>, _arg_signature: Option<&[u8]>, _arg_entropy: Option<&[u8]>, _arg_output: &mut Option<Vec<u8>>) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_finish, 0, |_aidl_data| {
-                _aidl_data.write(&_arg_input)?;
-                _aidl_data.write(&_arg_signature)?;
-                _aidl_data.write(&_arg_entropy)?;
-                _aidl_data.write_slice_size(_arg_output.as_deref())?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreOperation>::getDefaultImpl() {
-                  return _aidl_default_impl.finish(_arg_input, _arg_signature, _arg_entropy, _arg_output);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              *_arg_output = _aidl_reply.read()?;
-              Ok(())
-            }
-            fn abort(&self) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_abort, 0, |_aidl_data| {
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreOperation>::getDefaultImpl() {
-                  return _aidl_default_impl.abort();
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              Ok(())
-            }
-          }
-          impl IKeystoreOperation for binder::Binder<BnKeystoreOperation> {
-            fn update(&self, _arg_input: Option<&[u8]>, _arg_aadInput: Option<&[u8]>, _arg_output: &mut Option<Vec<u8>>) -> binder::public_api::Result<()> { self.0.update(_arg_input, _arg_aadInput, _arg_output) }
-            fn finish(&self, _arg_input: Option<&[u8]>, _arg_signature: Option<&[u8]>, _arg_entropy: Option<&[u8]>, _arg_output: &mut Option<Vec<u8>>) -> binder::public_api::Result<()> { self.0.finish(_arg_input, _arg_signature, _arg_entropy, _arg_output) }
-            fn abort(&self) -> binder::public_api::Result<()> { self.0.abort() }
-          }
-          fn on_transact(_aidl_service: &dyn IKeystoreOperation, _aidl_code: binder::TransactionCode, _aidl_data: &binder::parcel::Parcel, _aidl_reply: &mut binder::parcel::Parcel) -> binder::Result<()> {
-            match _aidl_code {
-              TRANSACTION_update => {
-                let _arg_input: Option<Vec<u8>> = _aidl_data.read()?;
-                let _arg_aadInput: Option<Vec<u8>> = _aidl_data.read()?;
-                let mut _arg_output: Option<Vec<u8>> = Default::default();
-                _aidl_data.resize_nullable_out_vec(&mut _arg_output)?;
-                let _aidl_return = _aidl_service.update(_arg_input.as_deref(), _arg_aadInput.as_deref(), &mut _arg_output);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                    _aidl_reply.write(&_arg_output)?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              TRANSACTION_finish => {
-                let _arg_input: Option<Vec<u8>> = _aidl_data.read()?;
-                let _arg_signature: Option<Vec<u8>> = _aidl_data.read()?;
-                let _arg_entropy: Option<Vec<u8>> = _aidl_data.read()?;
-                let mut _arg_output: Option<Vec<u8>> = Default::default();
-                _aidl_data.resize_nullable_out_vec(&mut _arg_output)?;
-                let _aidl_return = _aidl_service.finish(_arg_input.as_deref(), _arg_signature.as_deref(), _arg_entropy.as_deref(), &mut _arg_output);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                    _aidl_reply.write(&_arg_output)?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              TRANSACTION_abort => {
-                let _aidl_return = _aidl_service.abort();
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              _ => Err(binder::StatusCode::UNKNOWN_TRANSACTION)
-            }
-          }
-        }
-        pub mod IKeystoreSecurityLevel {
-          #![allow(non_upper_case_globals)]
-          #![allow(non_snake_case)]
-          #[allow(unused_imports)] use binder::IBinder;
-          use binder::declare_binder_interface;
-          declare_binder_interface! {
-            IKeystoreSecurityLevel["android.security.keystore2.IKeystoreSecurityLevel"] {
-              native: BnKeystoreSecurityLevel(on_transact),
-              proxy: BpKeystoreSecurityLevel {
-              },
-            }
-          }
-          pub trait IKeystoreSecurityLevel: binder::Interface + Send {
-            fn get_descriptor() -> &'static str where Self: Sized { "android.security.keystore2.IKeystoreSecurityLevel" }
-            fn create(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_operationParameters: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_forced: bool, _arg_challenge: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_18_OperationChallenge>) -> binder::public_api::Result<Box<dyn crate::mangled::_7_android_8_security_9_keystore2_18_IKeystoreOperation>> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn updateSubcomponent(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: Option<&crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: Option<&crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn generateKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_params: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_entropy: &[u8], _arg_resultKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn importKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_params: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_keyData: &[u8], _arg_resultKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn importWrappedKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_wrappingKey: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_maskingKey: &[u8], _arg_params: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_authenticators: &[crate::mangled::_7_android_8_security_9_keystore2_17_AuthenticatorSpec], _arg_resultKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn getDefaultImpl() -> DefaultImpl where Self: Sized {
-              DEFAULT_IMPL.lock().unwrap().clone()
-            }
-            fn setDefaultImpl(d: DefaultImpl) -> DefaultImpl where Self: Sized {
-              std::mem::replace(&mut *DEFAULT_IMPL.lock().unwrap(), d)
-            }
-          }
-          pub const TRANSACTION_create: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 0;
-          pub const TRANSACTION_updateSubcomponent: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 1;
-          pub const TRANSACTION_generateKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 2;
-          pub const TRANSACTION_importKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 3;
-          pub const TRANSACTION_importWrappedKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 4;
-          pub type DefaultImpl = Option<std::sync::Arc<dyn IKeystoreSecurityLevel + Sync>>;
-          use lazy_static::lazy_static;
-          lazy_static! {
-            static ref DEFAULT_IMPL: std::sync::Mutex<DefaultImpl> = std::sync::Mutex::new(None);
-          }
-          pub(crate) mod mangled { pub use super::IKeystoreSecurityLevel as _7_android_8_security_9_keystore2_22_IKeystoreSecurityLevel; }
-          impl IKeystoreSecurityLevel for BpKeystoreSecurityLevel {
-            fn create(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_operationParameters: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_forced: bool, _arg_challenge: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_18_OperationChallenge>) -> binder::public_api::Result<Box<dyn crate::mangled::_7_android_8_security_9_keystore2_18_IKeystoreOperation>> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_create, 0, |_aidl_data| {
-                _aidl_data.write(_arg_key)?;
-                _aidl_data.write(_arg_operationParameters)?;
-                _aidl_data.write(&_arg_forced)?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreSecurityLevel>::getDefaultImpl() {
-                  return _aidl_default_impl.create(_arg_key, _arg_operationParameters, _arg_forced, _arg_challenge);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              let _aidl_return: Box<dyn crate::mangled::_7_android_8_security_9_keystore2_18_IKeystoreOperation> = _aidl_reply.read()?;
-              *_arg_challenge = _aidl_reply.read()?;
-              Ok(_aidl_return)
-            }
-            fn updateSubcomponent(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: Option<&crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: Option<&crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_updateSubcomponent, 0, |_aidl_data| {
-                _aidl_data.write(_arg_key)?;
-                _aidl_data.write(&_arg_publicCert)?;
-                _aidl_data.write(&_arg_certificateChain)?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreSecurityLevel>::getDefaultImpl() {
-                  return _aidl_default_impl.updateSubcomponent(_arg_key, _arg_publicCert, _arg_certificateChain);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              Ok(())
-            }
-            fn generateKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_params: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_entropy: &[u8], _arg_resultKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_generateKey, 0, |_aidl_data| {
-                _aidl_data.write(_arg_key)?;
-                _aidl_data.write(_arg_params)?;
-                _aidl_data.write(_arg_entropy)?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreSecurityLevel>::getDefaultImpl() {
-                  return _aidl_default_impl.generateKey(_arg_key, _arg_params, _arg_entropy, _arg_resultKey, _arg_publicCert, _arg_certificateChain);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              *_arg_resultKey = _aidl_reply.read()?;
-              *_arg_publicCert = _aidl_reply.read()?;
-              *_arg_certificateChain = _aidl_reply.read()?;
-              Ok(())
-            }
-            fn importKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_params: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_keyData: &[u8], _arg_resultKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_importKey, 0, |_aidl_data| {
-                _aidl_data.write(_arg_key)?;
-                _aidl_data.write(_arg_params)?;
-                _aidl_data.write(_arg_keyData)?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreSecurityLevel>::getDefaultImpl() {
-                  return _aidl_default_impl.importKey(_arg_key, _arg_params, _arg_keyData, _arg_resultKey, _arg_publicCert, _arg_certificateChain);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              *_arg_resultKey = _aidl_reply.read()?;
-              *_arg_publicCert = _aidl_reply.read()?;
-              *_arg_certificateChain = _aidl_reply.read()?;
-              Ok(())
-            }
-            fn importWrappedKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_wrappingKey: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_maskingKey: &[u8], _arg_params: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_authenticators: &[crate::mangled::_7_android_8_security_9_keystore2_17_AuthenticatorSpec], _arg_resultKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_importWrappedKey, 0, |_aidl_data| {
-                _aidl_data.write(_arg_key)?;
-                _aidl_data.write(_arg_wrappingKey)?;
-                _aidl_data.write(_arg_maskingKey)?;
-                _aidl_data.write(_arg_params)?;
-                _aidl_data.write(_arg_authenticators)?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreSecurityLevel>::getDefaultImpl() {
-                  return _aidl_default_impl.importWrappedKey(_arg_key, _arg_wrappingKey, _arg_maskingKey, _arg_params, _arg_authenticators, _arg_resultKey, _arg_publicCert, _arg_certificateChain);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              *_arg_resultKey = _aidl_reply.read()?;
-              *_arg_publicCert = _aidl_reply.read()?;
-              *_arg_certificateChain = _aidl_reply.read()?;
-              Ok(())
-            }
-          }
-          impl IKeystoreSecurityLevel for binder::Binder<BnKeystoreSecurityLevel> {
-            fn create(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_operationParameters: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_forced: bool, _arg_challenge: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_18_OperationChallenge>) -> binder::public_api::Result<Box<dyn crate::mangled::_7_android_8_security_9_keystore2_18_IKeystoreOperation>> { self.0.create(_arg_key, _arg_operationParameters, _arg_forced, _arg_challenge) }
-            fn updateSubcomponent(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: Option<&crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: Option<&crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> { self.0.updateSubcomponent(_arg_key, _arg_publicCert, _arg_certificateChain) }
-            fn generateKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_params: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_entropy: &[u8], _arg_resultKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> { self.0.generateKey(_arg_key, _arg_params, _arg_entropy, _arg_resultKey, _arg_publicCert, _arg_certificateChain) }
-            fn importKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_params: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_keyData: &[u8], _arg_resultKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> { self.0.importKey(_arg_key, _arg_params, _arg_keyData, _arg_resultKey, _arg_publicCert, _arg_certificateChain) }
-            fn importWrappedKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_wrappingKey: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_maskingKey: &[u8], _arg_params: &[crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter], _arg_authenticators: &[crate::mangled::_7_android_8_security_9_keystore2_17_AuthenticatorSpec], _arg_resultKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<()> { self.0.importWrappedKey(_arg_key, _arg_wrappingKey, _arg_maskingKey, _arg_params, _arg_authenticators, _arg_resultKey, _arg_publicCert, _arg_certificateChain) }
-          }
-          fn on_transact(_aidl_service: &dyn IKeystoreSecurityLevel, _aidl_code: binder::TransactionCode, _aidl_data: &binder::parcel::Parcel, _aidl_reply: &mut binder::parcel::Parcel) -> binder::Result<()> {
-            match _aidl_code {
-              TRANSACTION_create => {
-                let _arg_key: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = _aidl_data.read()?;
-                let _arg_operationParameters: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter> = _aidl_data.read()?;
-                let _arg_forced: bool = _aidl_data.read()?;
-                let mut _arg_challenge: Option<crate::mangled::_7_android_8_security_9_keystore2_18_OperationChallenge> = Default::default();
-                let _aidl_return = _aidl_service.create(&_arg_key, &_arg_operationParameters, _arg_forced, &mut _arg_challenge);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                    _aidl_reply.write(_aidl_return)?;
-                    _aidl_reply.write(&_arg_challenge)?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              TRANSACTION_updateSubcomponent => {
-                let _arg_key: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = _aidl_data.read()?;
-                let _arg_publicCert: Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate> = _aidl_data.read()?;
-                let _arg_certificateChain: Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain> = _aidl_data.read()?;
-                let _aidl_return = _aidl_service.updateSubcomponent(&_arg_key, _arg_publicCert.as_ref(), _arg_certificateChain.as_ref());
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              TRANSACTION_generateKey => {
-                let _arg_key: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = _aidl_data.read()?;
-                let _arg_params: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter> = _aidl_data.read()?;
-                let _arg_entropy: Vec<u8> = _aidl_data.read()?;
-                let mut _arg_resultKey: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = Default::default();
-                let mut _arg_publicCert: Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate> = Default::default();
-                let mut _arg_certificateChain: Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain> = Default::default();
-                let _aidl_return = _aidl_service.generateKey(&_arg_key, &_arg_params, &_arg_entropy, &mut _arg_resultKey, &mut _arg_publicCert, &mut _arg_certificateChain);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                    _aidl_reply.write(&_arg_resultKey)?;
-                    _aidl_reply.write(&_arg_publicCert)?;
-                    _aidl_reply.write(&_arg_certificateChain)?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              TRANSACTION_importKey => {
-                let _arg_key: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = _aidl_data.read()?;
-                let _arg_params: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter> = _aidl_data.read()?;
-                let _arg_keyData: Vec<u8> = _aidl_data.read()?;
-                let mut _arg_resultKey: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = Default::default();
-                let mut _arg_publicCert: Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate> = Default::default();
-                let mut _arg_certificateChain: Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain> = Default::default();
-                let _aidl_return = _aidl_service.importKey(&_arg_key, &_arg_params, &_arg_keyData, &mut _arg_resultKey, &mut _arg_publicCert, &mut _arg_certificateChain);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                    _aidl_reply.write(&_arg_resultKey)?;
-                    _aidl_reply.write(&_arg_publicCert)?;
-                    _aidl_reply.write(&_arg_certificateChain)?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              TRANSACTION_importWrappedKey => {
-                let _arg_key: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = _aidl_data.read()?;
-                let _arg_wrappingKey: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = _aidl_data.read()?;
-                let _arg_maskingKey: Vec<u8> = _aidl_data.read()?;
-                let _arg_params: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter> = _aidl_data.read()?;
-                let _arg_authenticators: Vec<crate::mangled::_7_android_8_security_9_keystore2_17_AuthenticatorSpec> = _aidl_data.read()?;
-                let mut _arg_resultKey: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = Default::default();
-                let mut _arg_publicCert: Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate> = Default::default();
-                let mut _arg_certificateChain: Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain> = Default::default();
-                let _aidl_return = _aidl_service.importWrappedKey(&_arg_key, &_arg_wrappingKey, &_arg_maskingKey, &_arg_params, &_arg_authenticators, &mut _arg_resultKey, &mut _arg_publicCert, &mut _arg_certificateChain);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                    _aidl_reply.write(&_arg_resultKey)?;
-                    _aidl_reply.write(&_arg_publicCert)?;
-                    _aidl_reply.write(&_arg_certificateChain)?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              _ => Err(binder::StatusCode::UNKNOWN_TRANSACTION)
-            }
-          }
-        }
-        pub mod IKeystoreService {
-          #![allow(non_upper_case_globals)]
-          #![allow(non_snake_case)]
-          #[allow(unused_imports)] use binder::IBinder;
-          use binder::declare_binder_interface;
-          declare_binder_interface! {
-            IKeystoreService["android.security.keystore2.IKeystoreService"] {
-              native: BnKeystoreService(on_transact),
-              proxy: BpKeystoreService {
-              },
-            }
-          }
-          pub trait IKeystoreService: binder::Interface + Send {
-            fn get_descriptor() -> &'static str where Self: Sized { "android.security.keystore2.IKeystoreService" }
-            fn getSecurityLevel(&self, _arg_securityLevel: crate::mangled::_7_android_8_hardware_7_keymint_13_SecurityLevel) -> binder::public_api::Result<Box<dyn crate::mangled::_7_android_8_security_9_keystore2_22_IKeystoreSecurityLevel>> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn getKeyEntry(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_metadata: &mut crate::mangled::_7_android_8_security_9_keystore2_11_KeyMetadata, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<Box<dyn crate::mangled::_7_android_8_security_9_keystore2_22_IKeystoreSecurityLevel>> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn listEntries(&self, _arg_domain: crate::mangled::_7_android_8_security_9_keystore2_6_Domain, _arg_namespace_: i64) -> binder::public_api::Result<Vec<crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor>> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn deleteKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor) -> binder::public_api::Result<()> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn grant(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_granteeUid: i32, _arg_accessVector: i32, _arg_grantKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor) -> binder::public_api::Result<()> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn ungrant(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_granteeUid: i32) -> binder::public_api::Result<()> {
-              Err(binder::StatusCode::UNKNOWN_TRANSACTION.into())
-            }
-            fn getDefaultImpl() -> DefaultImpl where Self: Sized {
-              DEFAULT_IMPL.lock().unwrap().clone()
-            }
-            fn setDefaultImpl(d: DefaultImpl) -> DefaultImpl where Self: Sized {
-              std::mem::replace(&mut *DEFAULT_IMPL.lock().unwrap(), d)
-            }
-          }
-          pub const TRANSACTION_getSecurityLevel: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 0;
-          pub const TRANSACTION_getKeyEntry: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 1;
-          pub const TRANSACTION_listEntries: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 2;
-          pub const TRANSACTION_deleteKey: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 3;
-          pub const TRANSACTION_grant: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 4;
-          pub const TRANSACTION_ungrant: binder::TransactionCode = binder::SpIBinder::FIRST_CALL_TRANSACTION + 5;
-          pub type DefaultImpl = Option<std::sync::Arc<dyn IKeystoreService + Sync>>;
-          use lazy_static::lazy_static;
-          lazy_static! {
-            static ref DEFAULT_IMPL: std::sync::Mutex<DefaultImpl> = std::sync::Mutex::new(None);
-          }
-          pub(crate) mod mangled { pub use super::IKeystoreService as _7_android_8_security_9_keystore2_16_IKeystoreService; }
-          impl IKeystoreService for BpKeystoreService {
-            fn getSecurityLevel(&self, _arg_securityLevel: crate::mangled::_7_android_8_hardware_7_keymint_13_SecurityLevel) -> binder::public_api::Result<Box<dyn crate::mangled::_7_android_8_security_9_keystore2_22_IKeystoreSecurityLevel>> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_getSecurityLevel, 0, |_aidl_data| {
-                _aidl_data.write(&_arg_securityLevel)?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreService>::getDefaultImpl() {
-                  return _aidl_default_impl.getSecurityLevel(_arg_securityLevel);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              let _aidl_return: Box<dyn crate::mangled::_7_android_8_security_9_keystore2_22_IKeystoreSecurityLevel> = _aidl_reply.read()?;
-              Ok(_aidl_return)
-            }
-            fn getKeyEntry(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_metadata: &mut crate::mangled::_7_android_8_security_9_keystore2_11_KeyMetadata, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<Box<dyn crate::mangled::_7_android_8_security_9_keystore2_22_IKeystoreSecurityLevel>> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_getKeyEntry, 0, |_aidl_data| {
-                _aidl_data.write(_arg_key)?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreService>::getDefaultImpl() {
-                  return _aidl_default_impl.getKeyEntry(_arg_key, _arg_metadata, _arg_publicCert, _arg_certificateChain);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              let _aidl_return: Box<dyn crate::mangled::_7_android_8_security_9_keystore2_22_IKeystoreSecurityLevel> = _aidl_reply.read()?;
-              *_arg_metadata = _aidl_reply.read()?;
-              *_arg_publicCert = _aidl_reply.read()?;
-              *_arg_certificateChain = _aidl_reply.read()?;
-              Ok(_aidl_return)
-            }
-            fn listEntries(&self, _arg_domain: crate::mangled::_7_android_8_security_9_keystore2_6_Domain, _arg_namespace_: i64) -> binder::public_api::Result<Vec<crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor>> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_listEntries, 0, |_aidl_data| {
-                _aidl_data.write(&_arg_domain)?;
-                _aidl_data.write(&_arg_namespace_)?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreService>::getDefaultImpl() {
-                  return _aidl_default_impl.listEntries(_arg_domain, _arg_namespace_);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              let _aidl_return: Vec<crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor> = _aidl_reply.read()?;
-              Ok(_aidl_return)
-            }
-            fn deleteKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_deleteKey, 0, |_aidl_data| {
-                _aidl_data.write(_arg_key)?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreService>::getDefaultImpl() {
-                  return _aidl_default_impl.deleteKey(_arg_key);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              Ok(())
-            }
-            fn grant(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_granteeUid: i32, _arg_accessVector: i32, _arg_grantKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_grant, 0, |_aidl_data| {
-                _aidl_data.write(_arg_key)?;
-                _aidl_data.write(&_arg_granteeUid)?;
-                _aidl_data.write(&_arg_accessVector)?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreService>::getDefaultImpl() {
-                  return _aidl_default_impl.grant(_arg_key, _arg_granteeUid, _arg_accessVector, _arg_grantKey);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              *_arg_grantKey = _aidl_reply.read()?;
-              Ok(())
-            }
-            fn ungrant(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_granteeUid: i32) -> binder::public_api::Result<()> {
-              let _aidl_reply = self.binder.transact(TRANSACTION_ungrant, 0, |_aidl_data| {
-                _aidl_data.write(_arg_key)?;
-                _aidl_data.write(&_arg_granteeUid)?;
-                Ok(())
-              });
-              if let Err(binder::StatusCode::UNKNOWN_TRANSACTION) = _aidl_reply {
-                if let Some(_aidl_default_impl) = <Self as IKeystoreService>::getDefaultImpl() {
-                  return _aidl_default_impl.ungrant(_arg_key, _arg_granteeUid);
-                }
-              }
-              let _aidl_reply = _aidl_reply?;
-              let _aidl_status: binder::Status = _aidl_reply.read()?;
-              if !_aidl_status.is_ok() { return Err(_aidl_status); }
-              Ok(())
-            }
-          }
-          impl IKeystoreService for binder::Binder<BnKeystoreService> {
-            fn getSecurityLevel(&self, _arg_securityLevel: crate::mangled::_7_android_8_hardware_7_keymint_13_SecurityLevel) -> binder::public_api::Result<Box<dyn crate::mangled::_7_android_8_security_9_keystore2_22_IKeystoreSecurityLevel>> { self.0.getSecurityLevel(_arg_securityLevel) }
-            fn getKeyEntry(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_metadata: &mut crate::mangled::_7_android_8_security_9_keystore2_11_KeyMetadata, _arg_publicCert: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate>, _arg_certificateChain: &mut Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain>) -> binder::public_api::Result<Box<dyn crate::mangled::_7_android_8_security_9_keystore2_22_IKeystoreSecurityLevel>> { self.0.getKeyEntry(_arg_key, _arg_metadata, _arg_publicCert, _arg_certificateChain) }
-            fn listEntries(&self, _arg_domain: crate::mangled::_7_android_8_security_9_keystore2_6_Domain, _arg_namespace_: i64) -> binder::public_api::Result<Vec<crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor>> { self.0.listEntries(_arg_domain, _arg_namespace_) }
-            fn deleteKey(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor) -> binder::public_api::Result<()> { self.0.deleteKey(_arg_key) }
-            fn grant(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_granteeUid: i32, _arg_accessVector: i32, _arg_grantKey: &mut crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor) -> binder::public_api::Result<()> { self.0.grant(_arg_key, _arg_granteeUid, _arg_accessVector, _arg_grantKey) }
-            fn ungrant(&self, _arg_key: &crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, _arg_granteeUid: i32) -> binder::public_api::Result<()> { self.0.ungrant(_arg_key, _arg_granteeUid) }
-          }
-          fn on_transact(_aidl_service: &dyn IKeystoreService, _aidl_code: binder::TransactionCode, _aidl_data: &binder::parcel::Parcel, _aidl_reply: &mut binder::parcel::Parcel) -> binder::Result<()> {
-            match _aidl_code {
-              TRANSACTION_getSecurityLevel => {
-                let _arg_securityLevel: crate::mangled::_7_android_8_hardware_7_keymint_13_SecurityLevel = _aidl_data.read()?;
-                let _aidl_return = _aidl_service.getSecurityLevel(_arg_securityLevel);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                    _aidl_reply.write(_aidl_return)?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              TRANSACTION_getKeyEntry => {
-                let _arg_key: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = _aidl_data.read()?;
-                let mut _arg_metadata: crate::mangled::_7_android_8_security_9_keystore2_11_KeyMetadata = Default::default();
-                let mut _arg_publicCert: Option<crate::mangled::_7_android_8_security_9_keystore2_11_Certificate> = Default::default();
-                let mut _arg_certificateChain: Option<crate::mangled::_7_android_8_security_9_keystore2_16_CertificateChain> = Default::default();
-                let _aidl_return = _aidl_service.getKeyEntry(&_arg_key, &mut _arg_metadata, &mut _arg_publicCert, &mut _arg_certificateChain);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                    _aidl_reply.write(_aidl_return)?;
-                    _aidl_reply.write(&_arg_metadata)?;
-                    _aidl_reply.write(&_arg_publicCert)?;
-                    _aidl_reply.write(&_arg_certificateChain)?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              TRANSACTION_listEntries => {
-                let _arg_domain: crate::mangled::_7_android_8_security_9_keystore2_6_Domain = _aidl_data.read()?;
-                let _arg_namespace_: i64 = _aidl_data.read()?;
-                let _aidl_return = _aidl_service.listEntries(_arg_domain, _arg_namespace_);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                    _aidl_reply.write(_aidl_return)?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              TRANSACTION_deleteKey => {
-                let _arg_key: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = _aidl_data.read()?;
-                let _aidl_return = _aidl_service.deleteKey(&_arg_key);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              TRANSACTION_grant => {
-                let _arg_key: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = _aidl_data.read()?;
-                let _arg_granteeUid: i32 = _aidl_data.read()?;
-                let _arg_accessVector: i32 = _aidl_data.read()?;
-                let mut _arg_grantKey: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = Default::default();
-                let _aidl_return = _aidl_service.grant(&_arg_key, _arg_granteeUid, _arg_accessVector, &mut _arg_grantKey);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                    _aidl_reply.write(&_arg_grantKey)?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              TRANSACTION_ungrant => {
-                let _arg_key: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor = _aidl_data.read()?;
-                let _arg_granteeUid: i32 = _aidl_data.read()?;
-                let _aidl_return = _aidl_service.ungrant(&_arg_key, _arg_granteeUid);
-                match &_aidl_return {
-                  Ok(_aidl_return) => {
-                    _aidl_reply.write(&binder::Status::from(binder::StatusCode::OK))?;
-                  }
-                  Err(_aidl_status) => _aidl_reply.write(_aidl_status)?
-                }
-                Ok(())
-              }
-              _ => Err(binder::StatusCode::UNKNOWN_TRANSACTION)
-            }
-          }
-        }
-        pub mod KeyDescriptor {
-          #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
-          pub struct KeyDescriptor {
-            pub domain: crate::mangled::_7_android_8_security_9_keystore2_6_Domain, 
-            pub namespace_: i64, 
-            pub alias: Option<String>, 
-            pub blob: Option<Vec<u8>>, 
-          }
-          pub(crate) mod mangled { pub use super::KeyDescriptor as _7_android_8_security_9_keystore2_13_KeyDescriptor; }
-          impl Default for KeyDescriptor {
-            fn default() -> Self {
-              Self {
-                domain: Default::default(),
-                namespace_: 0,
-                alias: Default::default(),
-                blob: Default::default(),
-              }
-            }
-          }
-          impl binder::parcel::Serialize for KeyDescriptor {
-            fn serialize(&self, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              <Self as binder::parcel::SerializeOption>::serialize_option(Some(self), parcel)
-            }
-          }
-          impl binder::parcel::SerializeArray for KeyDescriptor {}
-          impl binder::parcel::SerializeOption for KeyDescriptor {
-            fn serialize_option(this: Option<&Self>, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              let this = if let Some(this) = this {
-                parcel.write(&1i32)?;
-                this
-              } else {
-                return parcel.write(&0i32);
-              };
-              let start_pos = parcel.get_data_position();
-              parcel.write(&0i32)?;
-              parcel.write(&this.domain)?;
-              parcel.write(&this.namespace_)?;
-              parcel.write(&this.alias)?;
-              parcel.write(&this.blob)?;
-              let end_pos = parcel.get_data_position();
-              let parcelable_size = (end_pos - start_pos) as i32;
-              unsafe { parcel.set_data_position(start_pos)?; }
-              parcel.write(&parcelable_size)?;
-              unsafe { parcel.set_data_position(end_pos)?; }
-              Ok(())
-            }
-          }
-          impl binder::parcel::Deserialize for KeyDescriptor {
-            fn deserialize(parcel: &binder::parcel::Parcel) -> binder::Result<Self> {
-              <Self as binder::parcel::DeserializeOption>::deserialize_option(parcel)
-                 .transpose()
-                 .unwrap_or(Err(binder::StatusCode::UNEXPECTED_NULL))
-            }
-          }
-          impl binder::parcel::DeserializeArray for KeyDescriptor {}
-          impl binder::parcel::DeserializeOption for KeyDescriptor {
-            fn deserialize_option(parcel: &binder::parcel::Parcel) -> binder::Result<Option<Self>> {
-              let status: i32 = parcel.read()?;
-              if status == 0 { return Ok(None); }
-              let start_pos = parcel.get_data_position();
-              let parcelable_size: i32 = parcel.read()?;
-              if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
-              let mut result = Self::default();
-              result.domain = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              result.namespace_ = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              result.alias = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              result.blob = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              Ok(Some(result))
-            }
-          }
-        }
-        pub mod KeyMetadata {
-          pub struct KeyMetadata {
-            pub key: crate::mangled::_7_android_8_security_9_keystore2_13_KeyDescriptor, 
-            pub securityLevel: crate::mangled::_7_android_8_hardware_7_keymint_13_SecurityLevel, 
-            pub hardwareEnforced: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter>, 
-            pub softwareEnforced: Vec<crate::mangled::_7_android_8_hardware_7_keymint_12_KeyParameter>, 
-          }
-          pub(crate) mod mangled { pub use super::KeyMetadata as _7_android_8_security_9_keystore2_11_KeyMetadata; }
-          impl Default for KeyMetadata {
-            fn default() -> Self {
-              Self {
-                key: Default::default(),
-                securityLevel: Default::default(),
-                hardwareEnforced: Default::default(),
-                softwareEnforced: Default::default(),
-              }
-            }
-          }
-          impl binder::parcel::Serialize for KeyMetadata {
-            fn serialize(&self, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              <Self as binder::parcel::SerializeOption>::serialize_option(Some(self), parcel)
-            }
-          }
-          impl binder::parcel::SerializeArray for KeyMetadata {}
-          impl binder::parcel::SerializeOption for KeyMetadata {
-            fn serialize_option(this: Option<&Self>, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              let this = if let Some(this) = this {
-                parcel.write(&1i32)?;
-                this
-              } else {
-                return parcel.write(&0i32);
-              };
-              let start_pos = parcel.get_data_position();
-              parcel.write(&0i32)?;
-              parcel.write(&this.key)?;
-              parcel.write(&this.securityLevel)?;
-              parcel.write(&this.hardwareEnforced)?;
-              parcel.write(&this.softwareEnforced)?;
-              let end_pos = parcel.get_data_position();
-              let parcelable_size = (end_pos - start_pos) as i32;
-              unsafe { parcel.set_data_position(start_pos)?; }
-              parcel.write(&parcelable_size)?;
-              unsafe { parcel.set_data_position(end_pos)?; }
-              Ok(())
-            }
-          }
-          impl binder::parcel::Deserialize for KeyMetadata {
-            fn deserialize(parcel: &binder::parcel::Parcel) -> binder::Result<Self> {
-              <Self as binder::parcel::DeserializeOption>::deserialize_option(parcel)
-                 .transpose()
-                 .unwrap_or(Err(binder::StatusCode::UNEXPECTED_NULL))
-            }
-          }
-          impl binder::parcel::DeserializeArray for KeyMetadata {}
-          impl binder::parcel::DeserializeOption for KeyMetadata {
-            fn deserialize_option(parcel: &binder::parcel::Parcel) -> binder::Result<Option<Self>> {
-              let status: i32 = parcel.read()?;
-              if status == 0 { return Ok(None); }
-              let start_pos = parcel.get_data_position();
-              let parcelable_size: i32 = parcel.read()?;
-              if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
-              let mut result = Self::default();
-              result.key = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              result.securityLevel = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              result.hardwareEnforced = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              result.softwareEnforced = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              Ok(Some(result))
-            }
-          }
-        }
-        pub mod KeyPermission {
-          #![allow(non_upper_case_globals)]
-          pub type KeyPermission = i32;
-          pub const None: KeyPermission = 0;
-          pub const Delete: KeyPermission = 1;
-          pub const GenUniqueId: KeyPermission = 2;
-          pub const GetInfo: KeyPermission = 4;
-          pub const Grant: KeyPermission = 8;
-          pub const ManageBlob: KeyPermission = 16;
-          pub const Rebind: KeyPermission = 32;
-          pub const ReqForcedOp: KeyPermission = 64;
-          pub const Update: KeyPermission = 128;
-          pub const Use: KeyPermission = 256;
-          pub const UseDevId: KeyPermission = 512;
-          pub(crate) mod mangled { pub use super::KeyPermission as _7_android_8_security_9_keystore2_13_KeyPermission; }
-        }
-        pub mod OperationChallenge {
-          pub struct OperationChallenge {
-            pub challenge: i64, 
-          }
-          pub(crate) mod mangled { pub use super::OperationChallenge as _7_android_8_security_9_keystore2_18_OperationChallenge; }
-          impl Default for OperationChallenge {
-            fn default() -> Self {
-              Self {
-                challenge: 0,
-              }
-            }
-          }
-          impl binder::parcel::Serialize for OperationChallenge {
-            fn serialize(&self, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              <Self as binder::parcel::SerializeOption>::serialize_option(Some(self), parcel)
-            }
-          }
-          impl binder::parcel::SerializeArray for OperationChallenge {}
-          impl binder::parcel::SerializeOption for OperationChallenge {
-            fn serialize_option(this: Option<&Self>, parcel: &mut binder::parcel::Parcel) -> binder::Result<()> {
-              let this = if let Some(this) = this {
-                parcel.write(&1i32)?;
-                this
-              } else {
-                return parcel.write(&0i32);
-              };
-              let start_pos = parcel.get_data_position();
-              parcel.write(&0i32)?;
-              parcel.write(&this.challenge)?;
-              let end_pos = parcel.get_data_position();
-              let parcelable_size = (end_pos - start_pos) as i32;
-              unsafe { parcel.set_data_position(start_pos)?; }
-              parcel.write(&parcelable_size)?;
-              unsafe { parcel.set_data_position(end_pos)?; }
-              Ok(())
-            }
-          }
-          impl binder::parcel::Deserialize for OperationChallenge {
-            fn deserialize(parcel: &binder::parcel::Parcel) -> binder::Result<Self> {
-              <Self as binder::parcel::DeserializeOption>::deserialize_option(parcel)
-                 .transpose()
-                 .unwrap_or(Err(binder::StatusCode::UNEXPECTED_NULL))
-            }
-          }
-          impl binder::parcel::DeserializeArray for OperationChallenge {}
-          impl binder::parcel::DeserializeOption for OperationChallenge {
-            fn deserialize_option(parcel: &binder::parcel::Parcel) -> binder::Result<Option<Self>> {
-              let status: i32 = parcel.read()?;
-              if status == 0 { return Ok(None); }
-              let start_pos = parcel.get_data_position();
-              let parcelable_size: i32 = parcel.read()?;
-              if parcelable_size < 0 { return Err(binder::StatusCode::BAD_VALUE); }
-              let mut result = Self::default();
-              result.challenge = parcel.read()?;
-              if (parcel.get_data_position() - start_pos) >= parcelable_size {
-                unsafe { parcel.set_data_position(start_pos + parcelable_size)?; }
-                return Ok(Some(result));
-              }
-              Ok(Some(result))
-            }
-          }
-        }
-        pub mod ResponseCode {
-          #![allow(non_upper_case_globals)]
-          pub type ResponseCode = i32;
-          pub const Ok: ResponseCode = 0;
-          pub const Locked: ResponseCode = 2;
-          pub const Uninitialized: ResponseCode = 3;
-          pub const SystemError: ResponseCode = 4;
-          pub const PermissionDenied: ResponseCode = 6;
-          pub const KeyNotFound: ResponseCode = 7;
-          pub const ValueCorrupted: ResponseCode = 8;
-          pub const WrongPassword: ResponseCode = 10;
-          pub const OpAuthNeeded: ResponseCode = 15;
-          pub const KeyPermanentlyInvalidated: ResponseCode = 17;
-          pub const NoSuchSecurityLevel: ResponseCode = 18;
-          pub const KeymintErrorCode: ResponseCode = 19;
-          pub const BackendBusy: ResponseCode = 20;
-          pub(crate) mod mangled { pub use super::ResponseCode as _7_android_8_security_9_keystore2_12_ResponseCode; }
-        }
-      }
-    }
-  }
-}
-pub mod mangled {
-  pub use super::aidl::android::security::keystore2::AuthenticatorSpec::mangled::*;
-  pub use super::aidl::android::security::keystore2::Certificate::mangled::*;
-  pub use super::aidl::android::security::keystore2::CertificateChain::mangled::*;
-  pub use super::aidl::android::security::keystore2::Domain::mangled::*;
-  pub use super::aidl::android::security::keystore2::IKeystoreOperation::mangled::*;
-  pub use super::aidl::android::security::keystore2::IKeystoreSecurityLevel::mangled::*;
-  pub use super::aidl::android::security::keystore2::IKeystoreService::mangled::*;
-  pub use super::aidl::android::security::keystore2::KeyDescriptor::mangled::*;
-  pub use super::aidl::android::security::keystore2::KeyMetadata::mangled::*;
-  pub use super::aidl::android::security::keystore2::KeyPermission::mangled::*;
-  pub use super::aidl::android::security::keystore2::OperationChallenge::mangled::*;
-  pub use super::aidl::android::security::keystore2::ResponseCode::mangled::*;
-  pub(crate) use android_hardware_keymint::mangled::*;
-}
diff --git a/keystore2/src/database.rs b/keystore2/src/database.rs
index ea70195..df71d94 100644
--- a/keystore2/src/database.rs
+++ b/keystore2/src/database.rs
@@ -41,14 +41,13 @@
 //! from the database module these functions take permission check
 //! callbacks.
 
-use crate::error::Error as KsError;
-use crate::key_parameter::{KeyParameter, SqlField, TagType};
-use crate::{error, permission::KeyPermSet};
+use crate::error::{Error as KsError, ResponseCode};
+use crate::key_parameter::{KeyParameter, SqlField, Tag};
+use crate::permission::KeyPermSet;
 use anyhow::{anyhow, Context, Result};
 
-use android_hardware_keymint::aidl::android::hardware::keymint::SecurityLevel::SecurityLevel as SecurityLevelType;
-use android_security_keystore2::aidl::android::security::keystore2::{
-    Domain, Domain::Domain as DomainType, KeyDescriptor::KeyDescriptor,
+use android_system_keystore2::aidl::android::system::keystore2::{
+    Domain::Domain, KeyDescriptor::KeyDescriptor, SecurityLevel::SecurityLevel,
 };
 
 #[cfg(not(test))]
@@ -99,7 +98,7 @@
     km_blob: Option<Vec<u8>>,
     cert: Option<Vec<u8>>,
     cert_chain: Option<Vec<u8>>,
-    sec_level: SecurityLevelType,
+    sec_level: SecurityLevel,
     parameters: Vec<KeyParameter>,
 }
 
@@ -133,7 +132,7 @@
         self.cert_chain.take()
     }
     /// Returns the security level of the key entry.
-    pub fn sec_level(&self) -> SecurityLevelType {
+    pub fn sec_level(&self) -> SecurityLevel {
         self.sec_level
     }
 }
@@ -261,9 +260,9 @@
     /// key artifacts, i.e., blobs and parameters have been associated with the new
     /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
     /// atomic even if key generation is not.
-    pub fn create_key_entry(&self, domain: DomainType, namespace: i64) -> Result<i64> {
+    pub fn create_key_entry(&self, domain: Domain, namespace: i64) -> Result<i64> {
         match domain {
-            Domain::App | Domain::SELinux => {}
+            Domain::APP | Domain::SELINUX => {}
             _ => {
                 return Err(KsError::sys())
                     .context(format!("Domain {:?} must be either App or SELinux.", domain));
@@ -273,7 +272,7 @@
             self.conn.execute(
                 "INSERT into persistent.keyentry (id, creation_date, domain, namespace, alias)
                      VALUES(?, datetime('now'), ?, ?, NULL);",
-                params![id, domain as i64, namespace],
+                params![id, domain.0 as u32, namespace],
             )
         })
         .context("In create_key_entry")
@@ -290,13 +289,13 @@
         key_id: i64,
         sc_type: SubComponentType,
         blob: &[u8],
-        sec_level: SecurityLevelType,
+        sec_level: SecurityLevel,
     ) -> Result<()> {
         self.conn
             .execute(
                 "INSERT into persistent.blobentry (subcomponent_type, keyentryid, blob, sec_level)
                     VALUES (?, ?, ?, ?);",
-                params![sc_type, key_id, blob, sec_level],
+                params![sc_type, key_id, blob, sec_level.0],
             )
             .context("Failed to insert blob.")?;
         Ok(())
@@ -319,8 +318,13 @@
 
         let iter = params.into_iter();
         for p in iter {
-            stmt.insert(params![key_id, p.get_tag(), p.key_parameter_value(), p.security_level()])
-                .with_context(|| format!("In insert_keyparameter: Failed to insert {:?}", p))?;
+            stmt.insert(params![
+                key_id,
+                p.get_tag().0,
+                p.key_parameter_value(),
+                p.security_level().0
+            ])
+            .with_context(|| format!("In insert_keyparameter: Failed to insert {:?}", p))?;
         }
         Ok(())
     }
@@ -332,11 +336,11 @@
         &mut self,
         newid: i64,
         alias: &str,
-        domain: DomainType,
+        domain: Domain,
         namespace: i64,
     ) -> Result<()> {
         match domain {
-            Domain::App | Domain::SELinux => {}
+            Domain::APP | Domain::SELINUX => {}
             _ => {
                 return Err(KsError::sys()).context(format!(
                     "In rebind_alias: Domain {:?} must be either App or SELinux.",
@@ -352,7 +356,7 @@
             "UPDATE persistent.keyentry
                  SET alias = NULL, domain = NULL, namespace = NULL
                  WHERE alias = ? AND domain = ? AND namespace = ?;",
-            params![alias, domain as i64, namespace],
+            params![alias, domain.0 as u32, namespace],
         )
         .context("In rebind_alias: Failed to rebind existing entry.")?;
         let result = tx
@@ -360,7 +364,7 @@
                 "UPDATE persistent.keyentry
                     SET alias = ?
                     WHERE id = ? AND domain = ? AND namespace = ?;",
-                params![alias, newid, domain as i64, namespace],
+                params![alias, newid, domain.0 as u32, namespace],
             )
             .context("In rebind_alias: Failed to set alias.")?;
         if result != 1 {
@@ -395,10 +399,10 @@
             )
             .context("In load_key_entry_id: Failed to select from keyentry table.")?;
         let mut rows = stmt
-            .query(params![key.domain, key.namespace_, alias])
+            .query(params![key.domain.0 as u32, key.nspace, alias])
             .context("In load_key_entry_id: Failed to read from keyentry table.")?;
         Self::with_rows_extract_one(&mut rows, |row| {
-            row.map_or_else(|| Err(KsError::Rc(error::Rc::KeyNotFound)), Ok)?
+            row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
                 .get(0)
                 .context("Failed to unpack id.")
         })
@@ -408,13 +412,13 @@
     /// This helper function completes the access tuple of a key, which is required
     /// to perform access control. The strategy depends on the `domain` field in the
     /// key descriptor.
-    /// * Domain::SELinux: The access tuple is complete and this function only loads
+    /// * Domain::SELINUX: The access tuple is complete and this function only loads
     ///       the key_id for further processing.
-    /// * Domain::App: Like Domain::SELinux, but the tuple is completed by `caller_uid`
+    /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
     ///       which serves as the namespace.
-    /// * Domain::Grant: The grant table is queried for the `key_id` and the
+    /// * Domain::GRANT: The grant table is queried for the `key_id` and the
     ///       `access_vector`.
-    /// * Domain::KeyId: The keyentry table is queried for the owning `domain` and
+    /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
     ///       `namespace`.
     /// In each case the information returned is sufficient to perform the access
     /// check and the key id can be used to load further key artifacts.
@@ -429,67 +433,69 @@
             // We already have the full access tuple to perform access control.
             // The only distinction is that we use the caller_uid instead
             // of the caller supplied namespace if the domain field is
-            // Domain::App.
-            Domain::App | Domain::SELinux => {
+            // Domain::APP.
+            Domain::APP | Domain::SELINUX => {
                 let mut access_key = key;
-                if access_key.domain == Domain::App {
-                    access_key.namespace_ = caller_uid as i64;
+                if access_key.domain == Domain::APP {
+                    access_key.nspace = caller_uid as i64;
                 }
                 let key_id = Self::load_key_entry_id(&access_key, &tx)
-                    .with_context(|| format!("With key.domain = {}.", access_key.domain))?;
+                    .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
 
                 Ok((key_id, access_key, None))
             }
 
-            // Domain::Grant. In this case we load the key_id and the access_vector
+            // Domain::GRANT. In this case we load the key_id and the access_vector
             // from the grant table.
-            Domain::Grant => {
+            Domain::GRANT => {
                 let mut stmt = tx
                     .prepare(
                         "SELECT keyentryid, access_vector FROM perboot.grant
                             WHERE grantee = ? AND id = ?;",
                     )
-                    .context("Domain::Grant prepare statement failed")?;
+                    .context("Domain::GRANT prepare statement failed")?;
                 let mut rows = stmt
-                    .query(params![caller_uid as i64, key.namespace_])
+                    .query(params![caller_uid as i64, key.nspace])
                     .context("Domain:Grant: query failed.")?;
                 let (key_id, access_vector): (i64, i32) =
                     Self::with_rows_extract_one(&mut rows, |row| {
-                        let r = row.map_or_else(|| Err(KsError::Rc(error::Rc::KeyNotFound)), Ok)?;
+                        let r =
+                            row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
                         Ok((
                             r.get(0).context("Failed to unpack key_id.")?,
                             r.get(1).context("Failed to unpack access_vector.")?,
                         ))
                     })
-                    .context("Domain::Grant.")?;
+                    .context("Domain::GRANT.")?;
                 Ok((key_id, key, Some(access_vector.into())))
             }
 
-            // Domain::KeyId. In this case we load the domain and namespace from the
+            // Domain::KEY_ID. In this case we load the domain and namespace from the
             // keyentry database because we need them for access control.
-            Domain::KeyId => {
+            Domain::KEY_ID => {
                 let mut stmt = tx
                     .prepare(
                         "SELECT domain, namespace FROM persistent.keyentry
                             WHERE
                             id = ?;",
                     )
-                    .context("Domain::KeyId: prepare statement failed")?;
+                    .context("Domain::KEY_ID: prepare statement failed")?;
                 let mut rows =
-                    stmt.query(params![key.namespace_]).context("Domain::KeyId: query failed.")?;
-                let (domain, namespace): (DomainType, i64) =
+                    stmt.query(params![key.nspace]).context("Domain::KEY_ID: query failed.")?;
+                let (domain, namespace): (Domain, i64) =
                     Self::with_rows_extract_one(&mut rows, |row| {
-                        let r = row.map_or_else(|| Err(KsError::Rc(error::Rc::KeyNotFound)), Ok)?;
+                        let r =
+                            row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
                         Ok((
-                            r.get(0).context("Failed to unpack domain.")?,
+                            Domain(r.get(0).context("Failed to unpack domain.")?),
                             r.get(1).context("Failed to unpack namespace.")?,
                         ))
                     })
-                    .context("Domain::KeyId.")?;
-                let key_id = key.namespace_;
+                    .context("Domain::KEY_ID.")?;
+                let key_id = key.nspace;
                 let mut access_key = key;
                 access_key.domain = domain;
-                access_key.namespace_ = namespace;
+                access_key.nspace = namespace;
 
                 Ok((key_id, access_key, None))
             }
@@ -501,7 +507,7 @@
         key_id: i64,
         load_bits: KeyEntryLoadBits,
         tx: &Transaction,
-    ) -> Result<(SecurityLevelType, Option<Vec<u8>>, Option<Vec<u8>>, Option<Vec<u8>>)> {
+    ) -> Result<(SecurityLevel, Option<Vec<u8>>, Option<Vec<u8>>, Option<Vec<u8>>)> {
         let mut stmt = tx
             .prepare(
                 "SELECT MAX(id), sec_level, subcomponent_type, blob FROM persistent.blobentry
@@ -512,7 +518,7 @@
         let mut rows =
             stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
 
-        let mut sec_level: SecurityLevelType = Default::default();
+        let mut sec_level: SecurityLevel = Default::default();
         let mut km_blob: Option<Vec<u8>> = None;
         let mut cert_blob: Option<Vec<u8>> = None;
         let mut cert_chain_blob: Option<Vec<u8>> = None;
@@ -521,7 +527,8 @@
                 row.get(2).context("Failed to extract subcomponent_type.")?;
             match (sub_type, load_bits.load_public()) {
                 (SubComponentType::KM_BLOB, _) => {
-                    sec_level = row.get(1).context("Failed to extract security level.")?;
+                    sec_level =
+                        SecurityLevel(row.get(1).context("Failed to extract security level.")?);
                     if load_bits.load_km() {
                         km_blob = Some(row.get(3).context("Failed to extract KM blob.")?);
                     }
@@ -557,8 +564,8 @@
         let mut rows =
             stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
         Self::with_rows_extract_all(&mut rows, |row| {
-            let tag: TagType = row.get(0).context("Failed to read tag.")?;
-            let sec_level: SecurityLevelType = row.get(2).context("Failed to read sec_level.")?;
+            let tag = Tag(row.get(0).context("Failed to read tag.")?);
+            let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
             parameters.push(
                 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
                     .context("Failed to read KeyParameter.")?,
@@ -634,10 +641,10 @@
         // Load the key_id and complete the access control tuple.
         // We ignore the access vector here because grants cannot be granted.
         // The access vector returned here expresses the permissions the
-        // grantee has if key.domain == Domain::Grant. But this vector
+        // grantee has if key.domain == Domain::GRANT. But this vector
         // cannot include the grant permission by design, so there is no way the
         // subsequent permission check can pass.
-        // We could check key.domain == Domain::Grant and fail early.
+        // We could check key.domain == Domain::GRANT and fail early.
         // But even if we load the access tuple by grant here, the permission
         // check denies the attempt to create a grant by grant descriptor.
         let (key_id, access_key_descriptor, _) =
@@ -681,7 +688,7 @@
         };
         tx.commit().context("In grant: failed to commit transaction.")?;
 
-        Ok(KeyDescriptor { domain: Domain::Grant, namespace_: grant_id, alias: None, blob: None })
+        Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
     }
 
     /// This function checks permissions like `grant` and `load_key_entry`
@@ -849,7 +856,7 @@
     fn test_no_persistence_for_tests() -> Result<()> {
         let db = new_test_db()?;
 
-        db.create_key_entry(Domain::App, 100)?;
+        db.create_key_entry(Domain::APP, 100)?;
         let entries = get_keyentry(&db)?;
         assert_eq!(entries.len(), 1);
         let db = new_test_db()?;
@@ -865,7 +872,7 @@
         let _file_guard_perboot = TempFile { filename: PERBOOT_TEST_SQL };
         let db = new_test_db_with_persistent_file()?;
 
-        db.create_key_entry(Domain::App, 100)?;
+        db.create_key_entry(Domain::APP, 100)?;
         let entries = get_keyentry(&db)?;
         assert_eq!(entries.len(), 1);
         let db = new_test_db_with_persistent_file()?;
@@ -877,32 +884,32 @@
 
     #[test]
     fn test_create_key_entry() -> Result<()> {
-        fn extractor(ke: &KeyEntryRow) -> (DomainType, i64, Option<&str>) {
+        fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>) {
             (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref())
         }
 
         let db = new_test_db()?;
 
-        db.create_key_entry(Domain::App, 100)?;
-        db.create_key_entry(Domain::SELinux, 101)?;
+        db.create_key_entry(Domain::APP, 100)?;
+        db.create_key_entry(Domain::SELINUX, 101)?;
 
         let entries = get_keyentry(&db)?;
         assert_eq!(entries.len(), 2);
-        assert_eq!(extractor(&entries[0]), (Domain::App, 100, None));
-        assert_eq!(extractor(&entries[1]), (Domain::SELinux, 101, None));
+        assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None));
+        assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None));
 
         // Test that we must pass in a valid Domain.
         check_result_is_error_containing_string(
-            db.create_key_entry(Domain::Grant, 102),
-            "Domain 1 must be either App or SELinux.",
+            db.create_key_entry(Domain::GRANT, 102),
+            "Domain Domain(1) must be either App or SELinux.",
         );
         check_result_is_error_containing_string(
-            db.create_key_entry(Domain::Blob, 103),
-            "Domain 3 must be either App or SELinux.",
+            db.create_key_entry(Domain::BLOB, 103),
+            "Domain Domain(3) must be either App or SELinux.",
         );
         check_result_is_error_containing_string(
-            db.create_key_entry(Domain::KeyId, 104),
-            "Domain 4 must be either App or SELinux.",
+            db.create_key_entry(Domain::KEY_ID, 104),
+            "Domain Domain(4) must be either App or SELinux.",
         );
 
         Ok(())
@@ -910,56 +917,56 @@
 
     #[test]
     fn test_rebind_alias() -> Result<()> {
-        fn extractor(ke: &KeyEntryRow) -> (Option<DomainType>, Option<i64>, Option<&str>) {
+        fn extractor(ke: &KeyEntryRow) -> (Option<Domain>, Option<i64>, Option<&str>) {
             (ke.domain, ke.namespace, ke.alias.as_deref())
         }
 
         let mut db = new_test_db()?;
-        db.create_key_entry(Domain::App, 42)?;
-        db.create_key_entry(Domain::App, 42)?;
+        db.create_key_entry(Domain::APP, 42)?;
+        db.create_key_entry(Domain::APP, 42)?;
         let entries = get_keyentry(&db)?;
         assert_eq!(entries.len(), 2);
-        assert_eq!(extractor(&entries[0]), (Some(Domain::App), Some(42), None));
-        assert_eq!(extractor(&entries[1]), (Some(Domain::App), Some(42), None));
+        assert_eq!(extractor(&entries[0]), (Some(Domain::APP), Some(42), None));
+        assert_eq!(extractor(&entries[1]), (Some(Domain::APP), Some(42), None));
 
         // Test that the first call to rebind_alias sets the alias.
-        db.rebind_alias(entries[0].id, "foo", Domain::App, 42)?;
+        db.rebind_alias(entries[0].id, "foo", Domain::APP, 42)?;
         let entries = get_keyentry(&db)?;
         assert_eq!(entries.len(), 2);
-        assert_eq!(extractor(&entries[0]), (Some(Domain::App), Some(42), Some("foo")));
-        assert_eq!(extractor(&entries[1]), (Some(Domain::App), Some(42), None));
+        assert_eq!(extractor(&entries[0]), (Some(Domain::APP), Some(42), Some("foo")));
+        assert_eq!(extractor(&entries[1]), (Some(Domain::APP), Some(42), None));
 
         // Test that the second call to rebind_alias also empties the old one.
-        db.rebind_alias(entries[1].id, "foo", Domain::App, 42)?;
+        db.rebind_alias(entries[1].id, "foo", Domain::APP, 42)?;
         let entries = get_keyentry(&db)?;
         assert_eq!(entries.len(), 2);
         assert_eq!(extractor(&entries[0]), (None, None, None));
-        assert_eq!(extractor(&entries[1]), (Some(Domain::App), Some(42), Some("foo")));
+        assert_eq!(extractor(&entries[1]), (Some(Domain::APP), Some(42), Some("foo")));
 
         // Test that we must pass in a valid Domain.
         check_result_is_error_containing_string(
-            db.rebind_alias(0, "foo", Domain::Grant, 42),
-            "Domain 1 must be either App or SELinux.",
+            db.rebind_alias(0, "foo", Domain::GRANT, 42),
+            "Domain Domain(1) must be either App or SELinux.",
         );
         check_result_is_error_containing_string(
-            db.rebind_alias(0, "foo", Domain::Blob, 42),
-            "Domain 3 must be either App or SELinux.",
+            db.rebind_alias(0, "foo", Domain::BLOB, 42),
+            "Domain Domain(3) must be either App or SELinux.",
         );
         check_result_is_error_containing_string(
-            db.rebind_alias(0, "foo", Domain::KeyId, 42),
-            "Domain 4 must be either App or SELinux.",
+            db.rebind_alias(0, "foo", Domain::KEY_ID, 42),
+            "Domain Domain(4) must be either App or SELinux.",
         );
 
         // Test that we correctly handle setting an alias for something that does not exist.
         check_result_is_error_containing_string(
-            db.rebind_alias(0, "foo", Domain::SELinux, 42),
+            db.rebind_alias(0, "foo", Domain::SELINUX, 42),
             "Expected to update a single entry but instead updated 0",
         );
         // Test that we correctly abort the transaction in this case.
         let entries = get_keyentry(&db)?;
         assert_eq!(entries.len(), 2);
         assert_eq!(extractor(&entries[0]), (None, None, None));
-        assert_eq!(extractor(&entries[1]), (Some(Domain::App), Some(42), Some("foo")));
+        assert_eq!(extractor(&entries[1]), (Some(Domain::APP), Some(42), Some("foo")));
 
         Ok(())
     }
@@ -977,8 +984,8 @@
             NO_PARAMS,
         )?;
         let app_key = KeyDescriptor {
-            domain: super::Domain::App,
-            namespace_: 0,
+            domain: super::Domain::APP,
+            nspace: 0,
             alias: Some("key".to_string()),
             blob: None,
         };
@@ -996,9 +1003,9 @@
                 assert_eq!(
                     *k,
                     KeyDescriptor {
-                        domain: super::Domain::App,
+                        domain: super::Domain::APP,
                         // namespace must be set to the caller_uid.
-                        namespace_: CALLER_UID as i64,
+                        nspace: CALLER_UID as i64,
                         alias: Some("key".to_string()),
                         blob: None,
                     }
@@ -1009,17 +1016,17 @@
         assert_eq!(
             app_granted_key,
             KeyDescriptor {
-                domain: super::Domain::Grant,
+                domain: super::Domain::GRANT,
                 // The grantid is next_random due to the mock random number generator.
-                namespace_: next_random,
+                nspace: next_random,
                 alias: None,
                 blob: None,
             }
         );
 
         let selinux_key = KeyDescriptor {
-            domain: super::Domain::SELinux,
-            namespace_: SELINUX_NAMESPACE,
+            domain: super::Domain::SELINUX,
+            nspace: SELINUX_NAMESPACE,
             alias: Some("yek".to_string()),
             blob: None,
         };
@@ -1030,10 +1037,10 @@
                 assert_eq!(
                     *k,
                     KeyDescriptor {
-                        domain: super::Domain::SELinux,
+                        domain: super::Domain::SELINUX,
                         // namespace must be the supplied SELinux
                         // namespace.
-                        namespace_: SELINUX_NAMESPACE,
+                        nspace: SELINUX_NAMESPACE,
                         alias: Some("yek".to_string()),
                         blob: None,
                     }
@@ -1044,9 +1051,9 @@
         assert_eq!(
             selinux_granted_key,
             KeyDescriptor {
-                domain: super::Domain::Grant,
+                domain: super::Domain::GRANT,
                 // The grantid is next_random + 1 due to the mock random number generator.
-                namespace_: next_random + 1,
+                nspace: next_random + 1,
                 alias: None,
                 blob: None,
             }
@@ -1059,10 +1066,10 @@
                 assert_eq!(
                     *k,
                     KeyDescriptor {
-                        domain: super::Domain::SELinux,
+                        domain: super::Domain::SELINUX,
                         // namespace must be the supplied SELinux
                         // namespace.
-                        namespace_: SELINUX_NAMESPACE,
+                        nspace: SELINUX_NAMESPACE,
                         alias: Some("yek".to_string()),
                         blob: None,
                     }
@@ -1073,9 +1080,9 @@
         assert_eq!(
             selinux_granted_key,
             KeyDescriptor {
-                domain: super::Domain::Grant,
+                domain: super::Domain::GRANT,
                 // Same grant id as before. The entry was only updated.
-                namespace_: next_random + 1,
+                nspace: next_random + 1,
                 alias: None,
                 blob: None,
             }
@@ -1120,9 +1127,19 @@
     #[test]
     fn test_insert_blob() -> Result<()> {
         let mut db = new_test_db()?;
-        db.insert_blob(1, SubComponentType::KM_BLOB, TEST_KM_BLOB, 1)?;
-        db.insert_blob(1, SubComponentType::CERT, TEST_CERT_BLOB, 2)?;
-        db.insert_blob(1, SubComponentType::CERT_CHAIN, TEST_CERT_CHAIN_BLOB, 3)?;
+        db.insert_blob(1, SubComponentType::KM_BLOB, TEST_KM_BLOB, SecurityLevel::SOFTWARE)?;
+        db.insert_blob(
+            1,
+            SubComponentType::CERT,
+            TEST_CERT_BLOB,
+            SecurityLevel::TRUSTED_ENVIRONMENT,
+        )?;
+        db.insert_blob(
+            1,
+            SubComponentType::CERT_CHAIN,
+            TEST_CERT_CHAIN_BLOB,
+            SecurityLevel::STRONGBOX,
+        )?;
 
         let mut stmt = db.conn.prepare(
             "SELECT subcomponent_type, keyentryid, blob, sec_level FROM persistent.blobentry
@@ -1133,11 +1150,11 @@
                 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
             })?;
         let r = rows.next().unwrap().unwrap();
-        assert_eq!(r, (SubComponentType::KM_BLOB, 1, TEST_KM_BLOB.to_vec(), 1));
+        assert_eq!(r, (SubComponentType::KM_BLOB, 1, TEST_KM_BLOB.to_vec(), 0));
         let r = rows.next().unwrap().unwrap();
-        assert_eq!(r, (SubComponentType::CERT, 1, TEST_CERT_BLOB.to_vec(), 2));
+        assert_eq!(r, (SubComponentType::CERT, 1, TEST_CERT_BLOB.to_vec(), 1));
         let r = rows.next().unwrap().unwrap();
-        assert_eq!(r, (SubComponentType::CERT_CHAIN, 1, TEST_CERT_CHAIN_BLOB.to_vec(), 3));
+        assert_eq!(r, (SubComponentType::CERT_CHAIN, 1, TEST_CERT_CHAIN_BLOB.to_vec(), 2));
 
         Ok(())
     }
@@ -1147,12 +1164,12 @@
     #[test]
     fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
         let mut db = new_test_db()?;
-        let key_id = make_test_key_entry(&mut db, Domain::App, 1, TEST_ALIAS)
+        let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS)
             .context("test_insert_and_load_full_keyentry_domain_app")?;
         let key_entry = db.load_key_entry(
             KeyDescriptor {
-                domain: Domain::App,
-                namespace_: 0,
+                domain: Domain::APP,
+                nspace: 0,
                 alias: Some(TEST_ALIAS.to_string()),
                 blob: None,
             },
@@ -1167,7 +1184,7 @@
                 km_blob: Some(TEST_KM_BLOB.to_vec()),
                 cert: Some(TEST_CERT_BLOB.to_vec()),
                 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
-                sec_level: 1,
+                sec_level: SecurityLevel::TRUSTED_ENVIRONMENT,
                 parameters: make_test_params()
             }
         );
@@ -1177,12 +1194,12 @@
     #[test]
     fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
         let mut db = new_test_db()?;
-        let key_id = make_test_key_entry(&mut db, Domain::SELinux, 1, TEST_ALIAS)
+        let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS)
             .context("test_insert_and_load_full_keyentry_domain_selinux")?;
         let key_entry = db.load_key_entry(
             KeyDescriptor {
-                domain: Domain::SELinux,
-                namespace_: 1,
+                domain: Domain::SELINUX,
+                nspace: 1,
                 alias: Some(TEST_ALIAS.to_string()),
                 blob: None,
             },
@@ -1197,7 +1214,7 @@
                 km_blob: Some(TEST_KM_BLOB.to_vec()),
                 cert: Some(TEST_CERT_BLOB.to_vec()),
                 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
-                sec_level: 1,
+                sec_level: SecurityLevel::TRUSTED_ENVIRONMENT,
                 parameters: make_test_params()
             }
         );
@@ -1207,10 +1224,10 @@
     #[test]
     fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
         let mut db = new_test_db()?;
-        let key_id = make_test_key_entry(&mut db, Domain::SELinux, 1, TEST_ALIAS)
+        let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS)
             .context("test_insert_and_load_full_keyentry_domain_key_id")?;
         let key_entry = db.load_key_entry(
-            KeyDescriptor { domain: Domain::KeyId, namespace_: key_id, alias: None, blob: None },
+            KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
             KeyEntryLoadBits::BOTH,
             1,
             |_k, _av| Ok(()),
@@ -1222,7 +1239,7 @@
                 km_blob: Some(TEST_KM_BLOB.to_vec()),
                 cert: Some(TEST_CERT_BLOB.to_vec()),
                 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
-                sec_level: 1,
+                sec_level: SecurityLevel::TRUSTED_ENVIRONMENT,
                 parameters: make_test_params()
             }
         );
@@ -1233,13 +1250,13 @@
     #[test]
     fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
         let mut db = new_test_db()?;
-        let key_id = make_test_key_entry(&mut db, Domain::App, 1, TEST_ALIAS)
+        let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS)
             .context("test_insert_and_load_full_keyentry_from_grant")?;
 
         let granted_key = db.grant(
             KeyDescriptor {
-                domain: Domain::App,
-                namespace_: 0,
+                domain: Domain::APP,
+                nspace: 0,
                 alias: Some(TEST_ALIAS.to_string()),
                 blob: None,
             },
@@ -1252,7 +1269,7 @@
         debug_dump_grant_table(&mut db)?;
 
         let key_entry = db.load_key_entry(granted_key, KeyEntryLoadBits::BOTH, 2, |k, av| {
-            assert_eq!(Domain::Grant, k.domain);
+            assert_eq!(Domain::GRANT, k.domain);
             assert!(av.unwrap().includes(KeyPerm::use_()));
             Ok(())
         })?;
@@ -1264,7 +1281,7 @@
                 km_blob: Some(TEST_KM_BLOB.to_vec()),
                 cert: Some(TEST_CERT_BLOB.to_vec()),
                 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
-                sec_level: 1,
+                sec_level: SecurityLevel::TRUSTED_ENVIRONMENT,
                 parameters: make_test_params()
             }
         );
@@ -1292,7 +1309,7 @@
     struct KeyEntryRow {
         id: i64,
         creation_date: String,
-        domain: Option<DomainType>,
+        domain: Option<Domain>,
         namespace: Option<i64>,
         alias: Option<String>,
     }
@@ -1304,7 +1321,10 @@
                 Ok(KeyEntryRow {
                     id: row.get(0)?,
                     creation_date: row.get(1)?,
-                    domain: row.get(2)?,
+                    domain: match row.get(2)? {
+                        Some(i) => Some(Domain(i)),
+                        None => None,
+                    },
                     namespace: row.get(3)?,
                     alias: row.get(4)?,
                 })
@@ -1537,14 +1557,29 @@
 
     fn make_test_key_entry(
         db: &mut KeystoreDB,
-        domain: DomainType,
+        domain: Domain,
         namespace: i64,
         alias: &str,
     ) -> Result<i64> {
         let key_id = db.create_key_entry(domain, namespace)?;
-        db.insert_blob(key_id, SubComponentType::KM_BLOB, TEST_KM_BLOB, 1)?;
-        db.insert_blob(key_id, SubComponentType::CERT, TEST_CERT_BLOB, 1)?;
-        db.insert_blob(key_id, SubComponentType::CERT_CHAIN, TEST_CERT_CHAIN_BLOB, 1)?;
+        db.insert_blob(
+            key_id,
+            SubComponentType::KM_BLOB,
+            TEST_KM_BLOB,
+            SecurityLevel::TRUSTED_ENVIRONMENT,
+        )?;
+        db.insert_blob(
+            key_id,
+            SubComponentType::CERT,
+            TEST_CERT_BLOB,
+            SecurityLevel::TRUSTED_ENVIRONMENT,
+        )?;
+        db.insert_blob(
+            key_id,
+            SubComponentType::CERT_CHAIN,
+            TEST_CERT_CHAIN_BLOB,
+            SecurityLevel::TRUSTED_ENVIRONMENT,
+        )?;
         db.insert_keyparameter(key_id, &make_test_params())?;
         db.rebind_alias(key_id, alias, domain, namespace)?;
         Ok(key_id)
diff --git a/keystore2/src/error.rs b/keystore2/src/error.rs
index 0326610..63ebe62 100644
--- a/keystore2/src/error.rs
+++ b/keystore2/src/error.rs
@@ -25,22 +25,19 @@
 //! This crate provides the convenience method `map_or_log_err` to convert `anyhow::Error`
 //! into this wire type. In addition to handling the conversion of `Error`
 //! to the `Result` wire type it handles any other error by mapping it to
-//! `ResponseCode::SystemError` and logs any error condition.
+//! `ResponseCode::SYSTEM_ERROR` and logs any error condition.
 //!
 //! Keystore functions should use `anyhow::Result` to return error conditions, and
 //! context should be added every time an error is forwarded.
 
 use std::cmp::PartialEq;
 
-pub use android_hardware_keymint::aidl::android::hardware::keymint::ErrorCode as Ec;
-pub use android_security_keystore2::aidl::android::security::keystore2::ResponseCode as Rc;
-
-use android_hardware_keymint::aidl::android::hardware::keymint::ErrorCode::ErrorCode;
-use android_security_keystore2::aidl::android::security::keystore2::ResponseCode::ResponseCode;
+pub use android_hardware_keymint::aidl::android::hardware::keymint::ErrorCode::ErrorCode;
+pub use android_system_keystore2::aidl::android::system::keystore2::ResponseCode::ResponseCode;
 
 use keystore2_selinux as selinux;
 
-use android_security_keystore2::binder::{
+use android_system_keystore2::binder::{
     ExceptionCode, Result as BinderResult, Status as BinderStatus,
 };
 
@@ -60,14 +57,14 @@
 }
 
 impl Error {
-    /// Short hand for `Error::Rc(ResponseCode::SystemError)`
+    /// Short hand for `Error::Rc(ResponseCode::SYSTEM_ERROR)`
     pub fn sys() -> Self {
-        Error::Rc(Rc::SystemError)
+        Error::Rc(ResponseCode::SYSTEM_ERROR)
     }
 
-    /// Short hand for `Error::Rc(ResponseCode::PermissionDenied`
+    /// Short hand for `Error::Rc(ResponseCode::PERMISSION_DENIED`
     pub fn perm() -> Self {
-        Error::Rc(Rc::PermissionDenied)
+        Error::Rc(ResponseCode::PERMISSION_DENIED)
     }
 }
 
@@ -83,7 +80,7 @@
                 let se = s.service_specific_error();
                 if se < 0 {
                     // Negative service specific errors are KM error codes.
-                    Error::Km(s.service_specific_error())
+                    Error::Km(ErrorCode(s.service_specific_error()))
                 } else {
                     // Non negative error codes cannot be KM error codes.
                     // So we create an `Error::Binder` variant to preserve
@@ -102,16 +99,16 @@
 }
 
 /// This function should be used by Keystore service calls to translate error conditions
-/// into `android.security.keystore2.Result` which is imported here as `aidl::Result`
+/// into `android.system.keystore2.Result` which is imported here as `aidl::Result`
 /// and newtyped as AidlResult.
 /// All error conditions get logged by this function.
 /// All `Error::Rc(x)` variants get mapped onto `aidl::Result{x, 0}`.
 /// All `Error::Km(x)` variants get mapped onto
 /// `aidl::Result{aidl::ResponseCode::KeymintErrorCode, x}`.
-/// `selinux::Error::perm()` is mapped on `aidl::Result{aidl::ResponseCode::PermissionDenied, 0}`.
+/// `selinux::Error::perm()` is mapped on `aidl::Result{aidl::ResponseCode::PERMISSION_DENIED, 0}`.
 ///
 /// All non `Error` error conditions get mapped onto
-/// `aidl::Result{aidl::ResponseCode::SystemError}`.
+/// `aidl::Result{aidl::ResponseCode::SYSTEM_ERROR}`.
 ///
 /// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed
 /// as argument to `handle_ok`. `handle_ok` must generate an `AidlResult`, typically
@@ -125,7 +122,7 @@
 ///     if (good_but_auth_required) {
 ///         Ok(aidl::ResponseCode::OpAuthRequired)
 ///     } else {
-///         Err(anyhow!(Error::Rc(aidl::ResponseCode::KeyNotFound)))
+///         Err(anyhow!(Error::Rc(aidl::ResponseCode::KEY_NOT_FOUND)))
 ///     }
 /// }
 ///
@@ -140,15 +137,15 @@
             log::error!("{:?}", e);
             let root_cause = e.root_cause();
             let rc = match root_cause.downcast_ref::<Error>() {
-                Some(Error::Rc(rcode)) => *rcode,
-                Some(Error::Km(ec)) => *ec,
+                Some(Error::Rc(rcode)) => rcode.0,
+                Some(Error::Km(ec)) => ec.0,
                 // If an Error::Binder reaches this stage we report a system error.
                 // The exception code and possible service specific error will be
                 // printed in the error log above.
-                Some(Error::Binder(_, _)) => Rc::SystemError,
+                Some(Error::Binder(_, _)) => ResponseCode::SYSTEM_ERROR.0,
                 None => match root_cause.downcast_ref::<selinux::Error>() {
-                    Some(selinux::Error::PermissionDenied) => Rc::PermissionDenied,
-                    _ => Rc::SystemError,
+                    Some(selinux::Error::PermissionDenied) => ResponseCode::PERMISSION_DENIED.0,
+                    _ => ResponseCode::SYSTEM_ERROR.0,
                 },
             };
             Err(BinderStatus::new_service_specific_error(rc, None))
@@ -161,7 +158,7 @@
 pub mod tests {
 
     use super::*;
-    use android_security_keystore2::binder::{
+    use android_system_keystore2::binder::{
         ExceptionCode, Result as BinderResult, Status as BinderStatus,
     };
     use anyhow::{anyhow, Context};
@@ -229,27 +226,27 @@
         );
         // All Error::Rc(x) get mapped on a service specific error
         // code of x.
-        for rc in Rc::Ok..Rc::BackendBusy {
+        for rc in ResponseCode::LOCKED.0..ResponseCode::BACKEND_BUSY.0 {
             assert_eq!(
                 Result::<(), i32>::Err(rc),
-                map_or_log_err(nested_rc(rc), |_| Err(BinderStatus::ok()))
+                map_or_log_err(nested_rc(ResponseCode(rc)), |_| Err(BinderStatus::ok()))
                     .map_err(|s| s.service_specific_error())
             );
         }
 
         // All Keystore Error::Km(x) get mapped on a service
         // specific error of x.
-        for ec in Ec::UNKNOWN_ERROR..Ec::ROOT_OF_TRUST_ALREADY_SET {
+        for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
             assert_eq!(
                 Result::<(), i32>::Err(ec),
-                map_or_log_err(nested_ec(ec), |_| Err(BinderStatus::ok()))
+                map_or_log_err(nested_ec(ErrorCode(ec)), |_| Err(BinderStatus::ok()))
                     .map_err(|s| s.service_specific_error())
             );
         }
 
         // All Keymint errors x received through a Binder Result get mapped on
         // a service specific error of x.
-        for ec in Ec::UNKNOWN_ERROR..Ec::ROOT_OF_TRUST_ALREADY_SET {
+        for ec in ErrorCode::UNKNOWN_ERROR.0..ErrorCode::ROOT_OF_TRUST_ALREADY_SET.0 {
             assert_eq!(
                 Result::<(), i32>::Err(ec),
                 map_or_log_err(
@@ -266,44 +263,47 @@
         // service specific error.
         let sse = map_km_error(binder_sse_error(1));
         assert_eq!(Err(Error::Binder(ExceptionCode::SERVICE_SPECIFIC, 1)), sse);
-        // map_or_log_err then maps it on a service specific error of Rc::SystemError.
+        // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
         assert_eq!(
-            Result::<(), i32>::Err(Rc::SystemError),
+            Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
             map_or_log_err(sse.context("Non negative service specific error."), |_| Err(
                 BinderStatus::ok()
             ))
-            .map_err(|s| s.service_specific_error())
+            .map_err(|s| ResponseCode(s.service_specific_error()))
         );
 
         // map_km_error creates a Error::Binder variant storing the given exception code.
         let binder_exception = map_km_error(binder_exception(ExceptionCode::TRANSACTION_FAILED));
         assert_eq!(Err(Error::Binder(ExceptionCode::TRANSACTION_FAILED, 0)), binder_exception);
-        // map_or_log_err then maps it on a service specific error of Rc::SystemError.
+        // map_or_log_err then maps it on a service specific error of ResponseCode::SYSTEM_ERROR.
         assert_eq!(
-            Result::<(), i32>::Err(Rc::SystemError),
+            Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
             map_or_log_err(binder_exception.context("Binder Exception."), |_| Err(
                 BinderStatus::ok()
             ))
-            .map_err(|s| s.service_specific_error())
+            .map_err(|s| ResponseCode(s.service_specific_error()))
         );
 
-        // selinux::Error::Perm() needs to be mapped to Rc::PermissionDenied
+        // selinux::Error::Perm() needs to be mapped to ResponseCode::PERMISSION_DENIED
         assert_eq!(
-            Result::<(), i32>::Err(Rc::PermissionDenied),
+            Result::<(), ResponseCode>::Err(ResponseCode::PERMISSION_DENIED),
             map_or_log_err(nested_selinux_perm(), |_| Err(BinderStatus::ok()))
-                .map_err(|s| s.service_specific_error())
+                .map_err(|s| ResponseCode(s.service_specific_error()))
         );
 
         // All other errors get mapped on System Error.
         assert_eq!(
-            Result::<(), i32>::Err(Rc::SystemError),
+            Result::<(), ResponseCode>::Err(ResponseCode::SYSTEM_ERROR),
             map_or_log_err(nested_other_error(), |_| Err(BinderStatus::ok()))
-                .map_err(|s| s.service_specific_error())
+                .map_err(|s| ResponseCode(s.service_specific_error()))
         );
 
         // Result::Ok variants get passed to the ok handler.
-        assert_eq!(Ok(Rc::OpAuthNeeded), map_or_log_err(nested_ok(Rc::OpAuthNeeded), Ok));
-        assert_eq!(Ok(Rc::Ok), map_or_log_err(nested_ok(Rc::Ok), Ok));
+        assert_eq!(Ok(ResponseCode::LOCKED), map_or_log_err(nested_ok(ResponseCode::LOCKED), Ok));
+        assert_eq!(
+            Ok(ResponseCode::SYSTEM_ERROR),
+            map_or_log_err(nested_ok(ResponseCode::SYSTEM_ERROR), Ok)
+        );
 
         Ok(())
     }
diff --git a/keystore2/src/globals.rs b/keystore2/src/globals.rs
new file mode 100644
index 0000000..0654b29
--- /dev/null
+++ b/keystore2/src/globals.rs
@@ -0,0 +1,29 @@
+// Copyright 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.
+
+//! This module holds global state of Keystore such as the thread local
+//! database connections and connections to services that Keystore needs
+//! to talk to.
+
+use crate::database::KeystoreDB;
+use std::cell::RefCell;
+
+thread_local! {
+    /// Database connections are not thread safe, but connecting to the
+    /// same database multiple times is safe as long as each connection is
+    /// used by only one thread. So we store one database connection per
+    /// thread in this thread local key.
+    pub static DB: RefCell<KeystoreDB> =
+            RefCell::new(KeystoreDB::new().expect("Failed to open database."));
+}
diff --git a/keystore2/src/key_parameter.rs b/keystore2/src/key_parameter.rs
index f08031e..8825fc9 100644
--- a/keystore2/src/key_parameter.rs
+++ b/keystore2/src/key_parameter.rs
@@ -17,18 +17,15 @@
 //! and the methods to work with KeyParameter.
 
 use crate::error::Error as KeystoreError;
-use crate::error::Rc;
+use crate::error::ResponseCode;
+
 pub use android_hardware_keymint::aidl::android::hardware::keymint::{
-    Algorithm, Algorithm::Algorithm as AlgorithmType, BlockMode,
-    BlockMode::BlockMode as BlockModeType, Digest, Digest::Digest as DigestType, EcCurve,
-    EcCurve::EcCurve as EcCurveType, HardwareAuthenticatorType,
-    HardwareAuthenticatorType::HardwareAuthenticatorType as HardwareAuthenticatorTypeType,
-    KeyOrigin, KeyOrigin::KeyOrigin as KeyOriginType,
-    KeyParameter::KeyParameter as AidlKeyParameter, KeyPurpose,
-    KeyPurpose::KeyPurpose as KeyPurposeType, PaddingMode,
-    PaddingMode::PaddingMode as PaddingModeType, SecurityLevel,
-    SecurityLevel::SecurityLevel as SecurityLevelType, Tag, Tag::Tag as TagType,
+    Algorithm::Algorithm, BlockMode::BlockMode, Digest::Digest, EcCurve::EcCurve,
+    HardwareAuthenticatorType::HardwareAuthenticatorType, KeyOrigin::KeyOrigin,
+    KeyParameter::KeyParameter as KmKeyParameter, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode,
+    Tag::Tag,
 };
+pub use android_system_keystore2::aidl::android::system::keystore2::SecurityLevel::SecurityLevel;
 use anyhow::{Context, Result};
 use rusqlite::types::{FromSql, Null, ToSql, ToSqlOutput};
 use rusqlite::{Result as SqlResult, Row};
@@ -37,7 +34,7 @@
 #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
 pub struct KeyParameter {
     key_parameter_value: KeyParameterValue,
-    security_level: SecurityLevelType,
+    security_level: SecurityLevel,
 }
 
 /// KeyParameterValue holds a value corresponding to one of the Tags defined in
@@ -47,23 +44,23 @@
     /// Associated with Tag:INVALID
     Invalid,
     /// Set of purposes for which the key may be used
-    KeyPurpose(KeyPurposeType),
+    KeyPurpose(KeyPurpose),
     /// Cryptographic algorithm with which the key is used
-    Algorithm(AlgorithmType),
+    Algorithm(Algorithm),
     /// Size of the key , in bits
     KeySize(i32),
     /// Block cipher mode(s) with which the key may be used
-    BlockMode(BlockModeType),
+    BlockMode(BlockMode),
     /// Digest algorithms that may be used with the key to perform signing and verification
-    Digest(DigestType),
+    Digest(Digest),
     /// Padding modes that may be used with the key.  Relevant to RSA, AES and 3DES keys.
-    PaddingMode(PaddingModeType),
+    PaddingMode(PaddingMode),
     /// Can the caller provide a nonce for nonce-requiring operations
     CallerNonce,
     /// Minimum length of MAC for HMAC keys and AES keys that support GCM mode
     MinMacLength(i32),
     /// The elliptic curve
-    EcCurve(EcCurveType),
+    EcCurve(EcCurve),
     /// Value of the public exponent for an RSA key pair
     RSAPublicExponent(i64),
     /// An attestation certificate for the generated key should contain an application-scoped
@@ -93,7 +90,7 @@
     /// No authentication is required to use this key
     NoAuthRequired,
     /// The types of user authenticators that may be used to authorize this key
-    HardwareAuthenticatorType(HardwareAuthenticatorTypeType),
+    HardwareAuthenticatorType(HardwareAuthenticatorType),
     /// The time in seconds for which the key is authorized for use, after user authentication
     AuthTimeout(i32),
     /// The key may be used after authentication timeout if device is still on-body
@@ -114,7 +111,7 @@
     /// Specifies the date and time the key was created
     CreationDateTime(i64),
     /// Specifies where the key was created, if known
-    KeyOrigin(KeyOriginType),
+    KeyOrigin(KeyOrigin),
     /// The key used by verified boot to validate the operating system booted
     RootOfTrust(Vec<u8>),
     /// System OS version with which the key may be used
@@ -164,12 +161,12 @@
 
 impl KeyParameter {
     /// Create an instance of KeyParameter, given the value and the security level.
-    pub fn new(key_parameter_value: KeyParameterValue, security_level: SecurityLevelType) -> Self {
+    pub fn new(key_parameter_value: KeyParameterValue, security_level: SecurityLevel) -> Self {
         KeyParameter { key_parameter_value, security_level }
     }
 
     /// Returns the tag given the KeyParameter instance.
-    pub fn get_tag(&self) -> TagType {
+    pub fn get_tag(&self) -> Tag {
         match self.key_parameter_value {
             KeyParameterValue::Invalid => Tag::INVALID,
             KeyParameterValue::KeyPurpose(_) => Tag::PURPOSE,
@@ -233,7 +230,7 @@
     }
 
     /// Returns the security level of a KeyParameter.
-    pub fn security_level(&self) -> &SecurityLevelType {
+    pub fn security_level(&self) -> &SecurityLevel {
         &self.security_level
     }
 }
@@ -264,15 +261,15 @@
     fn to_sql(&self) -> SqlResult<ToSqlOutput> {
         match self {
             KeyParameterValue::Invalid => Ok(ToSqlOutput::from(Null)),
-            KeyParameterValue::KeyPurpose(k) => Ok(ToSqlOutput::from(*k as u32)),
-            KeyParameterValue::Algorithm(a) => Ok(ToSqlOutput::from(*a as u32)),
+            KeyParameterValue::KeyPurpose(k) => Ok(ToSqlOutput::from(k.0 as u32)),
+            KeyParameterValue::Algorithm(a) => Ok(ToSqlOutput::from(a.0 as u32)),
             KeyParameterValue::KeySize(k) => Ok(ToSqlOutput::from(*k)),
-            KeyParameterValue::BlockMode(b) => Ok(ToSqlOutput::from(*b as u32)),
-            KeyParameterValue::Digest(d) => Ok(ToSqlOutput::from(*d as u32)),
-            KeyParameterValue::PaddingMode(p) => Ok(ToSqlOutput::from(*p as u32)),
+            KeyParameterValue::BlockMode(b) => Ok(ToSqlOutput::from(b.0 as u32)),
+            KeyParameterValue::Digest(d) => Ok(ToSqlOutput::from(d.0 as u32)),
+            KeyParameterValue::PaddingMode(p) => Ok(ToSqlOutput::from(p.0 as u32)),
             KeyParameterValue::CallerNonce => Ok(ToSqlOutput::from(Null)),
             KeyParameterValue::MinMacLength(m) => Ok(ToSqlOutput::from(*m)),
-            KeyParameterValue::EcCurve(e) => Ok(ToSqlOutput::from(*e as u32)),
+            KeyParameterValue::EcCurve(e) => Ok(ToSqlOutput::from(e.0 as u32)),
             KeyParameterValue::RSAPublicExponent(r) => Ok(ToSqlOutput::from(*r as i64)),
             KeyParameterValue::IncludeUniqueID => Ok(ToSqlOutput::from(Null)),
             KeyParameterValue::BootLoaderOnly => Ok(ToSqlOutput::from(Null)),
@@ -285,7 +282,7 @@
             KeyParameterValue::UserID(u) => Ok(ToSqlOutput::from(*u)),
             KeyParameterValue::UserSecureID(u) => Ok(ToSqlOutput::from(*u as i64)),
             KeyParameterValue::NoAuthRequired => Ok(ToSqlOutput::from(Null)),
-            KeyParameterValue::HardwareAuthenticatorType(h) => Ok(ToSqlOutput::from(*h as u32)),
+            KeyParameterValue::HardwareAuthenticatorType(h) => Ok(ToSqlOutput::from(h.0 as u32)),
             KeyParameterValue::AuthTimeout(m) => Ok(ToSqlOutput::from(*m)),
             KeyParameterValue::AllowWhileOnBody => Ok(ToSqlOutput::from(Null)),
             KeyParameterValue::TrustedUserPresenceRequired => Ok(ToSqlOutput::from(Null)),
@@ -294,7 +291,7 @@
             KeyParameterValue::ApplicationID(a) => Ok(ToSqlOutput::from(a.to_vec())),
             KeyParameterValue::ApplicationData(a) => Ok(ToSqlOutput::from(a.to_vec())),
             KeyParameterValue::CreationDateTime(c) => Ok(ToSqlOutput::from(*c as i64)),
-            KeyParameterValue::KeyOrigin(k) => Ok(ToSqlOutput::from(*k as u32)),
+            KeyParameterValue::KeyOrigin(k) => Ok(ToSqlOutput::from(k.0 as u32)),
             KeyParameterValue::RootOfTrust(r) => Ok(ToSqlOutput::from(r.to_vec())),
             KeyParameterValue::OSVersion(o) => Ok(ToSqlOutput::from(*o)),
             KeyParameterValue::OSPatchLevel(o) => Ok(ToSqlOutput::from(*o)),
@@ -328,25 +325,25 @@
     /// This filtering is enforced at a higher level and here we support conversion for all the
     /// variants.
     pub fn new_from_sql(
-        tag_val: TagType,
+        tag_val: Tag,
         data: &SqlField,
-        security_level_val: SecurityLevelType,
+        security_level_val: SecurityLevel,
     ) -> Result<Self> {
         let key_param_value = match tag_val {
             Tag::INVALID => KeyParameterValue::Invalid,
             Tag::PURPOSE => {
-                let key_purpose: KeyPurposeType = data
+                let key_purpose: i32 = data
                     .get()
-                    .map_err(|_| KeystoreError::Rc(Rc::ValueCorrupted))
+                    .map_err(|_| KeystoreError::Rc(ResponseCode::VALUE_CORRUPTED))
                     .context("Failed to read sql data for tag: PURPOSE.")?;
-                KeyParameterValue::KeyPurpose(key_purpose)
+                KeyParameterValue::KeyPurpose(KeyPurpose(key_purpose))
             }
             Tag::ALGORITHM => {
-                let algorithm: AlgorithmType = data
+                let algorithm: i32 = data
                     .get()
-                    .map_err(|_| KeystoreError::Rc(Rc::ValueCorrupted))
+                    .map_err(|_| KeystoreError::Rc(ResponseCode::VALUE_CORRUPTED))
                     .context("Failed to read sql data for tag: ALGORITHM.")?;
-                KeyParameterValue::Algorithm(algorithm)
+                KeyParameterValue::Algorithm(Algorithm(algorithm))
             }
             Tag::KEY_SIZE => {
                 let key_size: i32 =
@@ -354,25 +351,25 @@
                 KeyParameterValue::KeySize(key_size)
             }
             Tag::BLOCK_MODE => {
-                let block_mode: BlockModeType = data
+                let block_mode: i32 = data
                     .get()
-                    .map_err(|_| KeystoreError::Rc(Rc::ValueCorrupted))
+                    .map_err(|_| KeystoreError::Rc(ResponseCode::VALUE_CORRUPTED))
                     .context("Failed to read sql data for tag: BLOCK_MODE.")?;
-                KeyParameterValue::BlockMode(block_mode)
+                KeyParameterValue::BlockMode(BlockMode(block_mode))
             }
             Tag::DIGEST => {
-                let digest: DigestType = data
+                let digest: i32 = data
                     .get()
-                    .map_err(|_| KeystoreError::Rc(Rc::ValueCorrupted))
+                    .map_err(|_| KeystoreError::Rc(ResponseCode::VALUE_CORRUPTED))
                     .context("Failed to read sql data for tag: DIGEST.")?;
-                KeyParameterValue::Digest(digest)
+                KeyParameterValue::Digest(Digest(digest))
             }
             Tag::PADDING => {
-                let padding: PaddingModeType = data
+                let padding: i32 = data
                     .get()
-                    .map_err(|_| KeystoreError::Rc(Rc::ValueCorrupted))
+                    .map_err(|_| KeystoreError::Rc(ResponseCode::VALUE_CORRUPTED))
                     .context("Failed to read sql data for tag: PADDING.")?;
-                KeyParameterValue::PaddingMode(padding)
+                KeyParameterValue::PaddingMode(PaddingMode(padding))
             }
             Tag::CALLER_NONCE => KeyParameterValue::CallerNonce,
             Tag::MIN_MAC_LENGTH => {
@@ -381,11 +378,11 @@
                 KeyParameterValue::MinMacLength(min_mac_length)
             }
             Tag::EC_CURVE => {
-                let ec_curve: EcCurveType = data
+                let ec_curve: i32 = data
                     .get()
-                    .map_err(|_| KeystoreError::Rc(Rc::ValueCorrupted))
+                    .map_err(|_| KeystoreError::Rc(ResponseCode::VALUE_CORRUPTED))
                     .context("Failed to read sql data for tag: EC_CURVE.")?;
-                KeyParameterValue::EcCurve(ec_curve)
+                KeyParameterValue::EcCurve(EcCurve(ec_curve))
             }
             Tag::RSA_PUBLIC_EXPONENT => {
                 let rsa_pub_exponent: i64 =
@@ -436,11 +433,13 @@
             }
             Tag::NO_AUTH_REQUIRED => KeyParameterValue::NoAuthRequired,
             Tag::USER_AUTH_TYPE => {
-                let user_auth_type: HardwareAuthenticatorTypeType = data
+                let user_auth_type: i32 = data
                     .get()
-                    .map_err(|_| KeystoreError::Rc(Rc::ValueCorrupted))
+                    .map_err(|_| KeystoreError::Rc(ResponseCode::VALUE_CORRUPTED))
                     .context("Failed to read sql data for tag: USER_AUTH_TYPE.")?;
-                KeyParameterValue::HardwareAuthenticatorType(user_auth_type)
+                KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType(
+                    user_auth_type,
+                ))
             }
             Tag::AUTH_TIMEOUT => {
                 let auth_timeout: i32 =
@@ -467,11 +466,11 @@
                 KeyParameterValue::CreationDateTime(creation_datetime)
             }
             Tag::ORIGIN => {
-                let origin: KeyOriginType = data
+                let origin: i32 = data
                     .get()
-                    .map_err(|_| KeystoreError::Rc(Rc::ValueCorrupted))
+                    .map_err(|_| KeystoreError::Rc(ResponseCode::VALUE_CORRUPTED))
                     .context("Failed to read sql data for tag: ORIGIN.")?;
-                KeyParameterValue::KeyOrigin(origin)
+                KeyParameterValue::KeyOrigin(KeyOrigin(origin))
             }
             Tag::ROOT_OF_TRUST => {
                 let root_of_trust: Vec<u8> =
@@ -581,7 +580,7 @@
                 KeyParameterValue::ConfirmationToken(confirmation_token)
             }
             _ => {
-                return Err(KeystoreError::Rc(Rc::ValueCorrupted))
+                return Err(KeystoreError::Rc(ResponseCode::VALUE_CORRUPTED))
                     .context("Failed to decode Tag enum from value.")?
             }
         };
@@ -590,19 +589,20 @@
 }
 
 /// Macro rules for converting key parameter to/from wire type.
-/// This macro takes three different pieces of information about each of the KeyParameterValue
-/// variants.
-/// 1. variant name
-/// 2. tag name corresponding to the variant
-/// 3. the field name in the AidlKeyParameter struct, in which information about this variant is
-/// stored when converted
+/// This macro takes between three and four different pieces of information about each
+/// of the KeyParameterValue variants:
+/// 1. The KeyParameterValue variant name,
+/// 2. the tag name corresponding to the variant,
+/// 3. the field name in the KmKeyParameter struct, in which information about this variant is
+///    stored when converted, and
+/// 4. an optional enum type name when the nested value is of enum type.
 /// The macro takes a set of lines corresponding to each KeyParameterValue variant and generates
 /// the two conversion methods: convert_to_wire() and convert_from_wire().
 /// ## Example
 /// ```
 /// implement_key_parameter_conversion_to_from_wire! {
 ///         Invalid, INVALID, na;
-///         KeyPurpose, PURPOSE, integer;
+///         KeyPurpose, PURPOSE, integer, KeyPurpose;
 ///         CallerNonce, CALLER_NONCE, boolValue;
 ///         UserSecureID, USER_SECURE_ID, longInteger;
 ///         ApplicationID, APPLICATION_ID, blob;
@@ -611,33 +611,33 @@
 /// ```
 /// expands to:
 /// ```
-/// pub fn convert_to_wire(self) -> AidlKeyParameter {
+/// pub fn convert_to_wire(self) -> KmKeyParameter {
 ///         match self {
-///                 KeyParameterValue::Invalid => AidlKeyParameter {
+///                 KeyParameterValue::Invalid => KmKeyParameter {
 ///                         tag: Tag::INVALID,
 ///                         ..Default::default()
 ///                 },
-///                 KeyParameterValue::KeyPurpose(v) => AidlKeyParameter {
+///                 KeyParameterValue::KeyPurpose(v) => KmKeyParameter {
 ///                         tag: Tag::PURPOSE,
-///                         integer: v,
+///                         integer: v.0,
 ///                         ..Default::default()
 ///                 },
-///                 KeyParameterValue::CallerNonce => AidlKeyParameter {
+///                 KeyParameterValue::CallerNonce => KmKeyParameter {
 ///                         tag: Tag::CALLER_NONCE,
 ///                         boolValue: true,
 ///                         ..Default::default()
 ///                 },
-///                 KeyParameterValue::UserSecureID(v) => AidlKeyParameter {
+///                 KeyParameterValue::UserSecureID(v) => KmKeyParameter {
 ///                         tag: Tag::USER_SECURE_ID,
 ///                         longInteger: v,
 ///                         ..Default::default()
 ///                 },
-///                 KeyParameterValue::ApplicationID(v) => AidlKeyParameter {
+///                 KeyParameterValue::ApplicationID(v) => KmKeyParameter {
 ///                         tag: Tag::APPLICATION_ID,
 ///                         blob: v,
 ///                         ..Default::default()
 ///                 },
-///                 KeyParameterValue::ActiveDateTime(v) => AidlKeyParameter {
+///                 KeyParameterValue::ActiveDateTime(v) => KmKeyParameter {
 ///                         tag: Tag::ACTIVE_DATETIME,
 ///                         dateTime: v,
 ///                         ..Default::default()
@@ -647,33 +647,33 @@
 /// ```
 /// and
 /// ```
-/// pub fn convert_from_wire(aidl_kp: AidlKeyParameter) -> KeyParameterValue {
+/// pub fn convert_from_wire(aidl_kp: KmKeyParameter) -> KeyParameterValue {
 ///         match aidl_kp {
-///                 AidlKeyParameter {
+///                 KmKeyParameter {
 ///                         tag: Tag::INVALID,
 ///                         ..
 ///                 } => KeyParameterValue::Invalid,
-///                 AidlKeyParameter {
+///                 KmKeyParameter {
 ///                         tag: Tag::PURPOSE,
 ///                         integer: v,
 ///                         ..
-///                 } => KeyParameterValue::KeyPurpose(v),
-///                 AidlKeyParameter {
+///                 } => KeyParameterValue::KeyPurpose(KeyPurpose(v)),
+///                 KmKeyParameter {
 ///                         tag: Tag::CALLER_NONCE,
 ///                         boolValue: true,
 ///                         ..
 ///                 } => KeyParameterValue::CallerNonce,
-///                 AidlKeyParameter {
+///                 KmKeyParameter {
 ///                          tag: Tag::USER_SECURE_ID,
 ///                          longInteger: v,
 ///                          ..
 ///                 } => KeyParameterValue::UserSecureID(v),
-///                 AidlKeyParameter {
+///                 KmKeyParameter {
 ///                          tag: Tag::APPLICATION_ID,
 ///                          blob: v,
 ///                          ..
 ///                 } => KeyParameterValue::ApplicationID(v),
-///                 AidlKeyParameter {
+///                 KmKeyParameter {
 ///                          tag: Tag::ACTIVE_DATETIME,
 ///                          dateTime: v,
 ///                          ..
@@ -683,190 +683,227 @@
 /// }
 ///
 macro_rules! implement_key_parameter_conversion_to_from_wire {
-     // There are three groups of rules in this macro.
-     // 1. The first group contains the rule which acts as the public interface. It takes the input
-     //    given to this macro and prepares it to be given as input to the two groups of rules
-     //    mentioned below.
-     // 2. The second group starts with the prefix @to and generates convert_to_wire() method.
-     // 3. The third group starts with the prefix @from and generates convert_from_wire() method.
-     //
-     // Input to this macro is first handled by the first macro rule (belonging to the first
-     // group above), which pre-processes the input such that rules in the other two groups
-     // generate the code for the two methods, when called recursively.
-     // Each of convert_to_wire() and convert_from_wire() methods are generated using a set of
-     // four macro rules in the second two groups. These four rules intend to do the following
-     // tasks respectively:
-     // i) generates match arms related to Invalid KeyParameterValue variant.
-     // ii) generates match arms related to boolValue field in AidlKeyParameter struct.
-     // iii) generates match arms related to all the other fields in AidlKeyParameter struct.
-     // iv) generates the method definition including the match arms generated from the above
-     // three recursive macro rules.
+    // There are three groups of rules in this macro.
+    // 1. The first group contains the rule which acts as the public interface. It takes the input
+    //    given to this macro and prepares it to be given as input to the two groups of rules
+    //    mentioned below.
+    // 2. The second group starts with the prefix @to and generates convert_to_wire() method.
+    // 3. The third group starts with the prefix @from and generates convert_from_wire() method.
+    //
+    // Input to this macro is first handled by the first macro rule (belonging to the first
+    // group above), which pre-processes the input such that rules in the other two groups
+    // generate the code for the two methods, when called recursively.
+    // Each of convert_to_wire() and convert_from_wire() methods are generated using a set of
+    // four macro rules in the second two groups. These four rules intend to do the following
+    // tasks respectively:
+    // i) generates match arms related to Invalid KeyParameterValue variant.
+    // ii) generates match arms related to boolValue field in KmKeyParameter struct.
+    // iii) generates match arms related to all the other fields in KmKeyParameter struct.
+    // iv) generates the method definition including the match arms generated from the above
+    // three recursive macro rules.
 
-     // This rule is applied on the input given to the macro invocations from outside the macro.
-     ($($variant:ident, $tag_name:ident, $field_name:ident;)*) => {
-         // pre-processes input to target the rules that generate convert_to_wire() method.
-         implement_key_parameter_conversion_to_from_wire! {@to
-             [], $($variant, $tag_name, $field_name;)*
-         }
-         // pre-processes input to target the rules that generate convert_from_wire() method.
-         implement_key_parameter_conversion_to_from_wire! {@from
-             [], $($variant, $tag_name, $field_name;)*
-         }
-     };
+    // This rule is applied on the input given to the macro invocations from outside the macro.
+    ($($variant:ident, $tag_name:ident, $field_name:ident $(,$enum_type:ident)?;)*) => {
+        // pre-processes input to target the rules that generate convert_to_wire() method.
+        implement_key_parameter_conversion_to_from_wire! {@to
+            [], $($variant, $tag_name, $field_name $(,$enum_type)?;)*
+        }
+        // pre-processes input to target the rules that generate convert_from_wire() method.
+        implement_key_parameter_conversion_to_from_wire! {@from
+            [], $($variant, $tag_name, $field_name $(,$enum_type)?;)*
+        }
+    };
 
-     // Following four rules (belonging to the aforementioned second group) generate
-     // convert_to_wire() conversion method.
-     // -----------------------------------------------------------------------
-     // This rule handles Invalid variant.
-     // On an input: 'Invalid, INVALID, na;' it generates a match arm like:
-     // KeyParameterValue::Invalid => AidlKeyParameter {
-     //                                 tag: Tag::INVALID,
-     //                                 ..Default::default()
-     //                               },
-     (@to [$($out:tt)*], Invalid, INVALID, na; $($in:tt)*) => {
-         implement_key_parameter_conversion_to_from_wire! {@to
-             [$($out)*
-                 KeyParameterValue::Invalid => AidlKeyParameter {
-                     tag: Tag::INVALID,
-                     ..Default::default()
-                 },
-             ], $($in)*
-         }
-     };
-     // This rule handles all variants that correspond to bool values.
-     // On an input like: 'CallerNonce, CALLER_NONCE, boolValue;' it generates
-     // a match arm like:
-     // KeyParameterValue::CallerNonce => AidlKeyParameter {
-     //                                      tag: Tag::CALLER_NONCE,
-     //                                      boolValue: true,
-     //                                      ..Default::default()
-     //                                   },
-     (@to [$($out:tt)*], $variant:ident, $tag_val:ident, boolValue; $($in:tt)*) => {
-         implement_key_parameter_conversion_to_from_wire! {@to
-             [$($out)*
-                 KeyParameterValue::$variant => AidlKeyParameter {
-                     tag: Tag::$tag_val,
-                     boolValue: true,
-                     ..Default::default()
-                 },
-             ], $($in)*
-         }
-     };
-     // This rule handles all variants that are neither invalid nor bool values
-     // (i.e. all variants which correspond to integer, longInteger, dateTime and blob fields in
-     // AidlKeyParameter).
-     // On an input like: 'ConfirmationToken, CONFIRMATION_TOKEN, blob;' it generates a match arm
-     // like: KeyParameterValue::ConfirmationToken(v) => AidlKeyParameter {
-     //                                                      tag: Tag::CONFIRMATION_TOKEN,
-     //                                                      blob: v,
-     //                                                      ..Default::default(),
-     //                                                }
-     (@to [$($out:tt)*], $variant:ident, $tag_val:ident, $field:ident; $($in:tt)*) => {
-         implement_key_parameter_conversion_to_from_wire! {@to
-             [$($out)*
-                 KeyParameterValue::$variant(v) => AidlKeyParameter {
-                     tag: Tag::$tag_val,
-                     $field: v,
-                     ..Default::default()
-                 },
-             ], $($in)*
-         }
-     };
-     // After all the match arms are generated by the above three rules, this rule combines them
-     // into the convert_to_wire() method.
-     (@to [$($out:tt)*], ) => {
-         /// Conversion of key parameter to wire type
-         pub fn convert_to_wire(self) -> AidlKeyParameter {
-             match self {
-                 $($out)*
-             }
-         }
-     };
+    // Following four rules (belonging to the aforementioned second group) generate
+    // convert_to_wire() conversion method.
+    // -----------------------------------------------------------------------
+    // This rule handles Invalid variant.
+    // On an input: 'Invalid, INVALID, na;' it generates a match arm like:
+    // KeyParameterValue::Invalid => KmKeyParameter {
+    //                                   tag: Tag::INVALID,
+    //                                   ..Default::default()
+    //                               },
+    (@to [$($out:tt)*], Invalid, INVALID, na; $($in:tt)*) => {
+        implement_key_parameter_conversion_to_from_wire! {@to
+            [$($out)*
+                KeyParameterValue::Invalid => KmKeyParameter {
+                    tag: Tag::INVALID,
+                    ..Default::default()
+                },
+            ], $($in)*
+        }
+    };
+    // This rule handles all variants that correspond to bool values.
+    // On an input like: 'CallerNonce, CALLER_NONCE, boolValue;' it generates
+    // a match arm like:
+    // KeyParameterValue::CallerNonce => KmKeyParameter {
+    //                                       tag: Tag::CALLER_NONCE,
+    //                                       boolValue: true,
+    //                                       ..Default::default()
+    //                                   },
+    (@to [$($out:tt)*], $variant:ident, $tag_val:ident, boolValue; $($in:tt)*) => {
+        implement_key_parameter_conversion_to_from_wire! {@to
+            [$($out)*
+                KeyParameterValue::$variant => KmKeyParameter {
+                    tag: Tag::$tag_val,
+                    boolValue: true,
+                    ..Default::default()
+                },
+            ], $($in)*
+        }
+    };
+    // This rule handles all enum variants.
+    // On an input like: 'KeyPurpose, PURPOSE, integer, KeyPurpose;' it generates a match arm
+    // like: KeyParameterValue::KeyPurpose(v) => KmKeyParameter {
+    //                                               tag: Tag::PURPOSE,
+    //                                               integer: v.0,
+    //                                               ..Default::default(),
+    //                                           },
+    (@to [$($out:tt)*], $variant:ident, $tag_val:ident, $field:ident, $enum_type:ident; $($in:tt)*) => {
+       implement_key_parameter_conversion_to_from_wire! {@to
+           [$($out)*
+               KeyParameterValue::$variant(v) => KmKeyParameter {
+                   tag: Tag::$tag_val,
+                   $field: v.0,
+                   ..Default::default()
+               },
+           ], $($in)*
+       }
+    };
+    // This rule handles all variants that are neither invalid nor bool values nor enums
+    // (i.e. all variants which correspond to integer, longInteger, dateTime and blob fields in
+    // KmKeyParameter).
+    // On an input like: 'ConfirmationToken, CONFIRMATION_TOKEN, blob;' it generates a match arm
+    // like: KeyParameterValue::ConfirmationToken(v) => KmKeyParameter {
+    //                                                      tag: Tag::CONFIRMATION_TOKEN,
+    //                                                      blob: v,
+    //                                                      ..Default::default(),
+    //                                                  },
+    (@to [$($out:tt)*], $variant:ident, $tag_val:ident, $field:ident; $($in:tt)*) => {
+        implement_key_parameter_conversion_to_from_wire! {@to
+            [$($out)*
+                KeyParameterValue::$variant(v) => KmKeyParameter {
+                    tag: Tag::$tag_val,
+                    $field: v,
+                    ..Default::default()
+                },
+            ], $($in)*
+        }
+    };
+    // After all the match arms are generated by the above three rules, this rule combines them
+    // into the convert_to_wire() method.
+    (@to [$($out:tt)*], ) => {
+        /// Conversion of key parameter to wire type
+        pub fn convert_to_wire(self) -> KmKeyParameter {
+            match self {
+                $($out)*
+            }
+        }
+    };
 
-     // Following four rules (belonging to the aforementioned third group) generate
-     // convert_from_wire() conversion method.
-     // ------------------------------------------------------------------------
-     // This rule handles Invalid variant.
-     // On an input: 'Invalid, INVALID, na;' it generates a match arm like:
-     // AidlKeyParameter { tag: Tag::INVALID, .. } => KeyParameterValue::Invalid,
-     (@from [$($out:tt)*], Invalid, INVALID, na; $($in:tt)*) => {
-         implement_key_parameter_conversion_to_from_wire! {@from
-             [$($out)*
-                 AidlKeyParameter {
-                     tag: Tag::INVALID,
-                     ..
-                 } => KeyParameterValue::Invalid,
-             ], $($in)*
-         }
-     };
-     // This rule handles all variants that correspond to bool values.
-     // On an input like: 'CallerNonce, CALLER_NONCE, boolValue;' it generates a match arm like:
-     // AidlKeyParameter {
-     //      tag: Tag::CALLER_NONCE,
-     //      boolValue: true,
-     //      ..
-     // } => KeyParameterValue::CallerNonce,
-     (@from [$($out:tt)*], $variant:ident, $tag_val:ident, boolValue; $($in:tt)*) => {
-         implement_key_parameter_conversion_to_from_wire! {@from
-             [$($out)*
-                 AidlKeyParameter {
-                     tag: Tag::$tag_val,
-                     boolValue: true,
-                     ..
-                 } => KeyParameterValue::$variant,
-             ], $($in)*
-         }
-     };
-     // This rule handles all variants that are neither invalid nor bool values
-     // (i.e. all variants which correspond to integer, longInteger, dateTime and blob fields in
-     // AidlKeyParameter).
-     // On an input like: 'ConfirmationToken, CONFIRMATION_TOKEN, blob;' it generates a match arm
-     // like:
-     // AidlKeyParameter {
-     //         tag: Tag::CONFIRMATION_TOKEN,
-     //         blob: v,
-     //         ..,
-     // } => KeyParameterValue::ConfirmationToken(v),
-     (@from [$($out:tt)*], $variant:ident, $tag_val:ident, $field:ident; $($in:tt)*) => {
-         implement_key_parameter_conversion_to_from_wire! {@from
-             [$($out)*
-                 AidlKeyParameter {
-                     tag: Tag::$tag_val,
-                     $field: v,
-                     ..
-                 } => KeyParameterValue::$variant(v),
-             ], $($in)*
-         }
-     };
-     // After all the match arms are generated by the above three rules, this rule combines them
-     // into the convert_from_wire() method.
-     (@from [$($out:tt)*], ) => {
-         /// Conversion of key parameter from wire type
-         pub fn convert_from_wire(aidl_kp: AidlKeyParameter) -> KeyParameterValue {
-             match aidl_kp {
-                 $($out)*
-                 _ => KeyParameterValue::Invalid,
-             }
-         }
-     };
+    // Following four rules (belonging to the aforementioned third group) generate
+    // convert_from_wire() conversion method.
+    // ------------------------------------------------------------------------
+    // This rule handles Invalid variant.
+    // On an input: 'Invalid, INVALID, na;' it generates a match arm like:
+    // KmKeyParameter { tag: Tag::INVALID, .. } => KeyParameterValue::Invalid,
+    (@from [$($out:tt)*], Invalid, INVALID, na; $($in:tt)*) => {
+        implement_key_parameter_conversion_to_from_wire! {@from
+            [$($out)*
+                KmKeyParameter {
+                    tag: Tag::INVALID,
+                    ..
+                } => KeyParameterValue::Invalid,
+            ], $($in)*
+        }
+    };
+    // This rule handles all variants that correspond to bool values.
+    // On an input like: 'CallerNonce, CALLER_NONCE, boolValue;' it generates a match arm like:
+    // KmKeyParameter {
+    //      tag: Tag::CALLER_NONCE,
+    //      boolValue: true,
+    //      ..
+    // } => KeyParameterValue::CallerNonce,
+    (@from [$($out:tt)*], $variant:ident, $tag_val:ident, boolValue; $($in:tt)*) => {
+        implement_key_parameter_conversion_to_from_wire! {@from
+            [$($out)*
+                KmKeyParameter {
+                    tag: Tag::$tag_val,
+                    boolValue: true,
+                    ..
+                } => KeyParameterValue::$variant,
+            ], $($in)*
+        }
+    };
+    // This rule handles all enum variants.
+    // On an input like: 'KeyPurpose, PURPOSE, integer, KeyPurpose;' it generates a match arm
+    // like:
+    // KmKeyParameter {
+    //         tag: Tag::PURPOSE,
+    //         integer: v,
+    //         ..,
+    // } => KeyParameterValue::KeyPurpose(KeyPurpose(v)),
+    (@from [$($out:tt)*], $variant:ident, $tag_val:ident, $field:ident, $enum_type:ident; $($in:tt)*) => {
+        implement_key_parameter_conversion_to_from_wire! {@from
+            [$($out)*
+                KmKeyParameter {
+                    tag: Tag::$tag_val,
+                    $field: v,
+                    ..
+                } => KeyParameterValue::$variant($enum_type(v)),
+            ], $($in)*
+        }
+    };
+    // This rule handles all variants that are neither invalid nor bool values nor enums
+    // (i.e. all variants which correspond to integer, longInteger, dateTime and blob fields in
+    // KmKeyParameter).
+    // On an input like: 'ConfirmationToken, CONFIRMATION_TOKEN, blob;' it generates a match arm
+    // like:
+    // KmKeyParameter {
+    //         tag: Tag::CONFIRMATION_TOKEN,
+    //         blob: v,
+    //         ..,
+    // } => KeyParameterValue::ConfirmationToken(v),
+    (@from [$($out:tt)*], $variant:ident, $tag_val:ident, $field:ident; $($in:tt)*) => {
+        implement_key_parameter_conversion_to_from_wire! {@from
+            [$($out)*
+                KmKeyParameter {
+                    tag: Tag::$tag_val,
+                    $field: v,
+                    ..
+                } => KeyParameterValue::$variant(v),
+            ], $($in)*
+        }
+    };
+    // After all the match arms are generated by the above three rules, this rule combines them
+    // into the convert_from_wire() method.
+    (@from [$($out:tt)*], ) => {
+        /// Conversion of key parameter from wire type
+        pub fn convert_from_wire(aidl_kp: KmKeyParameter) -> KeyParameterValue {
+            match aidl_kp {
+                $($out)*
+                _ => KeyParameterValue::Invalid,
+            }
+        }
+    };
 }
 
 impl KeyParameterValue {
     // Invoke the macro that generates the code for key parameter conversion to/from wire type
     // with all possible variants of KeyParameterValue. Each line corresponding to a variant
     // contains: variant identifier, tag value, and the related field name (i.e.
-    // boolValue/integer/longInteger/dateTime/blob) in the AidlKeyParameter.
+    // boolValue/integer/longInteger/dateTime/blob) in the KmKeyParameter.
     implement_key_parameter_conversion_to_from_wire! {
         Invalid, INVALID, na;
-        KeyPurpose, PURPOSE, integer;
-        Algorithm, ALGORITHM, integer;
+        KeyPurpose, PURPOSE, integer, KeyPurpose;
+        Algorithm, ALGORITHM, integer, Algorithm;
         KeySize, KEY_SIZE, integer;
-        BlockMode, BLOCK_MODE, integer;
-        Digest, DIGEST, integer;
-        PaddingMode, PADDING, integer;
+        BlockMode, BLOCK_MODE, integer, BlockMode;
+        Digest, DIGEST, integer, Digest;
+        PaddingMode, PADDING, integer, PaddingMode;
         CallerNonce, CALLER_NONCE, boolValue;
         MinMacLength, MIN_MAC_LENGTH, integer;
-        EcCurve, EC_CURVE, integer;
+        EcCurve, EC_CURVE, integer, EcCurve;
         RSAPublicExponent, RSA_PUBLIC_EXPONENT, longInteger;
         IncludeUniqueID, INCLUDE_UNIQUE_ID, boolValue;
         BootLoaderOnly, BOOTLOADER_ONLY, boolValue;
@@ -879,7 +916,7 @@
         UserID, USER_ID, integer;
         UserSecureID, USER_SECURE_ID, longInteger;
         NoAuthRequired, NO_AUTH_REQUIRED, boolValue;
-        HardwareAuthenticatorType, USER_AUTH_TYPE, integer;
+        HardwareAuthenticatorType, USER_AUTH_TYPE, integer, HardwareAuthenticatorType;
         AuthTimeout, AUTH_TIMEOUT, integer;
         AllowWhileOnBody, ALLOW_WHILE_ON_BODY, boolValue;
         TrustedUserPresenceRequired, TRUSTED_USER_PRESENCE_REQUIRED, boolValue;
@@ -888,7 +925,7 @@
         ApplicationID, APPLICATION_ID, blob;
         ApplicationData, APPLICATION_DATA, blob;
         CreationDateTime, CREATION_DATETIME, dateTime;
-        KeyOrigin, ORIGIN, integer;
+        KeyOrigin, ORIGIN, integer, KeyOrigin;
         RootOfTrust, ROOT_OF_TRUST, blob;
         OSVersion, OS_VERSION, integer;
         OSPatchLevel, OS_PATCHLEVEL, integer;
@@ -960,9 +997,9 @@
         insert_into_keyparameter(
             &db,
             1,
-            Tag::ALGORITHM,
-            &Algorithm::RSA,
-            SecurityLevel::STRONGBOX,
+            Tag::ALGORITHM.0,
+            &Algorithm::RSA.0,
+            SecurityLevel::STRONGBOX.0,
         )?;
         let key_param = query_from_keyparameter(&db)?;
         assert_eq!(Tag::ALGORITHM, key_param.get_tag());
@@ -976,7 +1013,7 @@
     #[test]
     fn test_new_from_sql_i32() -> Result<()> {
         let db = init_db()?;
-        insert_into_keyparameter(&db, 1, Tag::KEY_SIZE, &1024, SecurityLevel::STRONGBOX)?;
+        insert_into_keyparameter(&db, 1, Tag::KEY_SIZE.0, &1024, SecurityLevel::STRONGBOX.0)?;
         let key_param = query_from_keyparameter(&db)?;
         assert_eq!(Tag::KEY_SIZE, key_param.get_tag());
         assert_eq!(*key_param.key_parameter_value(), KeyParameterValue::KeySize(1024));
@@ -992,9 +1029,9 @@
         insert_into_keyparameter(
             &db,
             1,
-            Tag::RSA_PUBLIC_EXPONENT,
+            Tag::RSA_PUBLIC_EXPONENT.0,
             &(i64::MAX),
-            SecurityLevel::STRONGBOX,
+            SecurityLevel::STRONGBOX.0,
         )?;
         let key_param = query_from_keyparameter(&db)?;
         assert_eq!(Tag::RSA_PUBLIC_EXPONENT, key_param.get_tag());
@@ -1010,7 +1047,7 @@
     #[test]
     fn test_new_from_sql_bool() -> Result<()> {
         let db = init_db()?;
-        insert_into_keyparameter(&db, 1, Tag::CALLER_NONCE, &Null, SecurityLevel::STRONGBOX)?;
+        insert_into_keyparameter(&db, 1, Tag::CALLER_NONCE.0, &Null, SecurityLevel::STRONGBOX.0)?;
         let key_param = query_from_keyparameter(&db)?;
         assert_eq!(Tag::CALLER_NONCE, key_param.get_tag());
         assert_eq!(*key_param.key_parameter_value(), KeyParameterValue::CallerNonce);
@@ -1027,9 +1064,9 @@
         insert_into_keyparameter(
             &db,
             1,
-            Tag::APPLICATION_ID,
+            Tag::APPLICATION_ID.0,
             &app_id_bytes,
-            SecurityLevel::STRONGBOX,
+            SecurityLevel::STRONGBOX.0,
         )?;
         let key_param = query_from_keyparameter(&db)?;
         assert_eq!(Tag::APPLICATION_ID, key_param.get_tag());
@@ -1140,7 +1177,7 @@
     #[test]
     fn test_invalid_conversion_from_sql() -> Result<()> {
         let db = init_db()?;
-        insert_into_keyparameter(&db, 1, Tag::ALGORITHM, &Null, 1)?;
+        insert_into_keyparameter(&db, 1, Tag::ALGORITHM.0, &Null, 1)?;
         tests::check_result_contains_error_string(
             query_from_keyparameter(&db),
             "Failed to read sql data for tag: ALGORITHM.",
@@ -1175,7 +1212,7 @@
     ) -> Result<()> {
         db.execute(
             "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
-VALUES(?, ?, ?, ?);",
+                VALUES(?, ?, ?, ?);",
             params![key_id, tag, *value, security_level],
         )?;
         Ok(())
@@ -1185,26 +1222,28 @@
     fn store_keyparameter(db: &Connection, key_id: i64, kp: &KeyParameter) -> Result<()> {
         db.execute(
             "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
-VALUES(?, ?, ?, ?);",
-            params![key_id, kp.get_tag(), kp.key_parameter_value(), kp.security_level()],
+                VALUES(?, ?, ?, ?);",
+            params![key_id, kp.get_tag().0, kp.key_parameter_value(), kp.security_level().0],
         )?;
         Ok(())
     }
 
     /// Helper method to query a row from keyparameter table
     fn query_from_keyparameter(db: &Connection) -> Result<KeyParameter> {
-        let mut stmt = db.prepare(
-            "SELECT tag, data, security_level FROM
-persistent.keyparameter",
-        )?;
+        let mut stmt =
+            db.prepare("SELECT tag, data, security_level FROM persistent.keyparameter")?;
         let mut rows = stmt.query(NO_PARAMS)?;
         let row = rows.next()?.unwrap();
-        Ok(KeyParameter::new_from_sql(row.get(0)?, &SqlField(1, row), row.get(2)?)?)
+        Ok(KeyParameter::new_from_sql(
+            Tag(row.get(0)?),
+            &SqlField(1, row),
+            SecurityLevel(row.get(2)?),
+        )?)
     }
 }
 
 /// The wire_tests module tests the 'convert_to_wire' and 'convert_from_wire' methods for
-/// KeyParameter, for the five different types used in AidlKeyParameter, in addition to Invalid
+/// KeyParameter, for the five different types used in KmKeyParameter, in addition to Invalid
 /// key parameter.
 /// i) bool
 /// ii) integer
@@ -1236,7 +1275,7 @@
         );
         let actual = KeyParameterValue::convert_to_wire(kp.key_parameter_value);
         assert_eq!(Tag::PURPOSE, actual.tag);
-        assert_eq!(KeyPurpose::ENCRYPT, actual.integer);
+        assert_eq!(KeyPurpose::ENCRYPT.0, actual.integer);
     }
     #[test]
     fn test_convert_to_wire_long_integer() {
@@ -1270,22 +1309,22 @@
     /// unit tests for from conversion
     #[test]
     fn test_convert_from_wire_invalid() {
-        let aidl_kp = AidlKeyParameter { tag: Tag::INVALID, ..Default::default() };
+        let aidl_kp = KmKeyParameter { tag: Tag::INVALID, ..Default::default() };
         let actual = KeyParameterValue::convert_from_wire(aidl_kp);
         assert_eq!(KeyParameterValue::Invalid, actual);
     }
     #[test]
     fn test_convert_from_wire_bool() {
         let aidl_kp =
-            AidlKeyParameter { tag: Tag::CALLER_NONCE, boolValue: true, ..Default::default() };
+            KmKeyParameter { tag: Tag::CALLER_NONCE, boolValue: true, ..Default::default() };
         let actual = KeyParameterValue::convert_from_wire(aidl_kp);
         assert_eq!(KeyParameterValue::CallerNonce, actual);
     }
     #[test]
     fn test_convert_from_wire_integer() {
-        let aidl_kp = AidlKeyParameter {
+        let aidl_kp = KmKeyParameter {
             tag: Tag::PURPOSE,
-            integer: KeyPurpose::ENCRYPT,
+            integer: KeyPurpose::ENCRYPT.0,
             ..Default::default()
         };
         let actual = KeyParameterValue::convert_from_wire(aidl_kp);
@@ -1293,7 +1332,7 @@
     }
     #[test]
     fn test_convert_from_wire_long_integer() {
-        let aidl_kp = AidlKeyParameter {
+        let aidl_kp = KmKeyParameter {
             tag: Tag::USER_SECURE_ID,
             longInteger: i64::MAX,
             ..Default::default()
@@ -1303,17 +1342,14 @@
     }
     #[test]
     fn test_convert_from_wire_date_time() {
-        let aidl_kp = AidlKeyParameter {
-            tag: Tag::ACTIVE_DATETIME,
-            dateTime: i64::MAX,
-            ..Default::default()
-        };
+        let aidl_kp =
+            KmKeyParameter { tag: Tag::ACTIVE_DATETIME, dateTime: i64::MAX, ..Default::default() };
         let actual = KeyParameterValue::convert_from_wire(aidl_kp);
         assert_eq!(KeyParameterValue::ActiveDateTime(i64::MAX), actual);
     }
     #[test]
     fn test_convert_from_wire_blob() {
-        let aidl_kp = AidlKeyParameter {
+        let aidl_kp = KmKeyParameter {
             tag: Tag::CONFIRMATION_TOKEN,
             blob: String::from("ConfirmationToken").into_bytes(),
             ..Default::default()
diff --git a/keystore2/src/lib.rs b/keystore2/src/lib.rs
index b5fef3e..7439a5b 100644
--- a/keystore2/src/lib.rs
+++ b/keystore2/src/lib.rs
@@ -16,6 +16,8 @@
 
 pub mod database;
 pub mod error;
+pub mod globals;
 /// Internal Representation of Key Parameter and convenience functions.
 pub mod key_parameter;
 pub mod permission;
+pub mod utils;
diff --git a/keystore2/src/permission.rs b/keystore2/src/permission.rs
index 1880623..0917256 100644
--- a/keystore2/src/permission.rs
+++ b/keystore2/src/permission.rs
@@ -18,9 +18,9 @@
 //! It also provides KeystorePerm and KeyPerm as convenience wrappers for the SELinux permission
 //! defined by keystore2 and keystore2_key respectively.
 
-use android_security_keystore2::aidl::android::security::keystore2::KeyPermission;
-
-use android_security_keystore2::aidl::android::security::keystore2::KeyDescriptor::KeyDescriptor;
+use android_system_keystore2::aidl::android::system::keystore2::{
+    Domain::Domain, KeyDescriptor::KeyDescriptor, KeyPermission::KeyPermission,
+};
 
 use std::cmp::PartialEq;
 use std::convert::From;
@@ -137,10 +137,10 @@
     =>
     {
         $(#[$m])*
-        pub struct $name(pub $aidl_name::$aidl_name);
+        pub struct $name(pub $aidl_name);
 
-        impl From<$aidl_name::$aidl_name> for $name {
-            fn from (p: $aidl_name::$aidl_name) -> Self {
+        impl From<$aidl_name> for $name {
+            fn from (p: $aidl_name) -> Self {
                 match p {
                     $aidl_name::$def_name => Self($aidl_name::$def_name),
                     $($aidl_name::$element_name => Self($aidl_name::$element_name),)*
@@ -149,8 +149,8 @@
             }
         }
 
-        impl Into<$aidl_name::$aidl_name> for $name {
-            fn into(self) -> $aidl_name::$aidl_name {
+        impl Into<$aidl_name> for $name {
+            fn into(self) -> $aidl_name {
                 self.0
             }
         }
@@ -192,17 +192,17 @@
     ///                       KeyPerm::get_info().to_selinux());
     /// ```
     #[derive(Clone, Copy, Debug, Eq, PartialEq)]
-    KeyPerm from KeyPermission with default (None, none) {
-        Delete,         selinux name: delete;
-        GenUniqueId,    selinux name: gen_unique_id;
-        GetInfo,        selinux name: get_info;
-        Grant,          selinux name: grant;
-        ManageBlob,     selinux name: manage_blob;
-        Rebind,         selinux name: rebind;
-        ReqForcedOp,    selinux name: req_forced_op;
-        Update,         selinux name: update;
-        Use,            selinux name: use;
-        UseDevId,       selinux name: use_dev_id;
+    KeyPerm from KeyPermission with default (NONE, none) {
+        DELETE,         selinux name: delete;
+        GEN_UNIQUE_ID,  selinux name: gen_unique_id;
+        GET_INFO,       selinux name: get_info;
+        GRANT,          selinux name: grant;
+        MANAGE_BLOB,    selinux name: manage_blob;
+        REBIND,         selinux name: rebind;
+        REQ_FORCED_OP,  selinux name: req_forced_op;
+        UPDATE,         selinux name: update;
+        USE,            selinux name: use;
+        USE_DEV_ID,     selinux name: use_dev_id;
     }
 );
 
@@ -356,7 +356,7 @@
                 let p = self.vec.0 & (1 << self.pos);
                 self.pos += 1;
                 if p != 0 {
-                    return Some(KeyPerm::from(p));
+                    return Some(KeyPerm::from(KeyPermission(p)));
                 }
             }
         }
@@ -365,7 +365,7 @@
 
 impl From<KeyPerm> for KeyPermSet {
     fn from(p: KeyPerm) -> Self {
-        Self(p.0 as i32)
+        Self((p.0).0 as i32)
     }
 }
 
@@ -400,7 +400,7 @@
 macro_rules! key_perm_set {
     () => { KeyPermSet(0) };
     ($head:expr $(, $tail:expr)* $(,)?) => {
-        KeyPermSet($head.0 as i32 $(| $tail.0 as i32)*)
+        KeyPermSet(($head.0).0 $(| ($tail.0).0)*)
     };
 }
 
@@ -429,8 +429,8 @@
 /// Attempts to grant the grant permission are always denied.
 ///
 /// The only viable target domains are
-///  * `Domain::App` in which case u:r:keystore:s0 is used as target context and
-///  * `Domain::SELinux` in which case the `key.namespace_` parameter is looked up in
+///  * `Domain::APP` in which case u:r:keystore:s0 is used as target context and
+///  * `Domain::SELINUX` in which case the `key.nspace` parameter is looked up in
 ///                      SELinux keystore key backend, and the result is used
 ///                      as target context.
 pub fn check_grant_permission(
@@ -438,12 +438,10 @@
     access_vec: KeyPermSet,
     key: &KeyDescriptor,
 ) -> anyhow::Result<()> {
-    use android_security_keystore2::aidl::android::security::keystore2::Domain;
-
     let target_context = match key.domain {
-        Domain::App => getcon().context("check_grant_permission: getcon failed.")?,
-        Domain::SELinux => lookup_keystore2_key_context(key.namespace_)
-            .context("check_grant_permission: Domain::SELinux: Failed to lookup namespace.")?,
+        Domain::APP => getcon().context("check_grant_permission: getcon failed.")?,
+        Domain::SELINUX => lookup_keystore2_key_context(key.nspace)
+            .context("check_grant_permission: Domain::SELINUX: Failed to lookup namespace.")?,
         _ => return Err(KsError::sys()).context(format!("Cannot grant {:?}.", key.domain)),
     };
 
@@ -469,19 +467,19 @@
 /// descriptor `key` in the security class `keystore2_key`.
 ///
 /// The behavior differs slightly depending on the selected target domain:
-///  * `Domain::App` u:r:keystore:s0 is used as target context.
-///  * `Domain::SELinux` `key.namespace_` parameter is looked up in the SELinux keystore key
+///  * `Domain::APP` u:r:keystore:s0 is used as target context.
+///  * `Domain::SELINUX` `key.nspace` parameter is looked up in the SELinux keystore key
 ///                      backend, and the result is used as target context.
-///  * `Domain::Blob` Same as SELinux but the "manage_blob" permission is always checked additionally
+///  * `Domain::BLOB` Same as SELinux but the "manage_blob" permission is always checked additionally
 ///                   to the one supplied in `perm`.
-///  * `Domain::Grant` Does not use selinux::check_access. Instead the `access_vector`
+///  * `Domain::GRANT` Does not use selinux::check_access. Instead the `access_vector`
 ///                    parameter is queried for permission, which must be supplied in this case.
 ///
 /// ## Return values.
 ///  * Ok(()) If the requested permissions were granted.
 ///  * Err(selinux::Error::perm()) If the requested permissions were denied.
-///  * Err(KsError::sys()) This error is produced if `Domain::Grant` is selected but no `access_vec`
-///                      was supplied. It is also produced if `Domain::KeyId` was selected, and
+///  * Err(KsError::sys()) This error is produced if `Domain::GRANT` is selected but no `access_vec`
+///                      was supplied. It is also produced if `Domain::KEY_ID` was selected, and
 ///                      on various unexpected backend failures.
 pub fn check_key_permission(
     caller_ctx: &CStr,
@@ -489,14 +487,12 @@
     key: &KeyDescriptor,
     access_vector: &Option<KeyPermSet>,
 ) -> anyhow::Result<()> {
-    use android_security_keystore2::aidl::android::security::keystore2::Domain;
-
     let target_context = match key.domain {
         // apps get the default keystore context
-        Domain::App => getcon().context("check_key_permission: getcon failed.")?,
-        Domain::SELinux => lookup_keystore2_key_context(key.namespace_)
-            .context("check_key_permission: Domain::SELinux: Failed to lookup namespace.")?,
-        Domain::Grant => {
+        Domain::APP => getcon().context("check_key_permission: getcon failed.")?,
+        Domain::SELINUX => lookup_keystore2_key_context(key.nspace)
+            .context("check_key_permission: Domain::SELINUX: Failed to lookup namespace.")?,
+        Domain::GRANT => {
             match access_vector {
                 Some(pv) => {
                     if pv.includes(perm) {
@@ -509,20 +505,20 @@
                 None => {
                     // If DOMAIN_GRANT was selected an access vector must be supplied.
                     return Err(KsError::sys()).context(
-                        "Cannot check permission for Domain::Grant without access vector.",
+                        "Cannot check permission for Domain::GRANT without access vector.",
                     );
                 }
             }
         }
-        Domain::KeyId => {
-            // We should never be called with `Domain::KeyId. The database
-            // lookup should have converted this into one of `Domain::App`
-            // or `Domain::SELinux`.
-            return Err(KsError::sys()).context("Cannot check permission for Domain::KeyId.");
+        Domain::KEY_ID => {
+            // We should never be called with `Domain::KEY_ID. The database
+            // lookup should have converted this into one of `Domain::APP`
+            // or `Domain::SELINUX`.
+            return Err(KsError::sys()).context("Cannot check permission for Domain::KEY_ID.");
         }
-        Domain::Blob => {
-            let tctx = lookup_keystore2_key_context(key.namespace_)
-                .context("Domain::Blob: Failed to lookup namespace.")?;
+        Domain::BLOB => {
+            let tctx = lookup_keystore2_key_context(key.nspace)
+                .context("Domain::BLOB: Failed to lookup namespace.")?;
             // If DOMAIN_KEY_BLOB was specified, we check for the "manage_blob"
             // permission in addition to the requested permission.
             selinux::check_access(
@@ -536,7 +532,7 @@
         }
         _ => {
             return Err(KsError::sys())
-                .context(format!("Unknown domain value: \"{}\".", key.domain))
+                .context(format!("Unknown domain value: \"{:?}\".", key.domain))
         }
     };
 
@@ -650,8 +646,7 @@
     fn check_grant_permission_app() -> Result<()> {
         let system_server_ctx = Context::new("u:r:system_server:s0")?;
         let shell_ctx = Context::new("u:r:shell:s0")?;
-        use android_security_keystore2::aidl::android::security::keystore2::Domain;
-        let key = KeyDescriptor { domain: Domain::App, namespace_: 0, alias: None, blob: None };
+        let key = KeyDescriptor { domain: Domain::APP, nspace: 0, alias: None, blob: None };
         assert!(check_grant_permission(&system_server_ctx, NOT_GRANT_PERMS, &key).is_ok());
         // attempts to grant the grant permission must always fail even when privileged.
 
@@ -667,11 +662,10 @@
 
     #[test]
     fn check_grant_permission_selinux() -> Result<()> {
-        use android_security_keystore2::aidl::android::security::keystore2::Domain;
         let (sctx, namespace, is_su) = check_context()?;
         let key = KeyDescriptor {
-            domain: Domain::SELinux,
-            namespace_: namespace as i64,
+            domain: Domain::SELINUX,
+            nspace: namespace as i64,
             alias: None,
             blob: None,
         };
@@ -688,8 +682,7 @@
 
     #[test]
     fn check_key_permission_domain_grant() -> Result<()> {
-        use android_security_keystore2::aidl::android::security::keystore2::Domain;
-        let key = KeyDescriptor { domain: Domain::Grant, namespace_: 0, alias: None, blob: None };
+        let key = KeyDescriptor { domain: Domain::GRANT, nspace: 0, alias: None, blob: None };
 
         assert_perm_failed!(check_key_permission(
             &selinux::Context::new("ignored").unwrap(),
@@ -711,9 +704,8 @@
         let system_server_ctx = Context::new("u:r:system_server:s0")?;
         let shell_ctx = Context::new("u:r:shell:s0")?;
         let gmscore_app = Context::new("u:r:gmscore_app:s0")?;
-        use android_security_keystore2::aidl::android::security::keystore2::Domain;
 
-        let key = KeyDescriptor { domain: Domain::App, namespace_: 0, alias: None, blob: None };
+        let key = KeyDescriptor { domain: Domain::APP, nspace: 0, alias: None, blob: None };
 
         assert!(check_key_permission(&system_server_ctx, KeyPerm::use_(), &key, &None).is_ok());
         assert!(check_key_permission(&system_server_ctx, KeyPerm::delete(), &key, &None).is_ok());
@@ -752,11 +744,10 @@
 
     #[test]
     fn check_key_permission_domain_selinux() -> Result<()> {
-        use android_security_keystore2::aidl::android::security::keystore2::Domain;
         let (sctx, namespace, is_su) = check_context()?;
         let key = KeyDescriptor {
-            domain: Domain::SELinux,
-            namespace_: namespace as i64,
+            domain: Domain::SELINUX,
+            nspace: namespace as i64,
             alias: None,
             blob: None,
         };
@@ -789,11 +780,10 @@
 
     #[test]
     fn check_key_permission_domain_blob() -> Result<()> {
-        use android_security_keystore2::aidl::android::security::keystore2::Domain;
         let (sctx, namespace, is_su) = check_context()?;
         let key = KeyDescriptor {
-            domain: Domain::Blob,
-            namespace_: namespace as i64,
+            domain: Domain::BLOB,
+            nspace: namespace as i64,
             alias: None,
             blob: None,
         };
@@ -808,8 +798,7 @@
 
     #[test]
     fn check_key_permission_domain_key_id() -> Result<()> {
-        use android_security_keystore2::aidl::android::security::keystore2::Domain;
-        let key = KeyDescriptor { domain: Domain::KeyId, namespace_: 0, alias: None, blob: None };
+        let key = KeyDescriptor { domain: Domain::KEY_ID, nspace: 0, alias: None, blob: None };
 
         assert_eq!(
             Some(&KsError::sys()),
diff --git a/keystore2/src/utils.rs b/keystore2/src/utils.rs
new file mode 100644
index 0000000..825b34a
--- /dev/null
+++ b/keystore2/src/utils.rs
@@ -0,0 +1,122 @@
+// Copyright 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.
+
+//! This module implements utility functions used by the Keystore 2.0 service
+//! implementation.
+
+use crate::error::Error;
+use crate::permission;
+use crate::permission::{KeyPerm, KeyPermSet, KeystorePerm};
+use android_hardware_keymint::aidl::android::hardware::keymint::{
+    KeyParameter::KeyParameter as KmParam, Tag::Tag,
+};
+use android_system_keystore2::aidl::android::system::keystore2::{
+    KeyDescriptor::KeyDescriptor, KeyParameter::KeyParameter,
+};
+use anyhow::{anyhow, Context};
+use binder::{FromIBinder, SpIBinder, ThreadState};
+use std::sync::Mutex;
+
+/// This function uses its namesake in the permission module and in
+/// combination with with_calling_sid from the binder crate to check
+/// if the caller has the given keystore permission.
+pub fn check_keystore_permission(perm: KeystorePerm) -> anyhow::Result<()> {
+    ThreadState::with_calling_sid(|calling_sid| {
+        permission::check_keystore_permission(
+            &calling_sid.ok_or_else(Error::sys).context(
+                "In check_keystore_permission: Cannot check permission without calling_sid.",
+            )?,
+            perm,
+        )
+    })
+}
+
+/// This function uses its namesake in the permission module and in
+/// combination with with_calling_sid from the binder crate to check
+/// if the caller has the given grant permission.
+pub fn check_grant_permission(access_vec: KeyPermSet, key: &KeyDescriptor) -> anyhow::Result<()> {
+    ThreadState::with_calling_sid(|calling_sid| {
+        permission::check_grant_permission(
+            &calling_sid.ok_or_else(Error::sys).context(
+                "In check_grant_permission: Cannot check permission without calling_sid.",
+            )?,
+            access_vec,
+            key,
+        )
+    })
+}
+
+/// This function uses its namesake in the permission module and in
+/// combination with with_calling_sid from the binder crate to check
+/// if the caller has the given key permission.
+pub fn check_key_permission(
+    perm: KeyPerm,
+    key: &KeyDescriptor,
+    access_vector: &Option<KeyPermSet>,
+) -> anyhow::Result<()> {
+    ThreadState::with_calling_sid(|calling_sid| {
+        permission::check_key_permission(
+            &calling_sid
+                .ok_or_else(Error::sys)
+                .context("In check_key_permission: Cannot check permission without calling_sid.")?,
+            perm,
+            key,
+            access_vector,
+        )
+    })
+}
+
+/// This function converts a `KeyParameter` from the keystore2 AIDL
+/// bindings into a `KeyParameter` from the keymint AIDL bindings.
+/// TODO This is a temporary workaround until the keymint AIDL spec
+/// lands.
+pub fn keyparam_ks_to_km(p: &KeyParameter) -> KmParam {
+    KmParam {
+        tag: Tag(p.tag),
+        boolValue: p.boolValue,
+        integer: p.integer,
+        longInteger: p.longInteger,
+        dateTime: p.dateTime,
+        blob: match &p.blob {
+            Some(b) => b.clone(),
+            None => vec![],
+        },
+    }
+}
+
+/// Thread safe wrapper around SpIBinder. It is safe to have SpIBinder smart pointers to the
+/// same object in multiple threads, but cloning a SpIBinder is not thread safe.
+/// Keystore frequently hands out binder tokens to the security level interface. If this
+/// is to happen from a multi threaded thread pool, the SpIBinder needs to be protected by a
+/// Mutex.
+#[derive(Debug)]
+pub struct Asp(Mutex<SpIBinder>);
+
+impl Asp {
+    /// Creates a new instance owning a SpIBinder wrapped in a Mutex.
+    pub fn new(i: SpIBinder) -> Self {
+        Self(Mutex::new(i))
+    }
+
+    /// Clones the owned SpIBinder and attempts to convert it into the requested interface.
+    pub fn get_interface<T: FromIBinder + ?Sized>(&self) -> anyhow::Result<Box<T>> {
+        // We can use unwrap here because we never panic when locked, so the mutex
+        // can never be poisoned.
+        let lock = self.0.lock().unwrap();
+        (*lock)
+            .clone()
+            .into_interface()
+            .map_err(|e| anyhow!(format!("get_interface failed with error code {:?}", e)))
+    }
+}