repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/data_vault.rs
drivers/src/data_vault.rs
/*++ Licensed under the Apache-2.0 license. File Name: data_vault.rs Abstract: File contains API for the Data Vault. --*/ use crate::{Array4x12, Ecc384PubKey, Ecc384Signature, Mldsa87PubKey, Mldsa87Signature}; use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; use zeroize::Zeroize; #[repr(C)] #[derive(Default, FromBytes, Immutable, IntoBytes, KnownLayout, Zeroize)] pub struct ColdResetEntries { ldev_dice_ecc_sig: Ecc384Signature, ldev_dice_ecc_pk: Ecc384PubKey, ldev_dice_mldsa_sig: Mldsa87Signature, ldev_dice_mldsa_pk: Mldsa87PubKey, fmc_dice_ecc_sig: Ecc384Signature, fmc_ecc_pk: Ecc384PubKey, fmc_dice_mldsa_sig: Mldsa87Signature, fmc_mldsa_pk: Mldsa87PubKey, fmc_tci: Array4x12, owner_pk_hash: Array4x12, cold_boot_fw_svn: u32, rom_cold_boot_status: u32, fmc_entry_point: u32, vendor_ecc_pk_index: u32, vendor_pqc_pk_index: u32, } #[repr(C)] #[derive(Default, FromBytes, Immutable, IntoBytes, KnownLayout, Zeroize)] pub struct WarmResetEntries { rt_tci: Array4x12, fw_svn: u32, rt_entry_point: u32, manifest_addr: u32, fw_min_svn: u32, rom_update_reset_status: u32, } #[repr(C)] #[derive(Default, FromBytes, Immutable, IntoBytes, KnownLayout, Zeroize)] pub struct DataVault { pub cold_reset_entries: ColdResetEntries, pub warm_reset_entries: WarmResetEntries, } impl DataVault { /// Set the ldev dice ECC signature. /// /// # Arguments /// * `sig` - ldev dice ECC signature /// pub fn set_ldev_dice_ecc_signature(&mut self, sig: &Ecc384Signature) { self.cold_reset_entries.ldev_dice_ecc_sig = *sig; } /// Get the ldev dice ECC signature. /// /// # Arguments /// * None /// /// # Returns /// ldev dice ECC signature /// pub fn ldev_dice_ecc_signature(&self) -> Ecc384Signature { self.cold_reset_entries.ldev_dice_ecc_sig } /// Set the ldev dice ECC public key. /// /// # Arguments /// * `pub_key` - ldev dice ECC public key /// pub fn set_ldev_dice_ecc_pub_key(&mut self, pub_key: &Ecc384PubKey) { self.cold_reset_entries.ldev_dice_ecc_pk = *pub_key; } /// Get the ldev dice ECC public key. /// /// # Returns /// * ldev dice ECC public key /// pub fn ldev_dice_ecc_pub_key(&self) -> Ecc384PubKey { self.cold_reset_entries.ldev_dice_ecc_pk } /// Set the fmc dice ECC signature. /// /// # Arguments /// * `sig` - fmc dice ECC signature /// pub fn set_fmc_dice_ecc_signature(&mut self, sig: &Ecc384Signature) { self.cold_reset_entries.fmc_dice_ecc_sig = *sig; } /// Get the fmc dice ECC signature. /// /// # Returns /// * fmc dice ECC signature /// pub fn fmc_dice_ecc_signature(&self) -> Ecc384Signature { self.cold_reset_entries.fmc_dice_ecc_sig } /// Set the fmc ECC public key. /// /// # Arguments /// * `pub_key` - fmc ECC public key /// pub fn set_fmc_ecc_pub_key(&mut self, pub_key: &Ecc384PubKey) { self.cold_reset_entries.fmc_ecc_pk = *pub_key; } /// Get the fmc ECC public key. /// /// # Returns /// * fmc ECC public key /// pub fn fmc_ecc_pub_key(&self) -> Ecc384PubKey { self.cold_reset_entries.fmc_ecc_pk } /// Set the ldev dice MLDSA signature. /// /// # Arguments /// * `sig` - ldev dice MLDSA signature /// pub fn set_ldev_dice_mldsa_signature(&mut self, sig: &Mldsa87Signature) { self.cold_reset_entries.ldev_dice_mldsa_sig = *sig; } /// Get the ldev dice MLDSA signature. /// /// # Returns /// * ldev dice MLDSA signature /// pub fn ldev_dice_mldsa_signature(&self) -> Mldsa87Signature { self.cold_reset_entries.ldev_dice_mldsa_sig } /// Set the ldev dice MLDSA public key. /// /// # Arguments /// * `pub_key` - ldev dice MLDSA public key /// pub fn set_ldev_dice_mldsa_pub_key(&mut self, pub_key: &Mldsa87PubKey) { self.cold_reset_entries.ldev_dice_mldsa_pk = *pub_key; } /// Get the ldev dice MLDSA public key. /// /// # Returns /// * ldev dice MLDSA public key /// pub fn ldev_dice_mldsa_pub_key(&self) -> Mldsa87PubKey { self.cold_reset_entries.ldev_dice_mldsa_pk } /// Set the fmc dice MLDSA signature. /// /// # Arguments /// * `sig` - fmc dice MLDSA signature /// pub fn set_fmc_dice_mldsa_signature(&mut self, sig: &Mldsa87Signature) { self.cold_reset_entries.fmc_dice_mldsa_sig = *sig; } /// Get the fmc dice MLDSA signature. /// /// # Returns /// * fmc dice MLDSA signature /// pub fn fmc_dice_mldsa_signature(&self) -> Mldsa87Signature { self.cold_reset_entries.fmc_dice_mldsa_sig } /// Set the fmc MLDSA public key. /// /// # Arguments /// * `pub_key` - fmc MLDSA public key /// pub fn set_fmc_mldsa_pub_key(&mut self, pub_key: &Mldsa87PubKey) { self.cold_reset_entries.fmc_mldsa_pk = *pub_key; } /// Get the fmc MLDSA public key. /// /// # Returns /// * fmc MLDSA public key /// pub fn fmc_mldsa_pub_key(&self) -> Mldsa87PubKey { self.cold_reset_entries.fmc_mldsa_pk } /// Set the fmc tcb component identifier. /// /// # Arguments /// * `tci` - fmc tcb component identifier /// pub fn set_fmc_tci(&mut self, tci: &Array4x12) { self.cold_reset_entries.fmc_tci = *tci; } /// Get the fmc tcb component identifier. /// /// # Returns /// * fmc tcb component identifier /// pub fn fmc_tci(&self) -> Array4x12 { self.cold_reset_entries.fmc_tci } /// Set the owner public keys hash /// /// # Arguments /// /// * `hash` - Owner public keys hash /// pub fn set_owner_pk_hash(&mut self, hash: &Array4x12) { self.cold_reset_entries.owner_pk_hash = *hash; } /// Get the owner public keys hash /// /// # Returns /// /// * `Array4x12` - Owner public keys hash /// pub fn owner_pk_hash(&self) -> Array4x12 { self.cold_reset_entries.owner_pk_hash } /// Set the cold-boot firmware security version number. /// /// # Arguments /// * `svn` - firmware security version number /// pub fn set_cold_boot_fw_svn(&mut self, svn: u32) { self.cold_reset_entries.cold_boot_fw_svn = svn; } /// Get the cold-boot firmware security version number. /// /// # Returns /// * cold-boot firmware security version number /// pub fn cold_boot_fw_svn(&self) -> u32 { self.cold_reset_entries.cold_boot_fw_svn } /// Set the fmc entry point. /// /// # Arguments /// /// * `entry_point` - fmc entry point pub fn set_fmc_entry_point(&mut self, entry_point: u32) { self.cold_reset_entries.fmc_entry_point = entry_point; } /// Get the fmc entry point. /// /// # Returns /// /// * fmc entry point pub fn fmc_entry_point(&self) -> u32 { self.cold_reset_entries.fmc_entry_point } /// Set the vendor ECC public key index used for image verification. /// /// # Arguments /// /// * `index` - Vendor ECC public key index pub fn set_vendor_ecc_pk_index(&mut self, index: u32) { self.cold_reset_entries.vendor_ecc_pk_index = index; } /// Get the vendor ECC public key index used for image verification. /// /// # Returns /// /// * `u32` - Vendor ECC public key index pub fn vendor_ecc_pk_index(&self) -> u32 { self.cold_reset_entries.vendor_ecc_pk_index } /// Set the vendor LMS public key index used for image verification. /// /// # Arguments /// /// * `index` - Vendor LMS public key index pub fn set_vendor_pqc_pk_index(&mut self, index: u32) { self.cold_reset_entries.vendor_pqc_pk_index = index; } /// Get the PQC (LMS or MLDSA) vendor public key index used for image verification. /// /// # Returns /// /// * `u32` - Vendor public key index pub fn vendor_pqc_pk_index(&self) -> u32 { self.cold_reset_entries.vendor_pqc_pk_index } /// Set the rom cold boot status. /// /// # Arguments /// /// * `status` - Rom Cold Boot Status pub fn set_rom_cold_boot_status(&mut self, status: u32) { self.cold_reset_entries.rom_cold_boot_status = status; } /// Get the rom cold boot status. /// /// # Returns /// /// * `u32` - Rom Cold Boot Status pub fn rom_cold_boot_status(&self) -> u32 { self.cold_reset_entries.rom_cold_boot_status } /// Set the rom update reset status. /// /// # Arguments /// /// * `status` - Rom Update Reset Status pub fn set_rom_update_reset_status(&mut self, status: u32) { self.warm_reset_entries.rom_update_reset_status = status; } /// Get the rom update reset status. /// /// # Returns /// /// * `u32` - Rom Update Reset Status pub fn rom_update_reset_status(&self) -> u32 { self.warm_reset_entries.rom_update_reset_status } /// Set the rt tcb component identifier. /// /// # Arguments /// * `tci` - rt tcb component identifier /// pub fn set_rt_tci(&mut self, tci: &Array4x12) { self.warm_reset_entries.rt_tci = *tci; } /// Get the rt tcb component identifier. /// /// # Returns /// * rt tcb component identifier /// pub fn rt_tci(&self) -> Array4x12 { self.warm_reset_entries.rt_tci } /// Set the fw security version number. /// /// # Arguments /// * `svn` - fw security version number /// pub fn set_fw_svn(&mut self, svn: u32) { self.warm_reset_entries.fw_svn = svn; } /// Get the fw security version number. /// /// # Returns /// * fw security version number /// pub fn fw_svn(&self) -> u32 { self.warm_reset_entries.fw_svn } /// Set the fw minimum security version number. /// /// # Arguments /// * `svn` - fw minimum security version number /// pub fn set_fw_min_svn(&mut self, svn: u32) { self.warm_reset_entries.fw_min_svn = svn; } /// Get the fw minimum security version number. /// /// # Returns /// * fw minimum security version number /// pub fn fw_min_svn(&self) -> u32 { self.warm_reset_entries.fw_min_svn } /// Set the rt entry. /// /// # Arguments /// * `entry_point` - rt entry point pub fn set_rt_entry_point(&mut self, entry_point: u32) { self.warm_reset_entries.rt_entry_point = entry_point; } /// Get the rt entry. /// /// # Returns /// /// * rt entry point pub fn rt_entry_point(&self) -> u32 { self.warm_reset_entries.rt_entry_point } /// Set the manifest address. /// /// # Arguments /// * `addr` - manifest address pub fn set_manifest_addr(&mut self, addr: u32) { self.warm_reset_entries.manifest_addr = addr; } /// Get the manifest address. /// /// # Returns /// /// * manifest address pub fn manifest_addr(&self) -> u32 { self.warm_reset_entries.manifest_addr } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/wait.rs
drivers/src/wait.rs
/*++ Licensed under the Apache-2.0 license. File Name: wait.rs Abstract: File contains common functions and macros to implement wait routines. --*/ pub fn until<F>(predicate: F) where F: Fn() -> bool, { while !predicate() {} }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/aes.rs
drivers/src/aes.rs
/*++ Licensed under the Apache-2.0 license. File Name: aes.rs Abstract: Driver for AES hardware operations. Notes about how this hardware differs from other hardware: * Shadowed control registers need to be written twice. * Registers are in little-endian order rather than big-endian, so we cannot use our normal Array4xN types. --*/ use crate::{ kv_access::{KvAccess, KvAccessErr}, CaliptraError, CaliptraResult, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, LEArray4x16, LEArray4x3, LEArray4x4, LEArray4x8, Trng, }; use caliptra_api::mailbox::CmAesMode; #[cfg(not(feature = "no-cfi"))] use caliptra_cfi_derive::cfi_impl_fn; use caliptra_registers::{aes::AesReg, aes_clp::AesClpReg}; use core::cmp::Ordering; use zerocopy::{transmute, FromBytes, Immutable, IntoBytes, KnownLayout}; type AesKeyBlock = LEArray4x8; type AesBlock = LEArray4x4; type AesGcmIvBlock = LEArray4x3; type AesGcmTag = LEArray4x4; pub const AES_BLOCK_SIZE_BYTES: usize = 16; const _: () = assert!(AES_BLOCK_SIZE_BYTES == core::mem::size_of::<AesBlock>()); const _: () = assert!(32 == core::mem::size_of::<AesKeyBlock>()); pub const AES_BLOCK_SIZE_WORDS: usize = AES_BLOCK_SIZE_BYTES / 4; const AES_MAX_DATA_SIZE: usize = 1024 * 1024; pub const AES_GCM_CONTEXT_SIZE_BYTES: usize = 100; pub const AES_CONTEXT_SIZE_BYTES: usize = 128; /// From the CMAC specification const R_B: u128 = 0x87; const ZERO_BLOCK: AesBlock = AesBlock::new([0; AES_BLOCK_SIZE_WORDS]); /// AES GCM IV #[derive(Debug, Copy, Clone)] pub enum AesGcmIv<'a> { Array(&'a AesGcmIvBlock), Random, } impl<'a> From<&'a LEArray4x3> for AesGcmIv<'a> { fn from(value: &'a LEArray4x3) -> Self { Self::Array(value) } } /// AES Key #[derive(Debug, Copy, Clone)] pub enum AesKey<'a> { /// Array - 32 Bytes (256 bits) Array(&'a AesKeyBlock), /// Split key parts that are XOR'd together Split(&'a AesKeyBlock, &'a AesKeyBlock), /// Read from the key vault KV(KeyReadArgs), } impl AesKey<'_> { // returns true if the key must be sideloaded const fn sideload(&self) -> bool { matches!(self, AesKey::KV(_)) } } impl<'a> From<&'a AesKeyBlock> for AesKey<'a> { /// Converts to this type from the input type. fn from(value: &'a AesKeyBlock) -> Self { Self::Array(value) } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(u32)] pub enum AesMode { Ecb = 1 << 0, Cbc = 1 << 1, _Cfb = 1 << 2, _Ofb = 1 << 3, Ctr = 1 << 4, Gcm = 1 << 5, _None = (1 << 6) - 1, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum AesKeyLen { _128 = 1, _192 = 2, _256 = 4, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum AesOperation { Encrypt = 1, Decrypt = 2, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum GcmPhase { Init = 1 << 0, Restore = 1 << 1, Aad = 1 << 2, Text = 1 << 3, Save = 1 << 4, Tag = 1 << 5, } #[derive(Clone, Copy, Debug, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq)] pub struct AesGcmContext { pub key: AesKeyBlock, pub iv: LEArray4x3, pub aad_len: u32, pub ghash_state: AesBlock, pub buffer_len: u32, pub buffer: [u8; 16], pub reserved: [u32; 4], } const _: () = assert!(core::mem::size_of::<AesGcmContext>() == AES_GCM_CONTEXT_SIZE_BYTES); #[derive(Clone, Copy, Debug, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq)] pub struct AesContext { pub mode: u32, pub key: AesKeyBlock, pub last_ciphertext: AesBlock, pub last_block_index: u8, _padding: [u8; 75], } impl Default for AesContext { fn default() -> Self { Self { mode: 0, key: AesKeyBlock::default(), last_ciphertext: AesBlock::default(), last_block_index: 0, _padding: [0; 75], } } } const _: () = assert!(core::mem::size_of::<AesContext>() == AES_CONTEXT_SIZE_BYTES); #[inline(never)] fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { if a.len() != b.len() { return false; } let mut acc = 0; for i in 0..a.len() { acc |= a[i] ^ b[i]; } acc == 0 } /// AES cryptographic engine driver. pub struct Aes { aes: AesReg, aes_clp: AesClpReg, } // the value of this mask is not important, but the AES engine must be programmed // with the key split into two pieces that are XOR'd together. const MASK: u32 = 0x1234_5678; /// Wait for the AES engine to be idle. /// Necessary before writing control registers. fn wait_for_idle(aes: &caliptra_registers::aes::RegisterBlock<ureg::RealMmioMut<'_>>) { while !aes.status().read().idle() {} } #[allow(clippy::too_many_arguments)] impl Aes { pub fn new(aes: AesReg, aes_clp: AesClpReg) -> Self { Self { aes, aes_clp } } // Ensures that only one copy of the AES registers are used // in any given context to ensure exclusive access. fn with_aes<T>( &mut self, f: impl FnOnce( caliptra_registers::aes::RegisterBlock<ureg::RealMmioMut<'_>>, caliptra_registers::aes_clp::RegisterBlock<ureg::RealMmioMut<'_>>, ) -> T, ) -> T { let aes = self.aes.regs_mut(); let aes_clp = self.aes_clp.regs_mut(); f(aes, aes_clp) } pub fn aes_256_gcm_init( &mut self, trng: &mut Trng, key: &AesKeyBlock, iv: AesGcmIv, aad: &[u8], ) -> CaliptraResult<AesGcmContext> { if aad.len() > AES_MAX_DATA_SIZE { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?; } let iv = self.initialize_aes_gcm( trng, iv, AesKey::Array(key), aad, AesOperation::Encrypt, // doesn't matter )?; let ghash_state = if aad.is_empty() { // Edge case where we have not actually done any AES operations, // so the GHASH state should not be saved. AesBlock::default() } else { self.save() }; self.zeroize_internal(); Ok(AesGcmContext { key: *key, iv, aad_len: aad.len() as u32, ghash_state, buffer_len: 0, buffer: [0; 16], reserved: [0; 4], }) } /// Restores the AES context, updates with new plaintext, /// and returns the number of ciphertext bytes written and /// the new context. pub fn aes_256_gcm_encrypt_update( &mut self, context: &AesGcmContext, plaintext: &[u8], ciphertext: &mut [u8], ) -> CaliptraResult<(usize, AesGcmContext)> { self.aes_256_gcm_update(context, plaintext, ciphertext, AesOperation::Encrypt) } /// Restores the AES context, updates with new ciphertext, /// and returns the number of plaintext bytes written and /// the new context. pub fn aes_256_gcm_decrypt_update( &mut self, context: &AesGcmContext, ciphertext: &[u8], plaintext: &mut [u8], ) -> CaliptraResult<(usize, AesGcmContext)> { self.aes_256_gcm_update(context, ciphertext, plaintext, AesOperation::Decrypt) } fn aes_256_gcm_update( &mut self, context: &AesGcmContext, mut input: &[u8], mut output: &mut [u8], op: AesOperation, ) -> CaliptraResult<(usize, AesGcmContext)> { let left = context.buffer_len as usize % AES_BLOCK_SIZE_BYTES; if output.len() < input.len() + left { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?; } let mut len = context.buffer_len as usize; if left + input.len() < AES_BLOCK_SIZE_BYTES { // not enough bytes to do a block, so save in the buffer and return let mut buffer = [0u8; AES_BLOCK_SIZE_BYTES]; buffer[..left].copy_from_slice(&context.buffer[..left]); buffer[left..left + input.len()].copy_from_slice(input); len += input.len(); self.zeroize_internal(); return Ok(( 0, AesGcmContext { key: context.key, iv: context.iv, aad_len: context.aad_len, ghash_state: context.ghash_state, buffer_len: len as u32, buffer, reserved: [0; 4], }, )); } self.restore( AesKey::Array(&context.key), &context.iv, context.aad_len, context.buffer_len, context.ghash_state, op, )?; // check if we need to process the previous buffer let mut written = 0; if left > 0 { // guaranteed to have at least one block to do let mut buffer = [0u8; AES_BLOCK_SIZE_BYTES]; buffer[..left].copy_from_slice(&context.buffer[..left]); let take = AES_BLOCK_SIZE_BYTES - left; buffer[left..].copy_from_slice(&input[..take]); input = &input[take..]; len += take; self.read_write_data_gcm(&buffer, GcmPhase::Text, Some(output))?; output = &mut output[AES_BLOCK_SIZE_BYTES..]; written += AES_BLOCK_SIZE_BYTES; } // Write blocks of input and read blocks of output. while input.len() >= AES_BLOCK_SIZE_BYTES { let take = AES_BLOCK_SIZE_BYTES; // should be impossible but needed to prevent panic if output.len() < take { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?; } self.read_write_data_gcm(&input[..take], GcmPhase::Text, Some(output))?; written += take; output = &mut output[take..]; input = &input[take..]; len += take; } // Save the remaining plaintext in the buffer. len += input.len(); let mut buffer = [0u8; AES_BLOCK_SIZE_BYTES]; buffer[..input.len()].copy_from_slice(input); let ghash_state = if context.aad_len == 0 && context.buffer_len == 0 { // Edge case where we have not actually done any AES operations, // so the GHASH state should not be saved. AesBlock::default() } else { self.save() }; self.zeroize_internal(); Ok(( written, AesGcmContext { key: context.key, iv: context.iv, aad_len: context.aad_len, ghash_state, buffer_len: len as u32, buffer, reserved: [0; 4], }, )) } /// Computes the final ciphertext, and returns the number of ciphertext bytes /// written and the final 16-byte tag. pub fn aes_256_gcm_encrypt_final( &mut self, context: &AesGcmContext, plaintext: &[u8], ciphertext: &mut [u8], ) -> CaliptraResult<(usize, AesGcmTag)> { self.aes_256_gcm_final(context, plaintext, ciphertext, AesOperation::Encrypt) } /// Computes the final plaintext, and returns the number of plaintext bytes /// written and whether the tags matched. pub fn aes_256_gcm_decrypt_final( &mut self, context: &AesGcmContext, ciphertext: &[u8], plaintext: &mut [u8], tag: &[u8], ) -> CaliptraResult<(usize, bool)> { if tag.len() > AES_BLOCK_SIZE_BYTES { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_TAG_SIZE)?; } let (written, computed_tag) = self.aes_256_gcm_final(context, ciphertext, plaintext, AesOperation::Decrypt)?; let computed_tag = computed_tag.as_bytes(); let tag_matches = constant_time_eq(tag, computed_tag); Ok((written, tag_matches)) } /// Restores the AES context, updates with new input, /// and returns the number of output bytes written and the final 16-byte tag. fn aes_256_gcm_final( &mut self, context: &AesGcmContext, mut input: &[u8], mut output: &mut [u8], op: AesOperation, ) -> CaliptraResult<(usize, AesGcmTag)> { let left = context.buffer_len as usize % AES_BLOCK_SIZE_BYTES; if output.len() < input.len() + left { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?; } self.restore( AesKey::Array(&context.key), &context.iv, context.aad_len, context.buffer_len, context.ghash_state, op, )?; // check if we need to process the previous buffer let mut len = context.buffer_len as usize; let mut written = 0; let mut new_input = [0u8; AES_BLOCK_SIZE_BYTES]; let mut input = if left > 0 { if left + input.len() >= AES_BLOCK_SIZE_BYTES { let mut buffer = [0u8; AES_BLOCK_SIZE_BYTES]; buffer[..left].copy_from_slice(&context.buffer[..left]); let take = AES_BLOCK_SIZE_BYTES - left; buffer[left..].copy_from_slice(&input[..take]); input = &input[take..]; len += take; self.read_write_data_gcm(&buffer, GcmPhase::Text, Some(output))?; output = &mut output[AES_BLOCK_SIZE_BYTES..]; written += AES_BLOCK_SIZE_BYTES; input } else { // edge case where the buffer and input are not enough to do a block len -= left; // correct the length, which is added again later new_input[..left].copy_from_slice(&context.buffer[..left]); new_input[left..left + input.len()].copy_from_slice(input); &new_input[..left + input.len()] } } else { input }; // Write blocks of plaintext and read blocks of ciphertext out. while input.len() >= AES_BLOCK_SIZE_BYTES { let take = AES_BLOCK_SIZE_BYTES; // should be impossible but needed to prevent panic if take > output.len() { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?; } self.read_write_data_gcm(&input[..take], GcmPhase::Text, Some(output))?; output = &mut output[take..]; input = &input[take..]; len += take; written += take; } // Do the final block if !input.is_empty() { self.read_write_data_gcm(input, GcmPhase::Text, Some(output))?; len += input.len(); written += input.len(); } // Compute and return the tag let tag = self.compute_tag(context.aad_len as usize, len)?; Ok((written, tag)) } /// Saves and returns the current GHASH state. fn save(&mut self) -> AesBlock { self.with_aes(|aes, _| { wait_for_idle(&aes); for _ in 0..2 { aes.ctrl_gcm_shadowed() .write(|w| w.phase(GcmPhase::Save as u32)); } wait_for_idle(&aes); // Read out the GHASH state from the data out registers. let ghash_state = AesBlock::read_from_reg(aes.data_out()); wait_for_idle(&aes); ghash_state }) } /// Restores the GHASH state. fn restore( &mut self, key: AesKey, iv: &LEArray4x3, aad_len: u32, len: u32, ghash_state: AesBlock, op: AesOperation, ) -> CaliptraResult<()> { // No zerocopy since we can't guarantee that the // byte array is aligned to 4-byte boundaries. let iv = [ iv.0[0], iv.0[1], iv.0[2], // hardware quirk: the hardware seems to expect IV[3] to be // presented as a big-endian int instead of little-endian, like elsewhere. // The specs expect us to store the whole IV when saving and restoring, // but this is not necessary if we already know the length and can compute this, // and account for the different endianness of this register. (len / (AES_BLOCK_SIZE_BYTES as u32) + 2).swap_bytes(), ]; // sideload the KV key before we program the control register if key.sideload() { self.load_key(key)?; } self.with_aes(|aes, _| { wait_for_idle(&aes); for _ in 0..2 { aes.ctrl_shadowed().write(|w| { w.key_len(AesKeyLen::_256 as u32) .mode(AesMode::Gcm as u32) .operation(op as u32) .manual_operation(false) .sideload(key.sideload()) }); } wait_for_idle(&aes); for _ in 0..2 { aes.ctrl_gcm_shadowed() .write(|w| w.phase(GcmPhase::Init as u32).num_valid_bytes(16)); } wait_for_idle(&aes); }); if !key.sideload() { self.load_key(key)?; } self.with_aes(|aes, _| { wait_for_idle(&aes); // Program the initial IV (last 4 bytes will be zero) for (i, ivi) in iv.into_iter().enumerate().take(3) { aes.iv().at(i).write(|_| ivi); } aes.iv().at(3).write(|_| 0); wait_for_idle(&aes); // if we haven't actually written any AAD or input, then // we can skip the restore operation. // This avoids some edge cases in the hardware. if aad_len == 0 && len == 0 { return Ok(()); } // Restore the GHASH state to data_in registers, which will load the state into the // GHASH unit. for _ in 0..2 { aes.ctrl_gcm_shadowed() .write(|w| w.phase(GcmPhase::Restore as u32)); } wait_for_idle(&aes); ghash_state.write_to_reg(aes.data_in()); wait_for_idle(&aes); // Program the IV (last 4 bytes may not be zero, unlike when doing normal init) for (i, ivi) in iv.into_iter().enumerate() { aes.iv().at(i).write(|_| ivi); } wait_for_idle(&aes); Ok::<(), CaliptraError>(()) }) } /// Calculate the AES-256-GCM encrypted ciphertext for the given plaintext. /// Returns the IV and the tag. #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn aes_256_gcm_encrypt( &mut self, trng: &mut Trng, iv: AesGcmIv, key: AesKey, aad: &[u8], plaintext: &[u8], ciphertext: &mut [u8], tag_size: usize, ) -> CaliptraResult<(AesGcmIvBlock, AesGcmTag)> { if tag_size > AES_BLOCK_SIZE_BYTES { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_TAG_SIZE)?; } if ciphertext.len() < plaintext.len() { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?; } self.aes_256_gcm_op( trng, iv, key, aad, plaintext, ciphertext, AesOperation::Encrypt, ) } /// Calculate the AES-256-GCM decrypted plaintext for the given ciphertext. /// Returns the IV and the tag. #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn aes_256_gcm_decrypt( &mut self, trng: &mut Trng, iv: &LEArray4x3, key: AesKey, aad: &[u8], ciphertext: &[u8], plaintext: &mut [u8], tag: &LEArray4x4, ) -> CaliptraResult<()> { if plaintext.len() < ciphertext.len() { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?; } let (_, computed_tag) = self.aes_256_gcm_op( trng, iv.into(), key, aad, ciphertext, plaintext, AesOperation::Decrypt, )?; if !constant_time_eq(tag.as_bytes(), computed_tag.as_bytes()) { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_TAG)?; } Ok(()) } /// Initializes the AES engine for GCM mode and returns the IV used. #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn initialize_aes_gcm( &mut self, trng: &mut Trng, iv: AesGcmIv, key: AesKey, aad: &[u8], op: AesOperation, ) -> CaliptraResult<AesGcmIvBlock> { if matches!(op, AesOperation::Decrypt) && matches!(iv, AesGcmIv::Random) { // should be impossible Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_STATE)?; } // No zerocopy since we can't guarantee that the // byte array is aligned to 4-byte boundaries. let iv: LEArray4x3 = match iv { AesGcmIv::Array(iv) => *iv, AesGcmIv::Random => LEArray4x3::new(trng.generate()?.0[..3].try_into().unwrap()), }; // sideload the KV key before we program the control register if key.sideload() { self.load_key(key)?; } self.with_aes(|aes, _| { wait_for_idle(&aes); for _ in 0..2 { aes.ctrl_shadowed().write(|w| { w.key_len(AesKeyLen::_256 as u32) .mode(AesMode::Gcm as u32) .operation(op as u32) .manual_operation(false) .sideload(key.sideload()) }); } wait_for_idle(&aes); for _ in 0..2 { aes.ctrl_gcm_shadowed() .write(|w| w.phase(GcmPhase::Init as u32).num_valid_bytes(16)); } wait_for_idle(&aes); }); if !key.sideload() { self.load_key(key)?; } self.with_aes(|aes, _| { wait_for_idle(&aes); // Program the IV (last 4 bytes must be 0). for (i, ivi) in iv.0.into_iter().enumerate() { aes.iv().at(i).write(|_| ivi); } aes.iv().at(3).write(|_| 0); wait_for_idle(&aes); Ok::<(), CaliptraError>(()) })?; // Load the AAD if !aad.is_empty() { self.read_write_data_gcm(aad, GcmPhase::Aad, None)?; } Ok(iv) } fn load_key(&mut self, key: AesKey<'_>) -> CaliptraResult<()> { self.with_aes(|aes, aes_clp| { wait_for_idle(&aes); // Program the key // No zerocopy since we can't guarantee that the // byte arrays are aligned to 4-byte boundaries. match key { AesKey::Array(&arr) => { for (i, word) in arr.0.iter().enumerate() { aes.key_share0().at(i).write(|_| *word ^ MASK); aes.key_share1().at(i).write(|_| MASK); } } AesKey::Split(&key1, &key2) => { key1.write_to_reg(aes.key_share0()); key2.write_to_reg(aes.key_share1()); } AesKey::KV(key) => KvAccess::copy_from_kv( key, aes_clp.aes_kv_rd_key_status(), aes_clp.aes_kv_rd_key_ctrl(), ) .map_err(|_| CaliptraError::DRIVER_AES_READ_KEY_KV_READ)?, } wait_for_idle(&aes); Ok(()) }) } /// Initializes the AES engine for CBC or CTR mode #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn initialize_aes_cbc_ctr( &mut self, iv: &AesBlock, key: AesKey, op: AesOperation, mode: AesMode, ) -> CaliptraResult<()> { // sideload the KV key before we program the control register if key.sideload() { self.load_key(key)?; } self.with_aes(|aes, _| { wait_for_idle(&aes); for _ in 0..2 { aes.ctrl_shadowed().write(|w| { w.key_len(AesKeyLen::_256 as u32) .mode(mode as u32) .operation(op as u32) .manual_operation(false) .sideload(key.sideload()) }); } wait_for_idle(&aes); }); if !key.sideload() { self.load_key(key)?; } // Program the IV self.with_aes(|aes, _| { wait_for_idle(&aes); iv.write_to_reg(aes.iv()); wait_for_idle(&aes); }); Ok(()) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn aes_256_gcm_op( &mut self, trng: &mut Trng, iv: AesGcmIv, key: AesKey, aad: &[u8], input: &[u8], output: &mut [u8], op: AesOperation, ) -> CaliptraResult<(AesGcmIvBlock, AesGcmTag)> { if input.len() > AES_MAX_DATA_SIZE || output.len() > AES_MAX_DATA_SIZE { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?; } if input.len() > output.len() { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?; } let iv = self.initialize_aes_gcm(trng, iv, key, aad, op)?; // Write blocks of plaintext and read blocks of ciphertext out. self.read_write_data_gcm(input, GcmPhase::Text, Some(output))?; let tag = self.compute_tag(aad.len(), input.len())?; Ok((iv, tag)) } pub fn compute_tag(&mut self, aad_len: usize, text_len: usize) -> CaliptraResult<AesGcmTag> { // Compute the tag self.with_aes(|aes, _| { wait_for_idle(&aes); for _ in 0..2 { aes.ctrl_gcm_shadowed().write(|w| { w.phase(GcmPhase::Tag as u32) .num_valid_bytes(AES_BLOCK_SIZE_BYTES as u32) }); } }); // Compute the final block and load it into data_in let mut tag_input = [0u8; AES_BLOCK_SIZE_BYTES]; // as per NIST SP 800-38D, algorithm 4, step 5, the last block // is len(A) || len(C), with the lengths in bits tag_input[0..8].copy_from_slice(&((aad_len * 8) as u64).to_be_bytes()); tag_input[8..16].copy_from_slice(&((text_len * 8) as u64).to_be_bytes()); self.load_data_block(&tag_input, 0)?; // Read out the tag. let tag_return = self.read_data_block_u32(); self.zeroize_internal(); Ok(tag_return) } fn read_data_block_u32(&mut self) -> AesBlock { let aes = self.aes.regs_mut(); while !aes.status().read().output_valid() {} AesBlock::read_from_reg(aes.data_out()) } fn read_data_block(&mut self, output: &mut [u8], block_num: usize) -> CaliptraResult<()> { // not possible but needed to prevent panic if block_num * AES_BLOCK_SIZE_BYTES >= output.len() { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?; } // read the data out let buffer = self.read_data_block_u32(); let buffer: [u8; AES_BLOCK_SIZE_BYTES] = transmute!(buffer); let output = &mut output[block_num * AES_BLOCK_SIZE_BYTES..]; let len = output.len().min(AES_BLOCK_SIZE_BYTES); let output = &mut output[..len]; output.copy_from_slice(&buffer[..len]); Ok(()) } fn load_data_block_u32(&mut self, data: AesBlock) { let aes = self.aes.regs_mut(); while !aes.status().read().input_ready() {} data.write_to_reg(aes.data_in()); } fn load_data_block(&mut self, data: &[u8], block_num: usize) -> CaliptraResult<()> { // not possible but needed to prevent panic if block_num * AES_BLOCK_SIZE_BYTES >= data.len() { Err(CaliptraError::RUNTIME_DRIVER_AES_INVALID_SLICE)?; } let data = &data[block_num * AES_BLOCK_SIZE_BYTES..]; let data = &data[..AES_BLOCK_SIZE_BYTES.min(data.len())]; let len = data.len(); let mut padded_data = [0u8; AES_BLOCK_SIZE_BYTES]; padded_data[..len].copy_from_slice(data); self.load_data_block_u32(transmute!(padded_data)); Ok(()) } pub fn gcm_set_text(&mut self, len: u32) { // set the mode and valid length self.with_aes(|aes, _| { wait_for_idle(&aes); for _ in 0..2 { aes.ctrl_gcm_shadowed() .write(|w| w.phase(GcmPhase::Text as u32).num_valid_bytes(len)); } wait_for_idle(&aes); }); } fn read_write_data_gcm( &mut self, input: &[u8], phase: GcmPhase, output: Option<&mut [u8]>, ) -> CaliptraResult<()> { let num_blocks = input.len().div_ceil(AES_BLOCK_SIZE_BYTES); // length of the last block let partial_text_len = input.len() % AES_BLOCK_SIZE_BYTES; let read_output = output.is_some(); let output = output.unwrap_or(&mut []); for i in 0..num_blocks { if i == 0 || ((i == num_blocks - 1) && (partial_text_len != 0)) { let num_bytes = if (i == num_blocks - 1) && partial_text_len != 0 { partial_text_len } else { AES_BLOCK_SIZE_BYTES }; // set the mode and valid length self.with_aes(|aes, _| { wait_for_idle(&aes); for _ in 0..2 { aes.ctrl_gcm_shadowed() .write(|w| w.phase(phase as u32).num_valid_bytes(num_bytes as u32)); } }); } self.load_data_block(input, i)?; if read_output { self.read_data_block(output, i)?; } } Ok(()) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] /// AES ECB Decrypt to KV. Used by OCP LOCK for MEK release. pub fn aes_256_ecb_decrypt_kv(&mut self, input: &LEArray4x16) -> CaliptraResult<()> { // Only KV 16 is allowed to be key KV. let mdk_slot = KeyReadArgs::new(KeyId::KeyId16); // Only KV 23 is allowed to be destination KV. let mek_slot = KeyWriteArgs::new(KeyId::KeyId23, KeyUsage::default().set_dma_data_en()); self.aes_256_ecb_decrypt_kv_internal(AesKey::KV(mdk_slot), mek_slot, input) } /// AES ECB Decrypt to KV. /// /// NOTE: Use `aes_256_ecb_decrypt_kv` so API invariants are enforced. pub fn aes_256_ecb_decrypt_kv_internal( &mut self, key: AesKey, output_kv: KeyWriteArgs, input: &LEArray4x16, ) -> CaliptraResult<()> { // Key is always in KV, always load before starting OP. self.load_key(key)?; // Set Dest KV in AES Ctrl register self.with_aes::<CaliptraResult<()>>(|aes, aes_clp| { wait_for_idle(&aes); KvAccess::begin_copy_to_kv( aes_clp.aes_kv_wr_status(), aes_clp.aes_kv_wr_ctrl(), output_kv, )?; Ok(()) })?; self.with_aes(|aes, _| { wait_for_idle(&aes); for _ in 0..2 { aes.ctrl_shadowed().write(|w| { w.key_len(AesKeyLen::_256 as u32) .mode(AesMode::Ecb as u32) .operation(AesOperation::Decrypt as u32) .manual_operation(false) .sideload(key.sideload()) }); } wait_for_idle(&aes); }); // Load 64 bytes of data for block_num in 0..input.as_bytes().chunks_exact(AES_BLOCK_SIZE_BYTES).len() { self.load_data_block(input.as_bytes(), block_num)?; } // Wait for HW to release result to KV self.with_aes::<CaliptraResult<()>>(|_, aes_clp| { match KvAccess::end_copy_to_kv(aes_clp.aes_kv_wr_status(), output_kv) { Ok(_) => Ok(()), Err(KvAccessErr::KeyRead) => { Err(CaliptraError::RUNTIME_DRIVER_AES_READ_KEY_KV_READ) } Err(KvAccessErr::KeyWrite) => Err(CaliptraError::RUNTIME_DRIVER_AES_WRITE_KV), _ => Err(CaliptraError::RUNTIME_DRIVER_AES_READ_KEY_KV_UNKNOWN), } })?;
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/doe.rs
drivers/src/doe.rs
/*++ Licensed under the Apache-2.0 license. File Name: doe.rs Abstract: File contains API for Deobfuscation Engine --*/ use crate::{wait, Array4x4, CaliptraResult, KeyId}; use caliptra_registers::doe::DoeReg; pub struct DeobfuscationEngine { doe: DoeReg, } impl DeobfuscationEngine { pub fn new(doe: DoeReg) -> Self { Self { doe } } /// Decrypt Unique Device Secret (UDS) /// /// # Arguments /// /// * `iv` - Initialization vector /// * `key_id` - Key vault key to store the decrypted UDS in pub fn decrypt_uds(&mut self, iv: &Array4x4, key_id: KeyId) -> CaliptraResult<()> { let doe = self.doe.regs_mut(); // Wait for hardware ready wait::until(|| doe.status().read().ready()); // Copy the initialization vector iv.write_to_reg(doe.iv()); // Trigger the command by programming the command and destination doe.ctrl() .write(|w| w.cmd(|w| w.doe_uds()).dest(key_id.into())); // Wait for command to complete wait::until(|| doe.status().read().valid()); Ok(()) } /// Decrypt Field Entropy /// /// # Arguments /// /// * `iv` - Initialization vector /// * `key_id` - Key vault key to store the decrypted field entropy in pub fn decrypt_field_entropy(&mut self, iv: &Array4x4, key_id: KeyId) -> CaliptraResult<()> { let doe = self.doe.regs_mut(); // Wait for hardware ready wait::until(|| doe.status().read().ready()); // Copy the initialization vector iv.write_to_reg(doe.iv()); // Trigger the command by programming the command and destination doe.ctrl() .write(|w| w.cmd(|w| w.doe_fe()).dest(key_id.into())); // Wait for command to complete wait::until(|| doe.status().read().valid()); Ok(()) } /// Decrypt HEK Seed /// /// # Arguments /// /// * `iv` - Initialization vector /// * `key_id` - Key vault key to store the decrypted HEK seed in pub fn decrypt_hek_seed(&mut self, iv: &Array4x4, key_id: KeyId) -> CaliptraResult<()> { let doe = self.doe.regs_mut(); // Wait for hardware ready wait::until(|| doe.status().read().ready()); // Copy the initialization vector iv.write_to_reg(doe.iv()); // Trigger the command by programming the command and destination doe.ctrl() .write(|w| w.cmd_ext(|w| w.doe_hek()).dest(key_id.into())); // Wait for command to complete wait::until(|| doe.status().read().valid()); Ok(()) } /// Clear loaded secrets /// /// This command clears following secrets from the hardware /// * Deobfuscation Key /// * Encrypted UDS /// * Encrypted Field entropy pub fn clear_secrets(&mut self) -> CaliptraResult<()> { let doe = self.doe.regs_mut(); // Wait for hardware ready wait::until(|| doe.status().read().ready()); // Trigger the command by programming the command and destination doe.ctrl().write(|w| w.cmd(|w| w.doe_clear_obf_secrets())); // Wait for command to complete wait::until(|| doe.status().read().valid()); Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/pic.rs
drivers/src/pic.rs
/*++ Licensed under the Apache-2.0 license. File Name: pic.rs Abstract: File contains a driver for the RISC-V VeeR EL2 programmable interrupt controller --*/ use caliptra_registers::el2_pic_ctrl::*; pub enum IntSource { DoeErr = 1, DoeNotif = 2, EccErr = 3, EccNotif = 4, HmacErr = 5, HmacNotif = 6, KvErr = 7, KvNotif = 8, Sha512Err = 9, Sha512Notif = 10, Sha256Err = 11, Sha256Notif = 12, QspiErr = 13, QspiNotif = 14, UartErr = 15, UartNotif = 16, I3cErr = 17, I3cNotif = 18, SocIfcErr = 19, SocIfcNotif = 20, Sha512AccErr = 21, Sha512AccNotif = 22, } impl From<IntSource> for usize { fn from(source: IntSource) -> Self { source as Self } } pub struct Pic { pic: El2PicCtrl, } impl Pic { pub fn new(pic: El2PicCtrl) -> Self { Self { pic } } pub fn int_set_max_priority(&mut self, source: IntSource) { self.pic .regs_mut() .meipl() .at(source.into()) .write(|v| v.priority(15)); #[cfg(feature = "riscv")] unsafe { core::arch::asm!("fence"); } } pub fn int_enable(&mut self, source: IntSource) { self.pic .regs_mut() .meie() .at(source.into()) .write(|v| v.inten(true)); #[cfg(feature = "riscv")] unsafe { core::arch::asm!("fence"); } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/persistent.rs
drivers/src/persistent.rs
// Licensed under the Apache-2.0 license use core::{marker::PhantomData, mem::size_of, ptr::addr_of}; #[cfg(feature = "runtime")] use caliptra_auth_man_types::{ AuthManifestImageMetadata, AuthManifestImageMetadataCollection, AUTH_MANIFEST_IMAGE_METADATA_MAX_COUNT, }; use caliptra_error::{CaliptraError, CaliptraResult}; use caliptra_image_types::{ImageManifest, SHA512_DIGEST_BYTE_SIZE}; #[cfg(feature = "runtime")] use dpe::{ExportedCdiHandle, U8Bool, MAX_HANDLES}; use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, TryFromBytes}; use zeroize::Zeroize; #[cfg(feature = "runtime")] use crate::sha2_512_384::SHA384_HASH_SIZE; use crate::{ fuse_log::FuseLogEntry, memory_layout, pcr_log::{MeasurementLogEntry, PcrLogEntry}, DataVault, FirmwareHandoffTable, LEArray4x8, Mldsa87PubKey, }; #[cfg(any(feature = "fmc", feature = "runtime"))] use crate::{FmcAliasCsrs, Mldsa87Signature}; #[cfg(feature = "runtime")] use crate::{pcr_reset::PcrResetCounter, KeyId}; #[cfg(any(feature = "fmc", feature = "runtime"))] pub use fw::*; pub const ECC384_MAX_IDEVID_CSR_SIZE: usize = 512; pub const ECC384_MAX_FMC_ALIAS_CSR_SIZE: usize = 768; pub const MAN1_SIZE: u32 = 17 * 1024; pub const MAN2_SIZE: u32 = 17 * 1024; pub const DATAVAULT_MAX_SIZE: u32 = 15 * 1024; pub const FHT_SIZE: u32 = 2 * 1024; pub const IDEVID_MLDSA_PUB_KEY_MAX_SIZE: u32 = 3 * 1024; pub const ECC_LDEVID_TBS_SIZE: u32 = 1024; pub const ECC_FMCALIAS_TBS_SIZE: u32 = 1024; pub const MLDSA_LDEVID_TBS_SIZE: u32 = 4 * 1024; pub const MLDSA_FMCALIAS_TBS_SIZE: u32 = 4 * 1024; pub const PCR_LOG_SIZE: u32 = 1024; pub const MEASUREMENT_LOG_SIZE: u32 = 1024; pub const FUSE_LOG_SIZE: u32 = 1024; pub const IDEVID_CSR_ENVELOP_SIZE: u32 = 9 * 1024; pub const MLDSA87_MAX_CSR_SIZE: usize = 7680; pub const PCR_LOG_MAX_COUNT: usize = 17; pub const FUSE_LOG_MAX_COUNT: usize = 62; pub const MEASUREMENT_MAX_COUNT: usize = 8; pub const CMB_AES_KEY_SHARE_SIZE: u32 = 32; pub const DOT_OWNER_PK_HASH_SIZE: u32 = 13 * 4; pub const OCP_LOCK_METADATA_SIZE: u32 = 8; pub const CLEARED_NON_FATAL_FW_ERROR_SIZE: u32 = 4; #[cfg(any(feature = "fmc", feature = "runtime"))] mod fw { pub const ECC_RTALIAS_TBS_SIZE: u32 = 1024; pub const MLDSA_RTALIAS_TBS_SIZE: u32 = 4 * 1024; pub const DPE_SIZE: u32 = 5 * 1024; pub const PCR_RESET_COUNTER_SIZE: u32 = 1024; pub const AUTH_MAN_IMAGE_METADATA_MAX_SIZE: u32 = 10 * 1024; pub const FMC_ALIAS_CSR_SIZE: u32 = 9 * 1024; pub const MLDSA_SIGNATURE_SIZE: u32 = 4628; } #[cfg(feature = "runtime")] // Currently only can export CDI once, but in the future we may want to support multiple exported // CDI handles at the cost of using more KeyVault slots. pub const EXPORTED_HANDLES_NUM: usize = 1; #[cfg(feature = "runtime")] #[derive(Clone, TryFromBytes, IntoBytes, KnownLayout, Zeroize)] pub struct ExportedCdiEntry { pub key: KeyId, pub handle: ExportedCdiHandle, pub active: U8Bool, } #[cfg(feature = "runtime")] #[derive(Clone, TryFromBytes, IntoBytes, KnownLayout, Zeroize)] pub struct ExportedCdiHandles { pub entries: [ExportedCdiEntry; EXPORTED_HANDLES_NUM], } pub type PcrLogArray = [PcrLogEntry; PCR_LOG_MAX_COUNT]; pub type FuseLogArray = [FuseLogEntry; FUSE_LOG_MAX_COUNT]; pub type StashMeasurementArray = [MeasurementLogEntry; MEASUREMENT_MAX_COUNT]; #[cfg(feature = "runtime")] pub type AuthManifestImageMetadataList = [AuthManifestImageMetadata; AUTH_MANIFEST_IMAGE_METADATA_MAX_COUNT]; #[derive(Clone, Immutable, IntoBytes, KnownLayout, TryFromBytes, Zeroize)] #[repr(C)] pub struct Ecc384IdevIdCsr { pub csr_len: u32, pub csr: [u8; ECC384_MAX_IDEVID_CSR_SIZE], } #[derive(Clone, FromBytes, Immutable, IntoBytes, KnownLayout, Zeroize)] #[repr(C)] pub struct Mldsa87IdevIdCsr { pub csr_len: u32, pub csr: [u8; MLDSA87_MAX_CSR_SIZE], } impl Default for Ecc384IdevIdCsr { fn default() -> Self { Self { csr_len: Self::UNPROVISIONED_CSR, csr: [0; ECC384_MAX_IDEVID_CSR_SIZE], } } } impl Default for Mldsa87IdevIdCsr { fn default() -> Self { Self { csr_len: Self::UNPROVISIONED_CSR, csr: [0; MLDSA87_MAX_CSR_SIZE], } } } macro_rules! impl_idevid_csr { ($type:ty, $size:expr) => { impl $type { /// The `csr_len` field is set to this constant when a ROM image supports CSR generation but /// the CSR generation flag was not enabled. /// /// This is used by the runtime to distinguish ROM images that support CSR generation from /// ones that do not. /// /// u32::MAX is too large to be a valid CSR, so we use it to encode this state. pub const UNPROVISIONED_CSR: u32 = u32::MAX; /// Get the CSR buffer pub fn get(&self) -> Option<&[u8]> { self.csr.get(..self.csr_len as usize) } /// Create `Self` from a csr slice. `csr_len` MUST be the actual length of the csr. pub fn new(csr_buf: &[u8], csr_len: usize) -> CaliptraResult<Self> { if csr_len >= $size { return Err(CaliptraError::ROM_IDEVID_INVALID_CSR); } let mut _self = Self { csr_len: csr_len as u32, csr: [0; $size], }; _self.csr[..csr_len].copy_from_slice(&csr_buf[..csr_len]); Ok(_self) } /// Get the length of the CSR in bytes. pub fn get_csr_len(&self) -> u32 { self.csr_len } /// Check if the CSR was unprovisioned pub fn is_unprovisioned(&self) -> bool { self.csr_len == Self::UNPROVISIONED_CSR } } }; } impl_idevid_csr!(Ecc384IdevIdCsr, ECC384_MAX_IDEVID_CSR_SIZE); impl_idevid_csr!(Mldsa87IdevIdCsr, MLDSA87_MAX_CSR_SIZE); pub type Hmac512Tag = [u8; SHA512_DIGEST_BYTE_SIZE]; pub const IDEVID_CSR_ENVELOP_MARKER: u32 = 0x43_5352; /// Calipatra IDEVID CSR Envelope #[repr(C)] #[derive(Clone, IntoBytes, Immutable, KnownLayout, TryFromBytes, Zeroize)] pub struct InitDevIdCsrEnvelope { /// Marker pub marker: u32, /// Size of the CSR Envelope pub size: u32, /// ECC CSR pub ecc_csr: Ecc384IdevIdCsr, /// MLDSA CSR pub mldsa_csr: Mldsa87IdevIdCsr, /// CSR MAC pub csr_mac: Hmac512Tag, } impl Default for InitDevIdCsrEnvelope { fn default() -> Self { InitDevIdCsrEnvelope { marker: IDEVID_CSR_ENVELOP_MARKER, size: size_of::<InitDevIdCsrEnvelope>() as u32, ecc_csr: Ecc384IdevIdCsr::default(), mldsa_csr: Mldsa87IdevIdCsr::default(), csr_mac: [0u8; SHA512_DIGEST_BYTE_SIZE], } } } pub mod fmc_alias_csr { use super::*; #[derive(Clone, TryFromBytes, IntoBytes, KnownLayout, Zeroize)] #[repr(C)] pub struct FmcAliasCsrs { pub ecc_csr_len: u32, pub ecc_csr: [u8; ECC384_MAX_FMC_ALIAS_CSR_SIZE], pub mldsa_csr_len: u32, pub mldsa_csr: [u8; MLDSA87_MAX_CSR_SIZE], } impl Default for FmcAliasCsrs { fn default() -> Self { Self { ecc_csr_len: Self::UNPROVISIONED_CSR, ecc_csr: [0; ECC384_MAX_FMC_ALIAS_CSR_SIZE], mldsa_csr_len: Self::UNPROVISIONED_CSR, mldsa_csr: [0; MLDSA87_MAX_CSR_SIZE], } } } impl FmcAliasCsrs { /// The `csr_len` field is set to this constant when a ROM image supports CSR generation but /// the CSR generation flag was not enabled. /// /// This is used by the runtime to distinguish ROM images that support CSR generation from /// ones that do not. /// /// u32::MAX is too large to be a valid CSR, so we use it to encode this state. pub const UNPROVISIONED_CSR: u32 = u32::MAX; /// Get the ECC CSR pub fn get_ecc_csr(&self) -> Option<&[u8]> { self.ecc_csr.get(..self.ecc_csr_len as usize) } /// Get the MLDSA CSR pub fn get_mldsa_csr(&self) -> Option<&[u8]> { self.mldsa_csr.get(..self.mldsa_csr_len as usize) } /// Get the length of the ECC CSR in bytes. pub fn get_ecc_csr_len(&self) -> u32 { self.ecc_csr_len } /// Get the length of the MLDSA CSR in bytes. pub fn get_mldsa_csr_len(&self) -> u32 { self.mldsa_csr_len } /// Check if the ECC CSR was unprovisioned pub fn is_ecc_csr_unprovisioned(&self) -> bool { self.ecc_csr_len == Self::UNPROVISIONED_CSR } /// Check if the MLDSA CSR was unprovisioned pub fn is_mldsa_csr_unprovisioned(&self) -> bool { self.mldsa_csr_len == Self::UNPROVISIONED_CSR } } } #[derive(TryFromBytes, IntoBytes, KnownLayout, Zeroize)] #[repr(C)] pub struct DOT_OWNER_PK_HASH { pub owner_pk_hash: [u32; 12], pub valid: bool, reserved: [u8; 3], } #[derive(TryFromBytes, IntoBytes, KnownLayout, Zeroize)] #[repr(C)] pub struct OcpLockMetadata { pub total_hek_seed_slots: u16, pub active_hek_seed_slots: u16, pub hek_seed_state: u16, pub hek_available: bool, reserved: [u8; 1], } #[derive(TryFromBytes, IntoBytes, KnownLayout, Zeroize)] #[repr(C)] pub struct PersistentData { #[cfg(any(feature = "fmc", feature = "runtime"))] pub fw: FwPersistentData, pub rom: RomPersistentData, } impl PersistentData { pub fn assert_matches_layout() { RomPersistentData::assert_matches_layout(); #[cfg(any(feature = "fmc", feature = "runtime"))] FwPersistentData::assert_matches_layout(); } } #[derive(TryFromBytes, IntoBytes, KnownLayout, Zeroize)] #[repr(C)] pub struct RomPersistentData { // NOTE: Add all new fields to the top of the struct because it is at the bottom of DCCM and // needs to grow upwards pub manifest1: ImageManifest, reserved0: [u8; MAN1_SIZE as usize - size_of::<ImageManifest>()], pub manifest2: ImageManifest, reserved1: [u8; MAN2_SIZE as usize - size_of::<ImageManifest>()], #[zeroize(skip)] pub data_vault: DataVault, reserved1_1: [u8; DATAVAULT_MAX_SIZE as usize - size_of::<DataVault>()], pub fht: FirmwareHandoffTable, reserved2: [u8; FHT_SIZE as usize - size_of::<FirmwareHandoffTable>()], pub idevid_mldsa_pub_key: Mldsa87PubKey, reserved2_1: [u8; IDEVID_MLDSA_PUB_KEY_MAX_SIZE as usize - size_of::<Mldsa87PubKey>()], pub ecc_ldevid_tbs: [u8; ECC_LDEVID_TBS_SIZE as usize], pub ecc_fmcalias_tbs: [u8; ECC_FMCALIAS_TBS_SIZE as usize], pub mldsa_ldevid_tbs: [u8; MLDSA_LDEVID_TBS_SIZE as usize], pub mldsa_fmcalias_tbs: [u8; MLDSA_FMCALIAS_TBS_SIZE as usize], pub pcr_log: PcrLogArray, reserved3: [u8; PCR_LOG_SIZE as usize - size_of::<PcrLogArray>()], pub measurement_log: StashMeasurementArray, reserved4: [u8; MEASUREMENT_LOG_SIZE as usize - size_of::<StashMeasurementArray>()], pub fuse_log: FuseLogArray, reserved5: [u8; FUSE_LOG_SIZE as usize - size_of::<FuseLogArray>()], pub idevid_csr_envelop: InitDevIdCsrEnvelope, reserved6: [u8; IDEVID_CSR_ENVELOP_SIZE as usize - size_of::<InitDevIdCsrEnvelope>()], pub cmb_aes_key_share0: LEArray4x8, pub cmb_aes_key_share1: LEArray4x8, pub dot_owner_pk_hash: DOT_OWNER_PK_HASH, pub cleared_non_fatal_fw_error: u32, // TODO(clundin): For runtime we may want to gate this behind a feature flag. pub ocp_lock_metadata: OcpLockMetadata, /// Major version. pub major_version: u16, /// Minor version. Initially written by ROM but may be changed to a higher version by FMC. pub minor_version: u16, /// Keep this as the bottom of the struct pub marker: u32, } impl RomPersistentData { pub const MAGIC: u32 = u32::from_be_bytes(*b"ROMP"); pub const MAJOR_VERSION: u16 = 1; pub const MINOR_VERSION: u16 = 0; pub fn assert_matches_layout() { const P: *const PersistentData = memory_layout::PERSISTENT_DATA_ORG as *const PersistentData; unsafe { #[cfg(any(feature = "fmc", feature = "runtime"))] let mut persistent_data_offset = size_of::<FwPersistentData>() as u32; #[cfg(not(any(feature = "fmc", feature = "runtime")))] let mut persistent_data_offset = 0; assert_eq!( addr_of!((*P).rom.manifest1) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += MAN1_SIZE; assert_eq!( addr_of!((*P).rom.manifest2) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += MAN2_SIZE; assert_eq!( addr_of!((*P).rom.data_vault) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += DATAVAULT_MAX_SIZE; assert_eq!( addr_of!((*P).rom.fht) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += FHT_SIZE; assert_eq!( addr_of!((*P).rom.idevid_mldsa_pub_key) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += IDEVID_MLDSA_PUB_KEY_MAX_SIZE; assert_eq!( addr_of!((*P).rom.ecc_ldevid_tbs) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += ECC_LDEVID_TBS_SIZE; assert_eq!( addr_of!((*P).rom.ecc_fmcalias_tbs) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += ECC_FMCALIAS_TBS_SIZE; assert_eq!( addr_of!((*P).rom.mldsa_ldevid_tbs) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += MLDSA_LDEVID_TBS_SIZE; assert_eq!( addr_of!((*P).rom.mldsa_fmcalias_tbs) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += MLDSA_FMCALIAS_TBS_SIZE; assert_eq!( addr_of!((*P).rom.pcr_log) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += PCR_LOG_SIZE; assert_eq!( addr_of!((*P).rom.measurement_log) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += MEASUREMENT_LOG_SIZE; assert_eq!( addr_of!((*P).rom.fuse_log) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += FUSE_LOG_SIZE; assert_eq!( addr_of!((*P).rom.idevid_csr_envelop) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += IDEVID_CSR_ENVELOP_SIZE; assert_eq!( addr_of!((*P).rom.cmb_aes_key_share0) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += CMB_AES_KEY_SHARE_SIZE; assert_eq!( addr_of!((*P).rom.cmb_aes_key_share1) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += CMB_AES_KEY_SHARE_SIZE; assert_eq!( addr_of!((*P).rom.dot_owner_pk_hash) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += DOT_OWNER_PK_HASH_SIZE; assert_eq!( addr_of!((*P).rom.cleared_non_fatal_fw_error) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += CLEARED_NON_FATAL_FW_ERROR_SIZE; assert_eq!( addr_of!((*P).rom.ocp_lock_metadata) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += OCP_LOCK_METADATA_SIZE; assert_eq!( addr_of!((*P).rom.major_version) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += 2; assert_eq!( addr_of!((*P).rom.minor_version) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += 2; assert_eq!( addr_of!((*P).rom.marker) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); assert_eq!(P.add(1) as u32, memory_layout::ROM_DATA_ORG); } } } #[cfg(any(feature = "fmc", feature = "runtime"))] #[derive(TryFromBytes, IntoBytes, KnownLayout, Zeroize)] #[repr(C)] pub struct FwPersistentData { // NOTE: Add all new fields to the top of the struct because it is at the bottom of DCCM and // needs to grow upwards #[cfg(feature = "runtime")] pub dpe: DpePersistentData, #[cfg(feature = "runtime")] reserved6: [u8; DPE_SIZE as usize - size_of::<DpePersistentData>()], #[cfg(not(feature = "runtime"))] dpe: [u8; DPE_SIZE as usize], pub ecc_rtalias_tbs: [u8; ECC_RTALIAS_TBS_SIZE as usize], pub mldsa_rtalias_tbs: [u8; MLDSA_RTALIAS_TBS_SIZE as usize], pub rtalias_mldsa_tbs_size: u16, reserved1: [u8; 2], pub rt_dice_mldsa_sign: Mldsa87Signature, #[cfg(feature = "runtime")] pub pcr_reset: PcrResetCounter, #[cfg(feature = "runtime")] reserved7: [u8; PCR_RESET_COUNTER_SIZE as usize - size_of::<PcrResetCounter>()], #[cfg(not(feature = "runtime"))] pcr_reset: [u8; PCR_RESET_COUNTER_SIZE as usize], #[cfg(feature = "runtime")] pub auth_manifest_image_metadata_col: AuthManifestImageMetadataCollection, #[cfg(feature = "runtime")] pub auth_manifest_digest: [u32; SHA384_HASH_SIZE / 4], #[cfg(feature = "runtime")] reserved9: [u8; AUTH_MAN_IMAGE_METADATA_MAX_SIZE as usize - (SHA384_HASH_SIZE + size_of::<AuthManifestImageMetadataCollection>())], #[cfg(not(feature = "runtime"))] pub auth_manifest_image_metadata_col: [u8; AUTH_MAN_IMAGE_METADATA_MAX_SIZE as usize], pub fmc_alias_csr: FmcAliasCsrs, reserved4: [u8; FMC_ALIAS_CSR_SIZE as usize - size_of::<FmcAliasCsrs>()], pub mcu_firmware_loaded: u32, pub version: u32, /// Keep this as the bottom of the struct pub marker: u32, } #[cfg(any(feature = "fmc", feature = "runtime"))] impl FwPersistentData { pub const MAGIC: u32 = u32::from_be_bytes(*b"FWPD"); pub const VERSION: u32 = 1; pub fn assert_matches_layout() { const P: *const PersistentData = memory_layout::PERSISTENT_DATA_ORG as *const PersistentData; unsafe { let mut persistent_data_offset = 0; assert_eq!( addr_of!((*P).fw.dpe) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += DPE_SIZE; assert_eq!( addr_of!((*P).fw.ecc_rtalias_tbs) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += ECC_RTALIAS_TBS_SIZE; assert_eq!( addr_of!((*P).fw.mldsa_rtalias_tbs) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += MLDSA_RTALIAS_TBS_SIZE; assert_eq!( addr_of!((*P).fw.rtalias_mldsa_tbs_size) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += 4; assert_eq!( addr_of!((*P).fw.rt_dice_mldsa_sign) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += MLDSA_SIGNATURE_SIZE; assert_eq!( addr_of!((*P).fw.pcr_reset) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += PCR_RESET_COUNTER_SIZE; assert_eq!( addr_of!((*P).fw.auth_manifest_image_metadata_col) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += AUTH_MAN_IMAGE_METADATA_MAX_SIZE; assert_eq!( addr_of!((*P).fw.fmc_alias_csr) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += FMC_ALIAS_CSR_SIZE; assert_eq!( addr_of!((*P).fw.mcu_firmware_loaded) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += 4; assert_eq!( addr_of!((*P).fw.version) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); persistent_data_offset += 4; assert_eq!( addr_of!((*P).fw.marker) as u32, memory_layout::PERSISTENT_DATA_ORG + persistent_data_offset ); } } } pub struct PersistentDataAccessor { // This field is here to ensure that Self::new() is the only way // to create this type. _phantom: PhantomData<()>, } impl PersistentDataAccessor { /// # Safety /// /// It is unsound for more than one of these objects to exist simultaneously. /// DO NOT CALL FROM RANDOM APPLICATION CODE! pub unsafe fn new() -> Self { Self { _phantom: Default::default(), } } /// # Safety /// /// DO NOT use unsafe code to modify any of this persistent memory /// as long as there exists any copies of the returned reference. #[inline(always)] pub fn get(&self) -> &PersistentData { // WARNING: The returned lifetime elided from `self` is critical for // safety. Do not change this API without review by a Rust expert. unsafe { ref_from_addr(memory_layout::PERSISTENT_DATA_ORG) } } /// # Safety /// /// During the lifetime of the returned reference, it is unsound to use any /// unsafe mechanism to read or write to this memory. #[inline(always)] pub fn get_mut(&mut self) -> &mut PersistentData { // WARNING: The returned lifetime elided from `self` is critical for // safety. Do not change this API without review by a Rust expert. unsafe { ref_mut_from_addr(memory_layout::PERSISTENT_DATA_ORG) } } } #[cfg(feature = "runtime")] #[repr(C)] #[derive(IntoBytes, TryFromBytes, KnownLayout, Zeroize)] pub struct DpePersistentData { pub state: dpe::State, pub context_tags: [u32; MAX_HANDLES], pub context_has_tag: [U8Bool; MAX_HANDLES], pub attestation_disabled: U8Bool, pub runtime_cmd_active: U8Bool, // to satisfy explicit padding reserved0: [u8; 2], pub exported_cdi_slots: ExportedCdiHandles, pub pl0_context_limit: u8, pub pl1_context_limit: u8, } #[cfg(feature = "runtime")] const _: () = assert!(size_of::<DpePersistentData>() <= DPE_SIZE as usize); #[inline(always)] unsafe fn ref_from_addr<'a, T: TryFromBytes>(addr: u32) -> &'a T { // LTO should be able to optimize out the assertions to maintain panic_is_missing // dereferencing zero is undefined behavior assert!(addr != 0); assert!(addr as usize % core::mem::align_of::<T>() == 0); assert!(core::mem::size_of::<u32>() == core::mem::size_of::<*const T>()); &*(addr as *const T) } #[inline(always)] unsafe fn ref_mut_from_addr<'a, T: TryFromBytes>(addr: u32) -> &'a mut T { // LTO should be able to optimize out the assertions to maintain panic_is_missing // dereferencing zero is undefined behavior assert!(addr != 0); assert!(addr as usize % core::mem::align_of::<T>() == 0); assert!(core::mem::size_of::<u32>() == core::mem::size_of::<*const T>()); &mut *(addr as *mut T) } #[cfg(test)] mod tests { use super::*; #[test] fn test_layout() { // NOTE: It's not good enough to test this from the host; we also need // to call assert_matches_layout() in a risc-v test. PersistentData::assert_matches_layout(); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/mldsa87.rs
drivers/src/mldsa87.rs
/*++ Licensed under the Apache-2.0 license. File Name: Mldsa87.rs Abstract: File contains API for MLDSA-87 Cryptography operations --*/ #![allow(dead_code)] use crate::{ array::{LEArray4x1157, LEArray4x1224, LEArray4x16, LEArray4x648, LEArray4x8}, kv_access::{KvAccess, KvAccessErr}, wait, CaliptraError, CaliptraResult, KeyReadArgs, Trng, }; #[cfg(not(feature = "no-cfi"))] use caliptra_cfi_derive::cfi_impl_fn; use caliptra_cfi_derive::Launder; use caliptra_cfi_lib::{ cfi_assert_eq, cfi_assert_eq_16_words, cfi_assert_ne_16_words, cfi_launder, }; use caliptra_registers::abr::{AbrReg, RegisterBlock}; use zerocopy::FromBytes; use zerocopy::{IntoBytes, Unalign}; #[must_use] #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Launder)] pub enum Mldsa87Result { Success = 0xAAAAAAAA, SigVerifyFailed = 0x55555555, } /// MLDSA-87 Public Key pub type Mldsa87PubKey = LEArray4x648; /// MLDSA-87 Private Key pub type Mldsa87PrivKey = LEArray4x1224; /// MLDSA-87 Signature pub type Mldsa87Signature = LEArray4x1157; /// MLDSA-87 Message (64 Bytes) pub type Mldsa87Msg = LEArray4x16; /// MLDSA-87 External Mu (64 Bytes) pub type Mldsa87Mu = LEArray4x16; /// MLDSA-87 Signature RND pub type Mldsa87SignRnd = LEArray4x8; type Mldsa87VerifyRes = LEArray4x16; pub const MLDSA87_VERIFY_RES_WORD_LEN: usize = 16; // Control register constants. const KEYGEN: u32 = 1; const SIGN: u32 = 2; const VERIFY: u32 = 3; const KEYGEN_SIGN: u32 = 4; /// MLDSA-87 Seed #[derive(Debug, Copy, Clone)] pub enum Mldsa87Seed<'a> { /// Array Array4x8(&'a LEArray4x8), /// Key Vault Key Key(KeyReadArgs), /// Private Key PrivKey(&'a Mldsa87PrivKey), } /// What type of information is being signed/verified. enum SigData<'a> { /// Raw Sha512 hash Msg(&'a Mldsa87Msg), /// External Mu (64 Bytes) Mu(&'a Mldsa87Mu), } impl<'a> From<&'a LEArray4x8> for Mldsa87Seed<'a> { /// Converts to this type from the input type. fn from(value: &'a LEArray4x8) -> Self { Self::Array4x8(value) } } impl From<KeyReadArgs> for Mldsa87Seed<'_> { /// Converts to this type from the input type. fn from(value: KeyReadArgs) -> Self { Self::Key(value) } } impl<'a> From<&'a Mldsa87PrivKey> for Mldsa87Seed<'a> { /// Converts to this type from the input type. fn from(value: &'a Mldsa87PrivKey) -> Self { Self::PrivKey(value) } } /// MLDSA-87 API pub struct Mldsa87 { mldsa87: AbrReg, } impl Mldsa87 { pub fn new(mldsa87: AbrReg) -> Self { Self { mldsa87 } } fn generate_iv(trng: &mut Trng) -> CaliptraResult<LEArray4x16> { let iv = trng.generate16()?; Ok(LEArray4x16::from(iv)) } // Wait on the provided condition OR the error condition defined in this function // In the event of the error condition being set, clear the error bits and return an error fn wait<F>(regs: RegisterBlock<ureg::RealMmioMut>, condition: F) -> CaliptraResult<()> where F: Fn() -> bool, { let err_condition = || { (u32::from(regs.intr_block_rf().error_global_intr_r().read()) != 0) || (u32::from(regs.intr_block_rf().error_internal_intr_r().read()) != 0) }; // Wait for either the given condition or the error condition wait::until(|| (condition() || err_condition())); if err_condition() { // Clear the errors // error_global_intr_r is RO regs.intr_block_rf() .error_internal_intr_r() .write(|_| u32::from(regs.intr_block_rf().error_internal_intr_r().read()).into()); return Err(CaliptraError::DRIVER_MLDSA87_HW_ERROR); } Ok(()) } /// Generate MLDSA-87 Key Pair /// /// # Arguments /// /// * `seed` - Either an array of 4x8 bytes or a key vault key to use as seed. /// * `trng` - TRNG driver instance. /// * `priv_key_out` - Optional output parameter to store the private key. /// /// # Returns /// /// * `Mldsa87PubKey` - Generated MLDSA-87 Public Key pub fn key_pair( &mut self, seed: Mldsa87Seed, trng: &mut Trng, priv_key_out: Option<&mut Mldsa87PrivKey>, ) -> CaliptraResult<Mldsa87PubKey> { let mldsa = self.mldsa87.regs_mut(); // Wait for hardware ready Mldsa87::wait(mldsa, || mldsa.mldsa_status().read().ready())?; // Copy seed to the hardware match seed { Mldsa87Seed::Array4x8(arr) => arr.write_to_reg(mldsa.mldsa_seed()), Mldsa87Seed::Key(key) => KvAccess::copy_from_kv( key, mldsa.kv_mldsa_seed_rd_status(), mldsa.kv_mldsa_seed_rd_ctrl(), ) .map_err(|err| err.into_read_seed_err())?, Mldsa87Seed::PrivKey(_) => Err(CaliptraError::DRIVER_MLDSA87_KEY_GEN_SEED_BAD_USAGE)?, } // Generate an IV. let iv = Self::generate_iv(trng)?; iv.write_to_reg(mldsa.entropy()); // Program the command register for key generation mldsa.mldsa_ctrl().write(|w| w.ctrl(KEYGEN)); // Wait for hardware ready Mldsa87::wait(mldsa, || mldsa.mldsa_status().read().valid())?; // Copy pubkey let pubkey = Mldsa87PubKey::read_from_reg(mldsa.mldsa_pubkey()); // Copy private key if requested. if let Some(priv_key) = priv_key_out { *priv_key = Mldsa87PrivKey::read_from_reg(mldsa.mldsa_privkey_out()); } // Clear the hardware when done mldsa.mldsa_ctrl().write(|w| w.zeroize(true)); Ok(pubkey) // TODO check that pubkey is valid? } fn sign_internal( &mut self, seed: Mldsa87Seed, pub_key: &Mldsa87PubKey, data: SigData, sign_rnd: &Mldsa87SignRnd, trng: &mut Trng, ) -> CaliptraResult<Mldsa87Signature> { let mut gen_keypair = true; let external_mu = matches!(data, SigData::Mu(_)); let mldsa = self.mldsa87.regs_mut(); // Wait for hardware ready Mldsa87::wait(mldsa, || mldsa.mldsa_status().read().ready())?; // Copy seed or the private key to the hardware match seed { Mldsa87Seed::Array4x8(arr) => arr.write_to_reg(mldsa.mldsa_seed()), Mldsa87Seed::Key(key) => KvAccess::copy_from_kv( key, mldsa.kv_mldsa_seed_rd_status(), mldsa.kv_mldsa_seed_rd_ctrl(), ) .map_err(|err| err.into_read_seed_err())?, Mldsa87Seed::PrivKey(priv_key) => { gen_keypair = false; priv_key.write_to_reg(mldsa.mldsa_privkey_in()) } } // Copy data to corresponding registers match data { SigData::Msg(msg) => msg.write_to_reg(mldsa.mldsa_msg()), SigData::Mu(mu) => mu.write_to_reg(mldsa.mldsa_external_mu()), } // Sign RND, TODO do we want deterministic? sign_rnd.write_to_reg(mldsa.mldsa_sign_rnd()); // Generate an IV. let iv = Self::generate_iv(trng)?; iv.write_to_reg(mldsa.entropy()); // Program the command register for key generation mldsa.mldsa_ctrl().write(|w| { w.ctrl(if gen_keypair { KEYGEN_SIGN } else { SIGN }) .external_mu(external_mu) }); // Wait for hardware ready Mldsa87::wait(mldsa, || mldsa.mldsa_status().read().valid())?; // Copy signature let signature = Mldsa87Signature::read_from_reg(mldsa.mldsa_signature()); // Clear the hardware. mldsa.mldsa_ctrl().write(|w| w.zeroize(true)); let result = self.verify_internal(pub_key, data, &signature)?; if result == Mldsa87Result::Success { cfi_assert_eq(cfi_launder(result), Mldsa87Result::Success); Ok(signature) } else { Err(CaliptraError::DRIVER_MLDSA87_SIGN_VALIDATION_FAILED) } } /// Sign the digest with specified private key. To defend against glitching /// attacks that could expose the private key, this function also verifies /// the generated signature. /// /// # Arguments /// /// * `seed` - Key Vault slot containing the seed for deterministic MLDSA Key Pair generation. /// * `pub_key` - Public key to verify the signature with. /// * `msg` - Message to sign. /// * `sign_rnd` - Signature RND input /// * `trng` - TRNG driver instance. /// /// # Returns /// /// * `Mldsa87Signature` - Generated signature pub fn sign( &mut self, seed: Mldsa87Seed, pub_key: &Mldsa87PubKey, msg: &Mldsa87Msg, sign_rnd: &Mldsa87SignRnd, trng: &mut Trng, ) -> CaliptraResult<Mldsa87Signature> { self.sign_internal(seed, pub_key, SigData::Msg(msg), sign_rnd, trng) } /// Sign the pre-computed external mu with specified private key. To defend /// against glitching attacks that could expose the private key, this /// function also verifies the generated signature. /// /// # Arguments /// /// * `seed` - Key Vault slot containing the seed for deterministic MLDSA Key Pair generation. /// * `pub_key` - Public key to verify the signature with. /// * `mu` - External mu to sign. /// * `sign_rnd` - Signature RND input /// * `trng` - TRNG driver instance. /// /// # Returns /// /// * `Mldsa87Signature` - Generated signature pub fn sign_external_mu( &mut self, seed: Mldsa87Seed, pub_key: &Mldsa87PubKey, mu: &Mldsa87Mu, sign_rnd: &Mldsa87SignRnd, trng: &mut Trng, ) -> CaliptraResult<Mldsa87Signature> { self.sign_internal(seed, pub_key, SigData::Mu(mu), sign_rnd, trng) } fn program_var_msg(mldsa: RegisterBlock<ureg::RealMmioMut>, msg: &[u8]) -> CaliptraResult<()> { // Wait for stream ready or valid status. Mldsa87::wait(mldsa, || { mldsa.mldsa_status().read().msg_stream_ready() || mldsa.mldsa_status().read().valid() })?; // Check if the operation completed prematurely. // This can happen in case of verification where the signature is invalid. // In this case, we should not proceed with streaming the message. if mldsa.mldsa_status().read().valid() { return Ok(()); } // Reset the message strobe register. mldsa.mldsa_msg_strobe().write(|s| s.strobe(0xF)); // Stream the message to the hardware. let dwords = msg.chunks_exact(size_of::<u32>()); let remainder = dwords.remainder(); for dword in dwords { let dw = <Unalign<u32>>::read_from_bytes(dword).unwrap(); mldsa.mldsa_msg().at(0).write(|_| dw.get()); } let last_strobe = match remainder.len() { 0 => 0b0000, 1 => 0b0001, 2 => 0b0011, 3 => 0b0111, _ => 0b0000, // should never happen }; mldsa.mldsa_msg_strobe().write(|s| s.strobe(last_strobe)); // Write last dword; 0 for no remainder. let mut last_word = 0_u32; last_word.as_mut_bytes()[..remainder.len()].copy_from_slice(remainder); mldsa.mldsa_msg().at(0).write(|_| last_word); // Wait for status to be valid Mldsa87::wait(mldsa, || mldsa.mldsa_status().read().valid())?; Ok(()) } pub fn sign_var( &mut self, seed: Mldsa87Seed, pub_key: &Mldsa87PubKey, msg: &[u8], sign_rnd: &Mldsa87SignRnd, trng: &mut Trng, ) -> CaliptraResult<Mldsa87Signature> { let mut gen_keypair = true; let mldsa = self.mldsa87.regs_mut(); // Wait for hardware ready Mldsa87::wait(mldsa, || mldsa.mldsa_status().read().ready())?; // Sign RND. sign_rnd.write_to_reg(mldsa.mldsa_sign_rnd()); // Generate an IV. let iv = Self::generate_iv(trng)?; iv.write_to_reg(mldsa.entropy()); // Copy seed or the private key to the hardware match seed { Mldsa87Seed::Array4x8(arr) => arr.write_to_reg(mldsa.mldsa_seed()), Mldsa87Seed::Key(key) => KvAccess::copy_from_kv( key, mldsa.kv_mldsa_seed_rd_status(), mldsa.kv_mldsa_seed_rd_ctrl(), ) .map_err(|err| err.into_read_seed_err())?, Mldsa87Seed::PrivKey(priv_key) => { gen_keypair = false; priv_key.write_to_reg(mldsa.mldsa_privkey_in()) } } // Program the command register for key generation mldsa.mldsa_ctrl().write(|w| { w.ctrl(if gen_keypair { KEYGEN_SIGN } else { SIGN }) .stream_msg(true) }); // Program the message to the hardware Mldsa87::program_var_msg(mldsa, msg)?; // Copy signature let signature = Mldsa87Signature::read_from_reg(mldsa.mldsa_signature()); // Clear the hardware. mldsa.mldsa_ctrl().write(|w| w.zeroize(true)); let result = self.verify_var(pub_key, msg, &signature)?; if result == Mldsa87Result::Success { cfi_assert_eq(cfi_launder(result), Mldsa87Result::Success); Ok(signature) } else { Err(CaliptraError::DRIVER_MLDSA87_SIGN_VALIDATION_FAILED) } } /// Common setup for verification functions /// Returns the truncated signature for later comparison fn verify_common_setup( &mut self, pub_key: &Mldsa87PubKey, signature: &Mldsa87Signature, ) -> CaliptraResult<[u32; MLDSA87_VERIFY_RES_WORD_LEN]> { #[cfg(feature = "fips-test-hooks")] unsafe { crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::MLDSA_VERIFY_FAILURE)? } let truncated_signature = &signature.0[..MLDSA87_VERIFY_RES_WORD_LEN]; let empty_verify_res = [0; MLDSA87_VERIFY_RES_WORD_LEN]; if truncated_signature == empty_verify_res { Err(CaliptraError::DRIVER_MLDSA87_UNSUPPORTED_SIGNATURE)?; } cfi_assert_ne_16_words(truncated_signature.try_into().unwrap(), &empty_verify_res); let mldsa = self.mldsa87.regs_mut(); // Wait for hardware ready Mldsa87::wait(mldsa, || mldsa.mldsa_status().read().ready())?; // Copy pubkey pub_key.write_to_reg(mldsa.mldsa_pubkey()); // Copy signature signature.write_to_reg(mldsa.mldsa_signature()); Ok(truncated_signature.try_into().unwrap()) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] fn verify_internal( &mut self, pub_key: &Mldsa87PubKey, data: SigData, signature: &Mldsa87Signature, ) -> CaliptraResult<Mldsa87Result> { let truncated_signature = self.verify_common_setup(pub_key, signature)?; let external_mu = matches!(data, SigData::Mu(_)); let mldsa = self.mldsa87.regs_mut(); // Copy data to corresponding registers match data { SigData::Msg(msg) => msg.write_to_reg(mldsa.mldsa_msg()), SigData::Mu(mu) => mu.write_to_reg(mldsa.mldsa_external_mu()), } // Program the command register for signature verification and optionally external mu. mldsa .mldsa_ctrl() .write(|w| w.ctrl(VERIFY).external_mu(external_mu)); // Wait for status to be valid Mldsa87::wait(mldsa, || mldsa.mldsa_status().read().valid())?; // Copy the random value let verify_res = LEArray4x16::read_from_reg(mldsa.mldsa_verify_res()); // Clear the hardware when done mldsa.mldsa_ctrl().write(|w| w.zeroize(true)); let result = if verify_res.0 == truncated_signature { cfi_assert_eq_16_words(&verify_res.0, &truncated_signature); Mldsa87Result::Success } else { Mldsa87Result::SigVerifyFailed }; Ok(result) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn verify( &mut self, pub_key: &Mldsa87PubKey, msg: &Mldsa87Msg, signature: &Mldsa87Signature, ) -> CaliptraResult<Mldsa87Result> { self.verify_internal(pub_key, SigData::Msg(msg), signature) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn verify_external_mu( &mut self, pub_key: &Mldsa87PubKey, mu: &Mldsa87Mu, signature: &Mldsa87Signature, ) -> CaliptraResult<Mldsa87Result> { self.verify_internal(pub_key, SigData::Mu(mu), signature) } #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn verify_var( &mut self, pub_key: &Mldsa87PubKey, msg: &[u8], signature: &Mldsa87Signature, ) -> CaliptraResult<Mldsa87Result> { let truncated_signature = self.verify_common_setup(pub_key, signature)?; let mldsa = self.mldsa87.regs_mut(); // Program the command register for signature verification with streaming mldsa .mldsa_ctrl() .write(|w| w.ctrl(VERIFY).stream_msg(true)); // Program the message to the hardware Mldsa87::program_var_msg(mldsa, msg)?; // Copy the result let verify_res = LEArray4x16::read_from_reg(mldsa.mldsa_verify_res()); // Clear the hardware when done mldsa.mldsa_ctrl().write(|w| w.zeroize(true)); let result = if verify_res.0 == truncated_signature { cfi_assert_eq_16_words(&verify_res.0, &truncated_signature); Mldsa87Result::Success } else { Mldsa87Result::SigVerifyFailed }; Ok(result) } /// Sign the PCR digest with PCR signing private key (seed) in keyvault slot 8 (KV8). /// KV8 contains the Alias FMC MLDSA keypair seed. /// /// # Arguments /// /// * `trng` - TRNG driver instance /// /// # Returns /// /// * `Mldsa87Signature` - Generated signature #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn pcr_sign_flow(&mut self, trng: &mut Trng) -> CaliptraResult<Mldsa87Signature> { let mldsa = self.mldsa87.regs_mut(); // Wait for hardware ready Mldsa87::wait(mldsa, || mldsa.mldsa_status().read().ready())?; // Generate an IV. let iv = Self::generate_iv(trng)?; iv.write_to_reg(mldsa.entropy()); mldsa .mldsa_ctrl() .write(|w| w.pcr_sign(true).ctrl(KEYGEN_SIGN)); // Wait for command to complete Mldsa87::wait(mldsa, || mldsa.mldsa_status().read().valid())?; // Copy signature let signature = Mldsa87Signature::read_from_reg(mldsa.mldsa_signature()); // Clear the hardware. mldsa.mldsa_ctrl().write(|w| w.zeroize(true)); Ok(signature) } /// Zeroize the hardware registers. /// /// This is useful to call from a fatal-error-handling routine. /// /// # Safety /// /// The caller must be certain that the results of any pending cryptographic /// operations will not be used after this function is called. /// /// This function is safe to call from a trap handler. pub unsafe fn zeroize() { Self::zeroize_no_wait(); let mut mldsa_reg = AbrReg::new(); let mldsa = mldsa_reg.regs_mut(); // Wait for hardware ready. Ignore errors let _ = Mldsa87::wait(mldsa, || mldsa.mldsa_status().read().ready()); } /// Zeroize the hardware registers without waiting for readiness. /// /// This is useful to call from a fatal-error-handling routine. /// /// # Safety /// /// The caller must be certain that the results of any pending cryptographic /// operations will not be used after this function is called. /// /// This function is safe to call from a trap handler. pub unsafe fn zeroize_no_wait() { let mut mldsa_reg = AbrReg::new(); let mldsa = mldsa_reg.regs_mut(); mldsa.mldsa_ctrl().write(|f| f.zeroize(true)); } } /// Mldsa87 key access error trait trait MlDsaKeyAccessErr { /// Convert to read seed operation error fn into_read_seed_err(self) -> CaliptraError; } impl MlDsaKeyAccessErr for KvAccessErr { /// Convert to read seed operation error fn into_read_seed_err(self) -> CaliptraError { match self { KvAccessErr::KeyRead => CaliptraError::DRIVER_MLDSA87_READ_SEED_KV_READ, KvAccessErr::KeyWrite => CaliptraError::DRIVER_MLDSA87_READ_SEED_KV_WRITE, KvAccessErr::Generic => CaliptraError::DRIVER_MLDSA87_READ_SEED_KV_UNKNOWN, } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/sha2_512_384acc.rs
drivers/src/sha2_512_384acc.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha2_512_384acc.rs Abstract: File contains API for SHA2 512/384 accelerator operations --*/ use crate::wait; use crate::CaliptraResult; use crate::Mailbox; use crate::{Array4x12, Array4x16}; use caliptra_error::CaliptraError; use caliptra_registers::sha512_acc::enums::ShaCmdE; use caliptra_registers::sha512_acc::regs::ExecuteWriteVal; use caliptra_registers::sha512_acc::Sha512AccCsr; pub type Sha384Digest<'a> = &'a mut Array4x12; pub type Sha512Digest<'a> = &'a mut Array4x16; #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ShaAccLockState { AssumedLocked = 0xAAAA_AAA5, NotAcquired = 0x5555_555A, } /// Endianness mode for SHA accelerator streaming operations. /// Note: data is reversed inside the hardware SHA engine state, /// so this may have the opposite effect of what is expected and /// always be tested against hardware. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StreamEndianness { /// Maintain native byte order of the data Native, /// Reorder byte endianness Reorder, } impl StreamEndianness { /// Returns true if endian_toggle should be set to true in the hardware (Native mode = maintain = true) fn should_toggle(self) -> bool { match self { StreamEndianness::Native => true, StreamEndianness::Reorder => false, } } } pub struct Sha2_512_384Acc { sha512_acc: Sha512AccCsr, } impl Sha2_512_384Acc { pub fn new(sha512_acc: Sha512AccCsr) -> Self { Self { sha512_acc } } /// Acquire the SHA384 Accelerator lock. /// /// # Arguments /// /// * assumed_lock_state - The assumed lock state of the SHA384 Accelerator. /// Note: Callers should pass assumed_lock_state=ShaAccLockState::NotAcquired /// unless they are the first caller to the peripheral after a cold/warm boot. /// /// # Returns /// /// * On success, either an object representing the SHA384 accelerator operation or /// 'None' if unable to acquire the SHA384 Accelerator lock. /// On failure, an error code. /// pub fn try_start_operation( &mut self, assumed_lock_state: ShaAccLockState, ) -> CaliptraResult<Option<Sha2_512_384AccOp>> { let sha_acc = self.sha512_acc.regs(); #[cfg(feature = "fips-test-hooks")] if unsafe { crate::FipsTestHook::hook_cmd_is_set( crate::FipsTestHook::SHA2_512_384_ACC_START_OP_FAILURE, ) } { return Ok(None); } match assumed_lock_state { ShaAccLockState::NotAcquired => { if sha_acc.lock().read().lock() { // Either SOC has the lock (correct state), // or the uC has the lock but the caller doesn't realize it (bug). Ok(None) } else { // The uC acquired the lock just now. Ok(Some(Sha2_512_384AccOp { sha512_acc: &mut self.sha512_acc, })) } } ShaAccLockState::AssumedLocked => { if sha_acc.lock().read().lock() { // SHA Acc is locked and the caller is assuming that the uC has it. Ok(Some(Sha2_512_384AccOp { sha512_acc: &mut self.sha512_acc, })) } else { // Caller expected uC to already have the lock, but uC actually didn't (bug) Err(CaliptraError::DRIVER_SHA2_512_384ACC_UNEXPECTED_ACQUIRED_LOCK_STATE) } } } } /// Zeroize the hardware registers. /// /// This is useful to call from a fatal-error-handling routine. /// /// # Safety /// /// The caller must be certain that the results of any pending cryptographic /// operations will not be used after this function is called. /// /// This function is safe to call from a trap handler. pub unsafe fn zeroize() { let mut sha512_acc = Sha512AccCsr::new(); sha512_acc.regs_mut().control().write(|w| w.zeroize(true)); } /// Lock the accelerator. /// /// This is useful to call from a fatal-error-handling routine. /// /// # Safety /// /// The caller must be certain that the results of any pending cryptographic /// operations will not be used after this function is called. /// /// This function is safe to call from a trap handler. pub unsafe fn lock() { let sha512_acc = Sha512AccCsr::new(); while sha512_acc.regs().lock().read().lock() && sha512_acc.regs().status().read().soc_has_lock() {} } /// Try to acquire the accelerator lock. /// /// This is useful to call from a fatal-error-handling routine. /// /// # Safety /// /// The caller must be certain that the results of any pending cryptographic /// operations will not be used after this function is called. /// /// This function is safe to call from a trap handler. pub unsafe fn try_lock() { let sha512_acc = Sha512AccCsr::new(); sha512_acc.regs().lock().read().lock(); } } pub struct Sha2_512_384AccOp<'a> { sha512_acc: &'a mut Sha512AccCsr, } impl Drop for Sha2_512_384AccOp<'_> { /// Release the SHA384 Accelerator lock. /// /// # Arguments /// /// * None fn drop(&mut self) { let sha_acc = self.sha512_acc.regs_mut(); sha_acc.lock().write(|w| w.lock(true)); } } impl Sha2_512_384AccOp<'_> { /// Write data dword by dword to the datain register fn write_data_to_datain(&mut self, data: &[u8]) { for chunk in data.chunks(4) { let mut dword = [0u8; 4]; dword[..chunk.len()].copy_from_slice(chunk); self.sha512_acc .regs_mut() .datain() .write(|_| u32::from_le_bytes(dword)); } } /// Perform SHA 384 digest on a byte slice /// /// # Arguments /// /// * `data` - byte slice to hash /// * `endianness` - byte endianness mode (Native or Reorder) /// * `digest` - buffer to populate with resulting digest pub fn digest_384_slice( &mut self, data: &[u8], endianness: StreamEndianness, digest: Sha384Digest, ) -> CaliptraResult<()> { #[cfg(feature = "fips-test-hooks")] unsafe { crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::SHA384_DIGEST_FAILURE)? } let dlen = data.len() as u32; // Start streaming self.stream_start_384(dlen, endianness)?; // Write data dword by dword to datain register self.write_data_to_datain(data); // Finish streaming and get digest self.stream_finish_384(digest)?; Ok(()) } /// Perform SHA 384 digest on multiple byte slices (concatenated) /// /// # Arguments /// /// * `slices` - array of byte slices to hash (in order) /// * `endianness` - byte endianness mode (Native or Reorder) /// * `digest` - buffer to populate with resulting digest pub fn digest_384_slices( &mut self, slices: &[&[u8]], endianness: StreamEndianness, digest: Sha384Digest, ) -> CaliptraResult<()> { #[cfg(feature = "fips-test-hooks")] unsafe { crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::SHA384_DIGEST_FAILURE)? } // Calculate total length let dlen: u32 = slices.iter().map(|s| s.len() as u32).sum(); // Start streaming self.stream_start_384(dlen, endianness)?; // Write data from all slices dword by dword to datain register for data in slices { self.write_data_to_datain(data); } // Finish streaming and get digest self.stream_finish_384(digest)?; Ok(()) } /// Perform SHA 512 digest on a byte slice /// /// # Arguments /// /// * `data` - byte slice to hash /// * `endianness` - byte endianness mode (Native or Reorder) /// * `digest` - buffer to populate with resulting digest pub fn digest_512_slice( &mut self, data: &[u8], endianness: StreamEndianness, digest: Sha512Digest, ) -> CaliptraResult<()> { #[cfg(feature = "fips-test-hooks")] unsafe { crate::FipsTestHook::error_if_hook_set( crate::FipsTestHook::SHA2_512_384_ACC_DIGEST_512_FAILURE, )? } let dlen = data.len() as u32; // Start streaming self.stream_start_512(dlen, endianness)?; // Write data dword by dword to datain register self.write_data_to_datain(data); // Finish streaming and get digest self.stream_finish_512(digest)?; Ok(()) } /// Perform SHA 512 digest on multiple byte slices (concatenated) /// /// # Arguments /// /// * `slices` - array of byte slices to hash (in order) /// * `endianness` - byte endianness mode (Native or Reorder) /// * `digest` - buffer to populate with resulting digest pub fn digest_512_slices( &mut self, slices: &[&[u8]], endianness: StreamEndianness, digest: Sha512Digest, ) -> CaliptraResult<()> { #[cfg(feature = "fips-test-hooks")] unsafe { crate::FipsTestHook::error_if_hook_set( crate::FipsTestHook::SHA2_512_384_ACC_DIGEST_512_FAILURE, )? } // Calculate total length let dlen: u32 = slices.iter().map(|s| s.len() as u32).sum(); // Start streaming self.stream_start_512(dlen, endianness)?; // Write data from all slices dword by dword to datain register for data in slices { self.write_data_to_datain(data); } // Finish streaming and get digest self.stream_finish_512(digest)?; Ok(()) } /// Prepare the SHA accelerator for streaming. /// /// # Arguments /// /// * `dlen` - length of data that will be hashed /// * `endianness` - byte endianness mode (Native or Reorder) pub fn stream_start_384( &mut self, dlen: u32, endianness: StreamEndianness, ) -> CaliptraResult<()> { let sha_acc = self.sha512_acc.regs_mut(); // Set the SHA accelerator mode and set the option to maintain the DWORD // endianess of the data in the mailbox provided to the SHA384 engine. sha_acc.mode().write(|w| { w.mode(|_| ShaCmdE::ShaStream384) .endian_toggle(endianness.should_toggle()) }); // Set the data length to hash. sha_acc.dlen().write(|_| dlen); Ok(()) } /// Execute and finish SHA accelerator streaming operation. pub fn stream_finish_384(&mut self, digest: Sha384Digest) -> CaliptraResult<()> { let sha_acc = self.sha512_acc.regs_mut(); // signal that we are done streaming sha_acc.execute().write(|w| w.execute(true)); self.stream_wait_for_done_384(digest) } /// Wait for the SHA accelerator streaming operation to finish. pub fn stream_wait_for_done_384(&mut self, digest: Sha384Digest) -> CaliptraResult<()> { let sha_acc = self.sha512_acc.regs_mut(); // Wait for the digest operation to finish wait::until(|| sha_acc.status().read().valid()); *digest = Array4x12::read_from_reg(sha_acc.digest().truncate::<12>()); // Zeroize the hardware registers. self.sha512_acc .regs_mut() .control() .write(|w| w.zeroize(true)); Ok(()) } /// Prepare the SHA accelerator for streaming. /// /// # Arguments /// /// * `dlen` - length of data that will be hashed /// * `endianness` - byte endianness mode (Native or Reorder) pub fn stream_start_512( &mut self, dlen: u32, endianness: StreamEndianness, ) -> CaliptraResult<()> { let sha_acc = self.sha512_acc.regs_mut(); // Set the SHA accelerator mode and set the option to maintain the DWORD // endianess of the data in the mailbox provided to the SHA512 engine. sha_acc.mode().write(|w| { w.mode(|_| ShaCmdE::ShaStream512) .endian_toggle(endianness.should_toggle()) }); // Set the data length to hash. sha_acc.dlen().write(|_| dlen); Ok(()) } /// Execute and finish SHA accelerator streaming operation. pub fn stream_finish_512(&mut self, digest: Sha512Digest) -> CaliptraResult<()> { let sha_acc = self.sha512_acc.regs_mut(); // signal that we are done streaming sha_acc.execute().write(|w| w.execute(true)); self.stream_wait_for_done_512(digest) } /// Wait for the SHA accelerator streaming operation to finish. pub fn stream_wait_for_done_512(&mut self, digest: Sha512Digest) -> CaliptraResult<()> { let sha_acc = self.sha512_acc.regs_mut(); // Wait for the digest operation to finish wait::until(|| sha_acc.status().read().valid()); *digest = Array4x16::read_from_reg(sha_acc.digest()); // Zeroize the hardware registers. self.sha512_acc .regs_mut() .control() .write(|w| w.zeroize(true)); Ok(()) } /// Perform SHA digest with a configurable mode /// /// # Arguments /// /// * `dlen` - length of data to read from the mailbox /// * `start_address` - start offset for the data in the mailbox /// * `endianness` - byte endianness mode (Native or Reorder) /// * `cmd` - SHA mode/command to use from ShaCmdE fn digest_generic( &mut self, dlen: u32, start_address: u32, endianness: StreamEndianness, cmd: ShaCmdE, ) -> CaliptraResult<()> { let sha_acc = self.sha512_acc.regs_mut(); let mbox_len = Mailbox::get_mbox_size(); if start_address >= mbox_len || (start_address + dlen) > mbox_len { return Err(CaliptraError::DRIVER_SHA2_512_384ACC_INDEX_OUT_OF_BOUNDS); } // Set the data length to read from the mailbox. sha_acc.dlen().write(|_| dlen); // Set the start offset of the data in the mailbox. sha_acc.start_address().write(|_| start_address); // Set the SHA accelerator mode and set the option to maintain the DWORD // endianess of the data in the mailbox provided to the SHA384 engine. sha_acc .mode() .write(|w| w.mode(|_| cmd).endian_toggle(endianness.should_toggle())); // Trigger the SHA operation. sha_acc.execute().write(|_| ExecuteWriteVal::from(1)); // Wait for the digest operation to finish wait::until(|| sha_acc.status().read().valid()); Ok(()) } /// Perform SHA 384 digest /// /// # Arguments /// /// * `dlen` - length of data to read from the mailbox /// * `start_address` - start offset for the data in the mailbox /// * `endianness` - byte endianness mode (Native or Reorder) /// * `digest` - buffer to populate with resulting digest pub fn digest_384( &mut self, dlen: u32, start_address: u32, endianness: StreamEndianness, digest: Sha384Digest, ) -> CaliptraResult<()> { #[cfg(feature = "fips-test-hooks")] unsafe { crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::SHA384_DIGEST_FAILURE)? } self.digest_generic(dlen, start_address, endianness, ShaCmdE::ShaMbox384)?; // Copy digest to buffer let sha_acc = self.sha512_acc.regs(); *digest = Array4x12::read_from_reg(sha_acc.digest().truncate::<12>()); // Zeroize the hardware registers. self.sha512_acc .regs_mut() .control() .write(|w| w.zeroize(true)); Ok(()) } /// Perform SHA 512 digest /// /// # Arguments /// /// * `dlen` - length of data to read from the mailbox /// * `start_address` - start offset for the data in the mailbox /// * `endianness` - byte endianness mode (Native or Reorder) /// * `digest` - buffer to populate with resulting digest pub fn digest_512( &mut self, dlen: u32, start_address: u32, endianness: StreamEndianness, digest: Sha512Digest, ) -> CaliptraResult<()> { #[cfg(feature = "fips-test-hooks")] unsafe { crate::FipsTestHook::error_if_hook_set( crate::FipsTestHook::SHA2_512_384_ACC_DIGEST_512_FAILURE, )? } self.digest_generic(dlen, start_address, endianness, ShaCmdE::ShaMbox512)?; // Copy digest to buffer let sha_acc = self.sha512_acc.regs(); *digest = Array4x16::read_from_reg(sha_acc.digest()); #[cfg(feature = "fips-test-hooks")] { *digest = unsafe { crate::FipsTestHook::corrupt_data_if_hook_set( crate::FipsTestHook::SHA2_512_384_ACC_CORRUPT_DIGEST_512, digest, ) }; } // Zeroize the hardware registers. self.sha512_acc .regs_mut() .control() .write(|w| w.zeroize(true)); Ok(()) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/okref.rs
drivers/src/okref.rs
// Licensed under the Apache-2.0 license /// This function makes it easier to efficiently deal with Result types with /// large `Ok` variants. /// /// Consider this code: /// /// ``` /// use caliptra_drivers::okref; /// /// fn some_function() -> Result<[u32; 64], u32> { /// Ok([0u32; 64]) /// } /// fn compute(val: &[u32; 64]) {} /// /// fn main() -> std::result::Result<(), u32> { /// let value = some_function()?; /// compute(&value); /// Ok(()) /// } /// ``` /// /// In the above code, the compiler will usually generate a memcpy inside main /// that copies the large array out of the Result into a separate stack /// location. `okref` can be used to work with the array directly out of the /// original stack location, eliminating the memcpy: /// /// ``` /// use caliptra_drivers::okref; /// /// fn some_function() -> Result<[u32; 64], u32> { /// Ok([0u32; 64]) /// } /// fn compute(val: &[u32; 64]) {} /// /// fn main() -> std::result::Result<(), u32> { /// let value = some_function(); /// let value = okref(&value)?; /// compute(value); /// Ok(()) /// } /// ``` /// pub fn okref<T, E: Copy>(r: &Result<T, E>) -> Result<&T, E> { match r { Ok(r) => Ok(r), Err(e) => Err(*e), } } pub fn okmutref<T, E: Copy>(r: &mut Result<T, E>) -> Result<&mut T, E> { match r { Ok(r) => Ok(r), Err(e) => Err(*e), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_okref_ok() { let result: Result<[u32; 16], char> = Ok([11u32; 16]); let okref_result: Result<&[u32; 16], char> = okref(&result); assert_eq!(okref_result.unwrap(), result.as_ref().unwrap()); } #[test] fn test_okref_err() { let result: Result<[u32; 16], char> = Err('x'); let okref_result: Result<&[u32; 16], char> = okref(&result); assert_eq!('x', okref_result.unwrap_err()); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/fips_test_hooks.rs
drivers/src/fips_test_hooks.rs
// Licensed under the Apache-2.0 license use caliptra_error::CaliptraResult; use caliptra_registers::soc_ifc::SocIfcReg; pub struct FipsTestHook; impl FipsTestHook { pub const RSVD: u8 = 0x0; // Set by Caliptra pub const COMPLETE: u8 = 0x1; // Set by external test pub const CONTINUE: u8 = 0x10; pub const HALT_SELF_TESTS: u8 = 0x21; pub const SHA1_CORRUPT_DIGEST: u8 = 0x22; pub const SHA256_CORRUPT_DIGEST: u8 = 0x23; pub const SHA384_CORRUPT_DIGEST: u8 = 0x24; pub const SHA2_512_384_ACC_CORRUPT_DIGEST_512: u8 = 0x25; pub const ECC384_CORRUPT_SIGNATURE: u8 = 0x26; pub const HMAC384_CORRUPT_TAG: u8 = 0x27; pub const LMS_CORRUPT_INPUT: u8 = 0x28; pub const ECC384_PAIRWISE_CONSISTENCY_ERROR: u8 = 0x29; pub const HALT_FW_LOAD: u8 = 0x2A; pub const HALT_SHUTDOWN_RT: u8 = 0x2B; pub const ECC384_CORRUPT_KEY_PAIR: u8 = 0x2C; pub const SHA1_DIGEST_FAILURE: u8 = 0x40; pub const SHA256_DIGEST_FAILURE: u8 = 0x41; pub const SHA384_DIGEST_FAILURE: u8 = 0x42; pub const SHA2_512_384_ACC_DIGEST_512_FAILURE: u8 = 0x43; pub const SHA2_512_384_ACC_START_OP_FAILURE: u8 = 0x44; pub const ECC384_SIGNATURE_GENERATE_FAILURE: u8 = 0x45; pub const ECC384_VERIFY_FAILURE: u8 = 0x46; pub const HMAC384_FAILURE: u8 = 0x47; pub const LMS_VERIFY_FAILURE: u8 = 0x48; pub const ECC384_KEY_PAIR_GENERATE_FAILURE: u8 = 0x49; pub const MLDSA_VERIFY_FAILURE: u8 = 0x4A; pub const ECC384_ECDH_FAILURE: u8 = 0x4B; // FW Load Errors pub const FW_LOAD_VENDOR_PUB_KEY_DIGEST_FAILURE: u8 = 0x50; pub const FW_LOAD_OWNER_PUB_KEY_DIGEST_FAILURE: u8 = 0x51; pub const FW_LOAD_HEADER_DIGEST_FAILURE: u8 = 0x52; pub const FW_LOAD_VENDOR_ECC_VERIFY_FAILURE: u8 = 0x53; pub const FW_LOAD_OWNER_ECC_VERIFY_FAILURE: u8 = 0x54; pub const FW_LOAD_OWNER_TOC_DIGEST_FAILURE: u8 = 0x55; pub const FW_LOAD_FMC_DIGEST_FAILURE: u8 = 0x56; pub const FW_LOAD_RUNTIME_DIGEST_FAILURE: u8 = 0x57; pub const FW_LOAD_VENDOR_LMS_VERIFY_FAILURE: u8 = 0x58; pub const FW_LOAD_OWNER_LMS_VERIFY_FAILURE: u8 = 0x59; pub const FW_LOAD_VENDOR_MLDSA_VERIFY_FAILURE: u8 = 0x5A; pub const FW_LOAD_OWNER_MLDSA_VERIFY_FAILURE: u8 = 0x5B; /// # Safety /// /// This function interrupts normal flow and halts operation of the ROM or FW /// (Only when the hook_cmd matches the value from get_fips_test_hook_code) pub unsafe fn halt_if_hook_set(hook_cmd: u8) { if get_fips_test_hook_code() == hook_cmd { // Report that we've reached this point set_fips_test_hook_code(FipsTestHook::COMPLETE); // Wait for the CONTINUE command while get_fips_test_hook_code() != FipsTestHook::CONTINUE {} // Write COMPLETE set_fips_test_hook_code(FipsTestHook::COMPLETE); } } /// # Safety /// /// This function returns an intentionally corrupted version of the data provided /// (Only when the hook_cmd matches the value from get_fips_test_hook_code) pub unsafe fn corrupt_data_if_hook_set<T: core::marker::Copy>(hook_cmd: u8, data: &T) -> T { if get_fips_test_hook_code() == hook_cmd { let mut mut_data = *data; let ptr_t = &mut mut_data as *mut T; let mut_u8 = ptr_t as *mut u8; let byte_0 = unsafe { &mut *mut_u8 }; // Corrupt (invert) the first byte *byte_0 = !*byte_0; return mut_data; } *data } /// # Safety /// /// This function enables a different test hook to allow for basic state machines /// (Only when the hook_cmd matches the value from get_fips_test_hook_code) pub unsafe fn update_hook_cmd_if_hook_set(hook_cmd: u8, new_hook_cmd: u8) { if get_fips_test_hook_code() == hook_cmd { set_fips_test_hook_code(new_hook_cmd); } } /// # Safety /// /// This function calls other unsafe functions to check the test hook code pub unsafe fn hook_cmd_is_set(hook_cmd: u8) -> bool { get_fips_test_hook_code() == hook_cmd } /// # Safety /// /// This function checks the current hook code and returns the /// FIPS_HOOKS_INJECTED_ERROR if enabled pub unsafe fn error_if_hook_set(hook_cmd: u8) -> CaliptraResult<()> { if get_fips_test_hook_code() == hook_cmd { Err(caliptra_error::CaliptraError::FIPS_HOOKS_INJECTED_ERROR) } else { Ok(()) } } } /// # Safety /// /// Temporarily creates a new instance of SocIfcReg instead of following the /// normal convention of sharing one instance unsafe fn get_fips_test_hook_code() -> u8 { // Bits 23:16 indicate the 8 bit code for the enabled FIPS test hook const CODE_MASK: u32 = 0x00FF0000; const CODE_OFFSET: u32 = 16; let soc_ifc = unsafe { SocIfcReg::new() }; let soc_ifc_regs = soc_ifc.regs(); let val = soc_ifc_regs.cptra_dbg_manuf_service_reg().read(); ((val & CODE_MASK) >> CODE_OFFSET) as u8 } /// # Safety /// /// Temporarily creates a new instance of SocIfcReg instead of following the /// normal convention of sharing one instance unsafe fn set_fips_test_hook_code(code: u8) { // Bits 23:16 indicate the 8 bit code for the enabled FIPS test hook const CODE_MASK: u32 = 0x00FF0000; const CODE_OFFSET: u32 = 16; let mut soc_ifc = unsafe { SocIfcReg::new() }; let soc_ifc_regs = soc_ifc.regs_mut(); let val = (soc_ifc_regs.cptra_dbg_manuf_service_reg().read() & !(CODE_MASK)) | ((code as u32) << CODE_OFFSET); soc_ifc_regs.cptra_dbg_manuf_service_reg().write(|_| val); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/lms.rs
drivers/src/lms.rs
/*++ Licensed under the Apache-2.0 license. File Name: lms_hss.rs Abstract: File contains API for LMS signature validation Implementation follows the LMS specification and pseudocode from RFC 8554 https://www.rfc-editor.org/rfc/rfc8554 --*/ use core::mem::MaybeUninit; use crate::{sha256::Sha256Alg, Array4x8, CaliptraResult, Sha256, Sha256DigestOp}; use caliptra_error::CaliptraError; use caliptra_lms_types::{ LmotsAlgorithmType, LmsAlgorithmType, LmsIdentifier, LmsPublicKey, LmsSignature, }; use zerocopy::{IntoBytes, LittleEndian, U32}; use zeroize::Zeroize; pub const D_PBLC: u16 = 0x8080; pub const D_MESG: u16 = 0x8181; pub const D_LEAF: u16 = 0x8282; pub const D_INTR: u16 = 0x8383; #[derive(Default, Debug)] pub struct Lms { kat_complete: bool, } pub type Sha256Digest = HashValue<8>; pub type Sha192Digest = HashValue<6>; #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LmsResult { Success = 0xCCCCCCCC, SigVerifyFailed = 0x33333333, } #[repr(transparent)] #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub struct HashValue<const N: usize>(pub [u32; N]); impl<const N: usize> Default for HashValue<N> { fn default() -> Self { let data = [0u32; N]; HashValue(data) } } impl<const N: usize> HashValue<N> { pub fn new(data: [u32; N]) -> Self { HashValue(data) } } impl<const N: usize> From<[U32<LittleEndian>; N]> for HashValue<N> { fn from(data: [U32<LittleEndian>; N]) -> Self { HashValue(swap_bytes(data)) } } impl<const N: usize> From<&[u32; N]> for HashValue<N> { fn from(data: &[u32; N]) -> Self { HashValue(*data) } } impl From<[u32; 8]> for HashValue<6> { fn from(data: [u32; 8]) -> Self { let mut result = [0u32; 6]; result[..6].copy_from_slice(&data[..6]); HashValue(result) } } impl From<[u8; 24]> for HashValue<6> { fn from(data: [u8; 24]) -> Self { let mut result = [0u32; 6]; for i in 0..6 { result[i] = u32::from_be_bytes([ data[i * 4], data[i * 4 + 1], data[i * 4 + 2], data[i * 4 + 3], ]); } HashValue(result) } } impl From<[u8; 32]> for HashValue<8> { fn from(data: [u8; 32]) -> Self { let mut result = [0u32; 8]; for i in 0..8 { result[i] = u32::from_be_bytes([ data[i * 4], data[i * 4 + 1], data[i * 4 + 2], data[i * 4 + 3], ]); } HashValue(result) } } impl<const N: usize> From<Array4x8> for HashValue<N> { fn from(data: Array4x8) -> Self { let mut result = [0u32; N]; result[..N].copy_from_slice(&data.0[..N]); HashValue(result) } } impl<const N: usize> AsRef<[u32]> for HashValue<N> { fn as_ref(&self) -> &[u32] { &self.0 } } fn swap_bytes<const N: usize>(b: [U32<LittleEndian>; N]) -> [u32; N] { let mut result = MaybeUninit::<[u32; N]>::uninit(); let dest = result.as_mut_ptr() as *mut u32; #[allow(clippy::needless_range_loop)] for i in 0..N { unsafe { dest.add(i).write(b[i].get().swap_bytes()) } } unsafe { result.assume_init() } } #[derive(Debug)] pub struct LmotsParameter { pub algorithm_name: LmotsAlgorithmType, pub n: u8, pub w: u8, pub p: u16, pub ls: u8, } const LMOTS_P: [LmotsParameter; 9] = [ LmotsParameter { algorithm_name: LmotsAlgorithmType::LmotsReserved, n: 0, w: 0, p: 0, ls: 0, }, LmotsParameter { algorithm_name: LmotsAlgorithmType::LmotsSha256N32W1, n: 32, w: 1, p: 265, ls: 7, }, LmotsParameter { algorithm_name: LmotsAlgorithmType::LmotsSha256N32W2, n: 32, w: 2, p: 133, ls: 6, }, LmotsParameter { algorithm_name: LmotsAlgorithmType::LmotsSha256N32W4, n: 32, w: 4, p: 67, ls: 4, }, LmotsParameter { algorithm_name: LmotsAlgorithmType::LmotsSha256N32W8, n: 32, w: 8, p: 34, ls: 0, }, LmotsParameter { algorithm_name: LmotsAlgorithmType::LmotsSha256N24W1, n: 24, w: 1, p: 200, ls: 8, }, LmotsParameter { algorithm_name: LmotsAlgorithmType::LmotsSha256N24W2, n: 24, w: 2, p: 101, ls: 6, }, LmotsParameter { algorithm_name: LmotsAlgorithmType::LmotsSha256N24W4, n: 24, w: 4, p: 51, ls: 4, }, LmotsParameter { algorithm_name: LmotsAlgorithmType::LmotsSha256N24W8, n: 24, w: 8, p: 26, ls: 0, }, ]; pub fn get_lmots_parameters( algo_type: LmotsAlgorithmType, ) -> CaliptraResult<&'static LmotsParameter> { for i in &LMOTS_P { if i.algorithm_name == algo_type { return Ok(i); } } Err(CaliptraError::DRIVER_LMS_INVALID_LMOTS_ALGO_TYPE) } pub fn get_lms_parameters(algo_type: LmsAlgorithmType) -> CaliptraResult<(u8, u8)> { match algo_type { LmsAlgorithmType::LmsSha256N32H5 => Ok((32, 5)), LmsAlgorithmType::LmsSha256N32H10 => Ok((32, 10)), LmsAlgorithmType::LmsSha256N32H15 => Ok((32, 15)), LmsAlgorithmType::LmsSha256N32H20 => Ok((32, 20)), LmsAlgorithmType::LmsSha256N32H25 => Ok((32, 25)), LmsAlgorithmType::LmsSha256N24H5 => Ok((24, 5)), LmsAlgorithmType::LmsSha256N24H10 => Ok((24, 10)), LmsAlgorithmType::LmsSha256N24H15 => Ok((24, 15)), LmsAlgorithmType::LmsSha256N24H20 => Ok((24, 20)), LmsAlgorithmType::LmsSha256N24H25 => Ok((24, 25)), _ => Err(CaliptraError::DRIVER_LMS_INVALID_LMS_ALGO_TYPE), } } impl Lms { pub const WNTZ_MODE_SHA256: u8 = 32; pub const ITER_COUNTER_OFFSET: usize = 22; pub const WNT_PREFIX_SIZE: usize = 55; // See https://datatracker.ietf.org/doc/html/rfc8554 // tmp = H(I || u32str(q) || u16str(i) || u8str(j) || tmp) pub const TMP_OFFSET: usize = 23; // follows pseudo code at https://www.rfc-editor.org/rfc/rfc8554#section-3.1.3 pub fn coefficient(&self, s: &[u8], i: usize, w: usize) -> CaliptraResult<u8> { let valid_w = matches!(w, 1 | 2 | 4 | 8); if !valid_w { return Err(CaliptraError::DRIVER_LMS_INVALID_WINTERNITS_PARAM); } let bitmask: u16 = (1 << (w)) - 1; let index = i * w / 8; if index >= s.len() { return Err(CaliptraError::DRIVER_LMS_INVALID_INDEX); } let b = s[index]; // extra logic to avoid the divide by 0 // which a good compiler would notice only happens when w is 0 and that portion of the // expression could be skipped let mut shift = 8; if w != 0 { shift = 8 - (w * (i % (8 / w)) + w); } // Rust errors if we try to shift off all of the bits off from a value // some implementations 0 fill, others do some other filling. // we make this be 0 let mut rs = 0; if shift < 8 { rs = b >> shift; } let small_bitmask = bitmask as u8; Ok(small_bitmask & rs) } fn checksum(&self, algo_type: LmotsAlgorithmType, input_string: &[u8]) -> CaliptraResult<u16> { let params = get_lmots_parameters(algo_type)?; let mut sum = 0u16; let valid_w = matches!(params.w, 1 | 2 | 4 | 8); if !valid_w { return Err(CaliptraError::DRIVER_LMS_INVALID_WINTERNITS_PARAM); } let upper_bound = params.n as u16 * (8 / params.w as u16); let bitmask = (1 << params.w) - 1; for i in 0..upper_bound as usize { sum += bitmask - (self.coefficient(input_string, i, params.w as usize)? as u16); } let shifted = sum << params.ls; Ok(shifted) } pub fn hash_message<const N: usize>( &self, sha256_driver: &mut impl Sha256Alg, message: &[u8], lms_identifier: &LmsIdentifier, q: &[u8; 4], nonce: &[U32<LittleEndian>; N], ) -> CaliptraResult<HashValue<N>> { let mut digest = Array4x8::default(); let mut hasher = sha256_driver.digest_init()?; hasher.update(lms_identifier)?; hasher.update(q)?; hasher.update(&D_MESG.to_be_bytes())?; hasher.update(nonce.as_bytes())?; hasher.update(message)?; hasher.finalize(&mut digest)?; Ok(HashValue::from(digest)) } // This operation is accelerated in hardware by RTL1.1 and later. fn hash_chain<const N: usize>( &self, sha256_driver: &mut impl Sha256Alg, wnt_prefix: &mut [u8; Self::WNT_PREFIX_SIZE], coeff: u8, params: &LmotsParameter, tmp: &mut HashValue<N>, ) -> CaliptraResult<HashValue<N>> { let iteration_count = ((1u16 << params.w) - 1) as u8; if coeff < iteration_count { let mut digest = Array4x8::default(); let mut hasher = sha256_driver.digest_init()?; wnt_prefix[Self::ITER_COUNTER_OFFSET] = coeff; let mut i = Self::TMP_OFFSET; for val in tmp.0.iter().take(N) { wnt_prefix[i..i + 4].clone_from_slice(&val.to_be_bytes()); i += 4; } //set n_mode: 1 for n=32, and 0 for n=24 let mut n_mode: bool = false; if params.n == Self::WNTZ_MODE_SHA256 { n_mode = true; } hasher.update_wntz(&wnt_prefix[0..Self::TMP_OFFSET + N * 4], params.w, n_mode)?; hasher.finalize_wntz(&mut digest, params.w, n_mode)?; *tmp = HashValue::<N>::from(digest); } Ok(*tmp) } pub fn candidate_ots_signature<const N: usize, const P: usize>( &self, sha256_driver: &mut impl Sha256Alg, lms_identifier: &LmsIdentifier, algo_type: LmotsAlgorithmType, q: &[u8; 4], y: &[[U32<LittleEndian>; N]; P], message_digest: &HashValue<N>, ) -> CaliptraResult<HashValue<N>> { let params: &LmotsParameter = get_lmots_parameters(algo_type)?; if params.p as usize != P { return Err(CaliptraError::DRIVER_LMS_INVALID_PVALUE); } if params.n > 32 { return Err(CaliptraError::DRIVER_LMS_INVALID_HASH_WIDTH); } if params.n as usize != N * 4 { return Err(CaliptraError::DRIVER_LMS_INVALID_HASH_WIDTH); } let mut z = [HashValue::<N>::default(); P]; let mut message_hash_with_checksum = [0u8; 34]; // 2 extra bytes for the checksum. needs to be N+2 let mut i = 0; for val in message_digest.0.iter() { message_hash_with_checksum[i..i + 4].clone_from_slice(&val.to_be_bytes()); i += 4; } let checksum_q = self.checksum(algo_type, &message_hash_with_checksum)?; let be_checksum = checksum_q.to_be_bytes(); let checksum_offset = N * 4; message_hash_with_checksum[checksum_offset] = be_checksum[0]; message_hash_with_checksum[checksum_offset + 1] = be_checksum[1]; // In order to reduce the number of copies allocate a single block of memory // and update only the portions that update between iterations let mut hash_block = [0u8; 55]; hash_block[0..16].clone_from_slice(lms_identifier); hash_block[16..20].clone_from_slice(q); for (i, val) in z.iter_mut().enumerate() { let a = self.coefficient(&message_hash_with_checksum, i, params.w as usize)?; let mut tmp = HashValue::<N>::from(y[i]); hash_block[20..22].clone_from_slice(&(i as u16).to_be_bytes()); *val = self.hash_chain(sha256_driver, &mut hash_block, a, params, &mut tmp)?; } let mut digest = Array4x8::default(); let mut hasher = sha256_driver.digest_init()?; hasher.update(lms_identifier)?; hasher.update(q)?; hasher.update(&D_PBLC.to_be_bytes())?; for t in z { for val in t.0.iter() { hasher.update(&val.to_be_bytes())?; } } hasher.finalize(&mut digest)?; let result = HashValue::<N>::from(digest); digest.0.zeroize(); Ok(result) } /// Note: Use this function only if glitch protection is not needed. /// If glitch protection is needed, use `verify_lms_signature_cfi` instead. pub fn verify_lms_signature( &self, sha256_driver: &mut Sha256, input_string: &[u8], lms_public_key: &LmsPublicKey<6>, lms_sig: &LmsSignature<6, 51, 15>, ) -> CaliptraResult<LmsResult> { #[cfg(feature = "fips-test-hooks")] let input_string = unsafe { crate::FipsTestHook::corrupt_data_if_hook_set( crate::FipsTestHook::LMS_CORRUPT_INPUT, &input_string, ) }; let mut candidate_key = self.verify_lms_signature_cfi(sha256_driver, input_string, lms_public_key, lms_sig)?; let result = if candidate_key != HashValue::from(lms_public_key.digest) { Ok(LmsResult::SigVerifyFailed) } else { Ok(LmsResult::Success) }; candidate_key.0.zeroize(); result } /// Note: Use this function only if glitch protection is not needed. /// If glitch protection is needed, use `verify_lms_signature_cfi_generic` instead. pub fn verify_lms_signature_generic<const N: usize, const P: usize, const H: usize>( &self, sha256_driver: &mut impl Sha256Alg, input_string: &[u8], lms_public_key: &LmsPublicKey<N>, lms_sig: &LmsSignature<N, P, H>, ) -> CaliptraResult<LmsResult> { let mut candidate_key = self.verify_lms_signature_cfi_generic( sha256_driver, input_string, lms_public_key, lms_sig, )?; let result = if candidate_key != HashValue::from(lms_public_key.digest) { Ok(LmsResult::SigVerifyFailed) } else { Ok(LmsResult::Success) }; candidate_key.0.zeroize(); result } // When callers from separate crates call a function like // verify_lms_signature_cfi_generic(), Rustc 1.70 // may build multiple versions (depending on optimizer heuristics), even when all the // generic parameters are identical. This is bad, as it can bloat the binary and the // second copy violates the FIPS requirements that the same machine code be used for the // KAT as the actual implementation. To defend against it, we provide this non-generic // function that production firmware should call instead. #[inline(never)] pub fn verify_lms_signature_cfi( &self, sha256_driver: &mut Sha256, input_string: &[u8], lms_public_key: &LmsPublicKey<6>, lms_sig: &LmsSignature<6, 51, 15>, ) -> CaliptraResult<HashValue<6>> { self.verify_lms_signature_cfi_generic(sha256_driver, input_string, lms_public_key, lms_sig) } #[inline(always)] pub fn verify_lms_signature_cfi_generic<const N: usize, const P: usize, const H: usize>( &self, sha256_driver: &mut impl Sha256Alg, input_string: &[u8], lms_public_key: &LmsPublicKey<N>, lms_sig: &LmsSignature<N, P, H>, ) -> CaliptraResult<HashValue<N>> { #[cfg(feature = "fips-test-hooks")] unsafe { crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::LMS_VERIFY_FAILURE)? } if lms_sig.ots.ots_type != lms_public_key.otstype { return Err(CaliptraError::DRIVER_LMS_SIGNATURE_LMOTS_DOESNT_MATCH_PUBKEY_LMOTS); } let q_str = <[u8; 4]>::from(lms_sig.q); let (_, tree_height) = get_lms_parameters(lms_sig.tree_type)?; // Make sure the height of the tree matches the value of H this was compiled with if tree_height as usize != H { return Err(CaliptraError::DRIVER_LMS_INVALID_TREE_HEIGHT); } // Make sure the value of Q is valid for the tree height if lms_sig.q.get() >= 1 << H { return Err(CaliptraError::DRIVER_LMS_INVALID_Q_VALUE); } let mut node_num: u32 = (1 << tree_height) + lms_sig.q.get(); if node_num >= 2 << tree_height { return Err(CaliptraError::DRIVER_LMS_INVALID_Q_VALUE); } let message_digest = self.hash_message( sha256_driver, input_string, &lms_public_key.id, &q_str, &lms_sig.ots.nonce, )?; let candidate_key = self.candidate_ots_signature( sha256_driver, &lms_public_key.id, lms_sig.ots.ots_type, &q_str, &lms_sig.ots.y, &message_digest, )?; match tree_height { 5 => (), 10 => (), 15 => (), 20 => (), 25 => (), _ => return Err(CaliptraError::DRIVER_LMS_INVALID_TREE_HEIGHT), } let mut digest = Array4x8::default(); let mut hasher = sha256_driver.digest_init()?; hasher.update(&lms_public_key.id)?; hasher.update(&node_num.to_be_bytes())?; hasher.update(&D_LEAF.to_be_bytes())?; for val in candidate_key.0.iter() { hasher.update(&val.to_be_bytes())?; } hasher.finalize(&mut digest)?; let mut temp = HashValue::<N>::from(digest); let mut i = 0; while node_num > 1 { let mut digest = Array4x8::default(); let mut hasher = sha256_driver.digest_init()?; hasher.update(&lms_public_key.id)?; hasher.update(&(node_num / 2).to_be_bytes())?; hasher.update(&D_INTR.to_be_bytes())?; if node_num % 2 == 1 { hasher.update( lms_sig .tree_path .get(i) .ok_or(CaliptraError::DRIVER_LMS_PATH_OUT_OF_BOUNDS)? .as_bytes(), )?; } for val in temp.0.iter() { hasher.update(&val.to_be_bytes())?; } if node_num % 2 == 0 { hasher.update( lms_sig .tree_path .get(i) .ok_or(CaliptraError::DRIVER_LMS_PATH_OUT_OF_BOUNDS)? .as_bytes(), )?; } hasher.finalize(&mut digest)?; temp = HashValue::<N>::from(digest); node_num /= 2; i += 1; digest.0.zeroize(); } digest.0.zeroize(); Ok(temp) } // Return the kat_complete state pub fn kat_is_complete(&self) -> bool { self.kat_complete } // Update the kat_complete state to true (complete) pub fn mark_kat_complete(&mut self) { self.kat_complete = true; } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/hmac_kdf.rs
drivers/src/hmac_kdf.rs
/*++ Licensed under the Apache-2.0 license. File Name: hmac_kdf.rs Abstract: A KDF implementation that is compliant with SP 800-108 Section 4.1 (KDF in Counter Mode). --*/ use crate::{Hmac, HmacKey, HmacMode, HmacTag, Trng}; #[cfg(not(feature = "no-cfi"))] use caliptra_cfi_derive::cfi_mod_fn; use caliptra_error::CaliptraResult; /// Calculate HMAC-KDF /// /// If the output is a KV slot, the slot is marked as a valid HMAC key / /// ECC or MLDSA keygen seed. /// /// # Arguments /// /// * `hmac` - HMAC context /// * `key` - HMAC key /// * `label` - Label for the KDF. If `context` is omitted, this is considered /// the fixed input data. /// * `context` - Context for KDF. If present, a NULL byte is included between /// the label and context. /// * `trng` - TRNG driver instance /// * `output` - Location to store the output /// * `mode` - HMAC Mode #[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)] pub fn hmac_kdf( hmac: &mut Hmac, key: HmacKey, label: &[u8], context: Option<&[u8]>, trng: &mut Trng, output: HmacTag, mode: HmacMode, ) -> CaliptraResult<()> { #[cfg(feature = "fips-test-hooks")] unsafe { crate::FipsTestHook::error_if_hook_set(crate::FipsTestHook::HMAC384_FAILURE)? } let mut hmac_op = hmac.hmac_init(key, trng, output, mode)?; hmac_op.update(&1_u32.to_be_bytes())?; hmac_op.update(label)?; if let Some(context) = context { hmac_op.update(&[0x00])?; hmac_op.update(context)?; } hmac_op.finalize() }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/preconditioned_key.rs
drivers/src/preconditioned_key.rs
/*++ Licensed under the Apache-2.0 license. File Name: preconditioned_key.rs Abstract: A FIPS-approved method for combining keys together leveraging an HMAC-based key-extraction process. --*/ use crate::{ hmac_kdf, Aes, AesKey, AesOperation, Hmac, HmacData, HmacKey, HmacMode, HmacTag, KeyReadArgs, KeyUsage, KeyWriteArgs, LEArray4x8, Trng, }; use caliptra_error::{CaliptraError, CaliptraResult}; pub fn preconditioned_key_extract( input_key: HmacKey, output_key: HmacTag, kdf_label: &[u8], salt: HmacKey, trng: &mut Trng, hmac: &mut Hmac, aes: &mut Aes, ) -> CaliptraResult<()> { let HmacTag::Key(output_kv) = output_key else { Err(CaliptraError::RUNTIME_DRIVER_PRECONDITIONED_KEY_INVALID_INPUT)? }; let aes_key; let aes_key = match salt { // NOTE: The HMAC Key may be byte reversed from what the AES engine expects. // You must be careful to always specify the HMAC Key in the same order. HmacKey::Array4x16(arr) => { let mut aes_arr: [u32; 8] = [0; 8]; // Truncate HMAC Key from 64 bytes to 32 bytes. aes_arr.clone_from_slice(&arr.0[..8]); // Swap bytes before converting to LEArray4x8. for byte in aes_arr.iter_mut() { *byte = byte.swap_bytes(); } aes_key = LEArray4x8::from(&aes_arr); AesKey::Array(&aes_key) } HmacKey::Key(kv) => AesKey::KV(kv), _ => Err(CaliptraError::RUNTIME_DRIVER_PRECONDITIONED_KEY_INVALID_INPUT)?, }; let mut checksum = [0; 16]; aes.aes_256_ecb(aes_key, AesOperation::Encrypt, &[0; 16], &mut checksum)?; hmac_kdf( hmac, input_key, kdf_label, Some(&checksum), trng, HmacTag::Key(KeyWriteArgs::new( output_kv.id, KeyUsage::default().set_hmac_data_en(), )), HmacMode::Hmac512, )?; hmac.hmac( salt, HmacData::Key(KeyReadArgs::new(output_kv.id)), trng, HmacTag::Key(output_kv), HmacMode::Hmac512, )?; Ok(()) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/pcr_log.rs
drivers/src/pcr_log.rs
/*++ Licensed under the Apache-2.0 license. File Name: pcr.rs Abstract: PCR-related types. --*/ use crate::PcrId; use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; use zeroize::Zeroize; pub const PCR_ID_FMC_CURRENT: PcrId = PcrId::PcrId0; pub const PCR_ID_FMC_JOURNEY: PcrId = PcrId::PcrId1; pub const PCR_ID_STASH_MEASUREMENT: PcrId = PcrId::PcrId31; // PcrLogEntryId is used to identify the PCR entry and // the size of the data in PcrLogEntry::pcr_data. #[repr(u16)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PcrLogEntryId { Invalid = 0, DeviceStatus = 1, // data size = 9 bytes VendorPubKeyInfoHash = 2, // data size = 48 bytes OwnerPubKeyHash = 3, // data size = 48 bytes FmcTci = 4, // data size = 48 bytes StashMeasurement = 5, // data size = 48 bytes RtTci = 6, // data size = 48 bytes FwImageManifest = 7, // data size = 48 bytes } impl From<u16> for PcrLogEntryId { /// Converts to this type from the input type. fn from(id: u16) -> PcrLogEntryId { match id { 1 => PcrLogEntryId::DeviceStatus, 2 => PcrLogEntryId::VendorPubKeyInfoHash, 3 => PcrLogEntryId::OwnerPubKeyHash, 4 => PcrLogEntryId::FmcTci, 5 => PcrLogEntryId::StashMeasurement, 6 => PcrLogEntryId::RtTci, 7 => PcrLogEntryId::FwImageManifest, _ => PcrLogEntryId::Invalid, } } } /// PCR log entry #[repr(C)] #[derive(IntoBytes, Clone, Copy, Debug, Default, FromBytes, Immutable, KnownLayout, Zeroize)] pub struct PcrLogEntry { /// Entry identifier pub id: u16, pub reserved0: [u8; 2], /// Bitmask indicating the PCRs to which the data is being extended to. pub pcr_ids: u32, // PCR data pub pcr_data: [u32; 12], } impl PcrLogEntry { pub fn measured_data(&self) -> &[u8] { let data_len = match PcrLogEntryId::from(self.id) { PcrLogEntryId::Invalid => 0, PcrLogEntryId::DeviceStatus => 9, PcrLogEntryId::VendorPubKeyInfoHash => 48, PcrLogEntryId::OwnerPubKeyHash => 48, PcrLogEntryId::FmcTci => 48, PcrLogEntryId::StashMeasurement => 48, PcrLogEntryId::RtTci => 48, PcrLogEntryId::FwImageManifest => 48, }; &self.pcr_data.as_bytes()[..data_len] } } /// Measurement log entry #[repr(C)] #[derive(IntoBytes, Clone, Copy, Debug, Default, FromBytes, Immutable, KnownLayout, Zeroize)] pub struct MeasurementLogEntry { pub pcr_entry: PcrLogEntry, pub metadata: [u8; 4], pub context: [u32; 12], pub svn: u32, pub reserved0: [u8; 4], } pub const RT_FW_CURRENT_PCR: PcrId = PcrId::PcrId2; pub const RT_FW_JOURNEY_PCR: PcrId = PcrId::PcrId3;
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/kv_access.rs
drivers/src/kv_access.rs
/*++ Licensed under the Apache-2.0 license. File Name: kv_access.rs Abstract: File contains helper methods used by peripherals to access keys in key vault. --*/ use crate::array::Array4xN; use crate::{wait, CaliptraResult, KeyId, KeyUsage, PcrId}; use caliptra_registers::enums::KvErrorE; use caliptra_registers::regs::{KvReadCtrlRegWriteVal, KvStatusRegReadVal, KvWriteCtrlRegWriteVal}; use ureg::{Mmio, MmioMut}; /// Key read operation arguments #[derive(Debug, Clone, Copy)] pub struct KeyReadArgs { /// Key Id pub id: KeyId, } impl KeyReadArgs { /// Create an instance of `KeyReadArgs` /// /// # Arguments /// /// * `id` - Key Id pub fn new(id: KeyId) -> Self { Self { id } } } /// Key write operation arguments #[derive(Debug, Clone, Copy)] pub struct KeyWriteArgs { /// Key Id pub id: KeyId, /// Key usage flags pub usage: KeyUsage, } impl KeyWriteArgs { /// Create an instance of `KeyWriteArgs` /// /// # Arguments /// /// * `id` - Key Id /// * `usage` - Key usage flags pub fn new(id: KeyId, usage: KeyUsage) -> Self { Self { id, usage } } } /// Key Access Error pub(crate) enum KvAccessErr { /// Key read error KeyRead, /// Key write error KeyWrite, /// Generic error Generic, } /// Key Access pub(crate) enum KvAccess {} impl KvAccess { /// Begin copying the array to key vault /// /// This function disables the write enable bit in control register /// to prevent the copy of the key to key vault /// /// # Arguments /// /// * `status_reg` - Status register /// * `ctrl_reg` - Control register pub(crate) fn begin_copy_to_arr< StatusReg: ureg::ReadableReg<ReadVal = KvStatusRegReadVal>, CtrlReg: ureg::ResettableReg + ureg::WritableReg<WriteVal = KvWriteCtrlRegWriteVal>, TMmio: MmioMut, >( status_reg: ureg::RegRef<StatusReg, TMmio>, ctrl_reg: ureg::RegRef<CtrlReg, TMmio>, ) -> CaliptraResult<()> { wait::until(|| status_reg.read().ready()); ctrl_reg.write(|w| w.write_en(false)); Ok(()) } /// Finish copying the key to array /// /// # Arguments /// /// * `reg` - Source register to copy from /// * `arr` - Destination array to copy the contents of register to pub(crate) fn end_copy_to_arr< const ARR_WORD_LEN: usize, const ARR_BYTE_LEN: usize, TReg: ureg::ReadableReg<ReadVal = u32, Raw = u32>, TMmio: Mmio + Copy, >( reg: ureg::Array<ARR_WORD_LEN, ureg::RegRef<TReg, TMmio>>, arr: &mut Array4xN<ARR_WORD_LEN, ARR_BYTE_LEN>, ) -> CaliptraResult<()> { *arr = Array4xN::<ARR_WORD_LEN, ARR_BYTE_LEN>::read_from_reg(reg); Ok(()) } /// Begin copying the contents of the operation to key slot in key vault /// /// # Arguments /// /// * `status_reg` - Status register /// * `ctrl_reg` - Control register /// * `key` - Key slot in key vault pub(crate) fn begin_copy_to_kv< StatusReg: ureg::ReadableReg<ReadVal = KvStatusRegReadVal>, CtrlReg: ureg::ResettableReg + ureg::WritableReg<WriteVal = KvWriteCtrlRegWriteVal>, TMmio: MmioMut, >( status_reg: ureg::RegRef<StatusReg, TMmio>, ctrl_reg: ureg::RegRef<CtrlReg, TMmio>, key: KeyWriteArgs, ) -> CaliptraResult<()> { wait::until(|| status_reg.read().ready()); ctrl_reg.write(|w| { w.write_en(true) .write_entry(key.id.into()) .hmac_key_dest_valid(key.usage.hmac_key()) .hmac_block_dest_valid(key.usage.hmac_data()) .mldsa_seed_dest_valid(key.usage.mldsa_seed()) .ecc_pkey_dest_valid(key.usage.ecc_private_key()) .ecc_seed_dest_valid(key.usage.ecc_key_gen_seed()) .aes_key_dest_valid(key.usage.aes_key()) .mlkem_seed_dest_valid(key.usage.mlkem_seed()) .mlkem_msg_dest_valid(key.usage.mlkem_msg()) .dma_data_dest_valid(key.usage.dma_data()) }); Ok(()) } /// Finish copying the key to key vault /// /// # Arguments /// /// * `status_reg` - Status register /// * `key` - Key slot in key vault pub(crate) fn end_copy_to_kv< SReg: ureg::ReadableReg<ReadVal = KvStatusRegReadVal>, TMmio: Mmio, >( status_reg: ureg::RegRef<SReg, TMmio>, _key: KeyWriteArgs, ) -> Result<(), KvAccessErr> { wait::until(|| status_reg.read().valid()); match status_reg.read().error() { KvErrorE::Success => Ok(()), KvErrorE::KvReadFail => Err(KvAccessErr::KeyRead), KvErrorE::KvWriteFail => Err(KvAccessErr::KeyWrite), _ => Err(KvAccessErr::Generic), } } /// Copy the contents of the array to register /// /// # Arguments /// /// * `arr` - Source array to copy from /// * `reg` - Destination register to copy to pub(crate) fn copy_from_arr< const ARR_WORD_LEN: usize, const ARR_BYTE_LEN: usize, TReg: ureg::ResettableReg + ureg::WritableReg<WriteVal = u32, Raw = u32>, TMmio: MmioMut + Copy, >( arr: &Array4xN<ARR_WORD_LEN, ARR_BYTE_LEN>, reg: ureg::Array<ARR_WORD_LEN, ureg::RegRef<TReg, TMmio>>, ) -> CaliptraResult<()> { arr.write_to_reg(reg); Ok(()) } /// Copy the contents from key slot in key vault to crypto block /// /// # Arguments /// /// * `key` - Key slot to copy the data from /// * `status_reg` - Status register /// * `ctrl_reg` - Control register pub(crate) fn copy_from_kv< StatusReg: ureg::ReadableReg<ReadVal = KvStatusRegReadVal>, CtrlReg: ureg::ResettableReg + ureg::WritableReg<WriteVal = KvReadCtrlRegWriteVal>, TMmio: MmioMut, >( key: KeyReadArgs, status_reg: ureg::RegRef<StatusReg, TMmio>, ctrl_reg: ureg::RegRef<CtrlReg, TMmio>, ) -> Result<(), KvAccessErr> { crate::wait::until(|| status_reg.read().ready()); ctrl_reg.write(|w| { w.read_en(true) .read_entry(key.id.into()) .pcr_hash_extend(false) }); crate::wait::until(|| status_reg.read().valid()); match status_reg.read().error() { KvErrorE::Success => Ok(()), KvErrorE::KvReadFail => Err(KvAccessErr::KeyRead), KvErrorE::KvWriteFail => Err(KvAccessErr::KeyWrite), _ => Err(KvAccessErr::Generic), } } /// Hash extends the contents from pcr slot in pcr vault /// /// # Arguments /// /// * `pcr_id` - Pcr slot to hash extend /// * `status_reg` - Status register /// * `ctrl_reg` - Control register pub(crate) fn extend_from_pv< StatusReg: ureg::ReadableReg<ReadVal = KvStatusRegReadVal>, CtrlReg: ureg::ResettableReg + ureg::WritableReg<WriteVal = KvReadCtrlRegWriteVal>, TMmio: MmioMut, >( pcr_id: PcrId, status_reg: ureg::RegRef<StatusReg, TMmio>, ctrl_reg: ureg::RegRef<CtrlReg, TMmio>, ) -> Result<(), KvAccessErr> { crate::wait::until(|| status_reg.read().ready()); ctrl_reg.write(|w| { w.read_en(true) .read_entry(pcr_id.into()) .pcr_hash_extend(true) }); crate::wait::until(|| status_reg.read().valid()); match status_reg.read().error() { KvErrorE::Success => Ok(()), KvErrorE::KvReadFail => Err(KvAccessErr::KeyRead), KvErrorE::KvWriteFail => Err(KvAccessErr::KeyWrite), _ => Err(KvAccessErr::Generic), } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/cmac_kdf.rs
drivers/src/cmac_kdf.rs
/*++ Licensed under the Apache-2.0 license. File Name: cmac_kdf.rs Abstract: A KDF implementation that is compliant with SP 800-108 Section 4.1 (KDF in Counter Mode) using CMAC as the underlying PRF. --*/ use crate::{Aes, AesKey, LEArray4x16, AES_BLOCK_SIZE_WORDS}; use arrayvec::ArrayVec; #[cfg(not(feature = "no-cfi"))] use caliptra_cfi_derive::cfi_mod_fn; use caliptra_error::{CaliptraError, CaliptraResult}; const MAX_KMAC_INPUT_SIZE: usize = 4096; /// Calculate CMAC-KDF /// /// # Arguments /// /// * `aes` - AES driver /// * `key`- AES key /// * `label` - Label for the KDF. If `context` is omitted, this is considered /// the fixed input data. /// * `context` - Context for KDF. If present, a NULL byte is included between /// the label and context. /// * `rounds` - must be 1, 2, 3, or 4. This determines the output size. /// /// # Returns /// The output key as an array of bytes. The number of valid bytes is /// `rounds` * 16.` #[cfg_attr(not(feature = "no-cfi"), cfi_mod_fn)] pub fn cmac_kdf( aes: &mut Aes, key: AesKey, label: &[u8], context: Option<&[u8]>, rounds: u32, ) -> CaliptraResult<LEArray4x16> { let input_len = label.len() + context.map(|c| c.len() + 1).unwrap_or(0) + 4; if input_len > MAX_KMAC_INPUT_SIZE { return Err(CaliptraError::DRIVER_CMAC_KDF_INVALID_SLICE); } if !(1..=4).contains(&rounds) { return Err(CaliptraError::DRIVER_CMAC_KDF_INVALID_ROUNDS); } let mut input = ArrayVec::<u8, MAX_KMAC_INPUT_SIZE>::new(); let mut output = LEArray4x16::default(); for round in 0..rounds { // reset the input for each round input.clear(); // Each round is a 4-byte counter input .try_extend_from_slice(&(round + 1).to_be_bytes()) .map_err(|_| CaliptraError::DRIVER_CMAC_KDF_INVALID_SLICE)?; input .try_extend_from_slice(label) .map_err(|_| CaliptraError::DRIVER_CMAC_KDF_INVALID_SLICE)?; if let Some(context) = context { // separator input .try_push(0x00) .map_err(|_| CaliptraError::DRIVER_CMAC_KDF_INVALID_SLICE)?; input .try_extend_from_slice(context) .map_err(|_| CaliptraError::DRIVER_CMAC_KDF_INVALID_SLICE)?; } let result = aes.cmac(key, &input)?; output.0 [round as usize * AES_BLOCK_SIZE_WORDS..(round as usize + 1) * AES_BLOCK_SIZE_WORDS] .copy_from_slice(&result.0); } Ok(output) }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/trng.rs
drivers/src/trng.rs
// Licensed under the Apache-2.0 license use core::array; use caliptra_error::{CaliptraError, CaliptraResult}; use caliptra_registers::{ csrng::CsrngReg, entropy_src::EntropySrcReg, soc_ifc::SocIfcReg, soc_ifc_trng::SocIfcTrngReg, }; use crate::{trng_ext::TrngExt, Array4x12, Array4x16, Csrng, MfgFlags}; #[repr(u32)] pub enum Trng { Internal(Csrng) = 0xb714a2b1, External(TrngExt) = 0xf3702ce3, MfgMode() = 0x0c702ce3, // Teach the compiler that "other" values are possible to encourage it not // to get too crazy with optimizations. Match statements should handle `_` // by jumping to the CFI handler. Invalid0 = 0x0060f20f, Invalid1 = 0x0a8dfe7a, } impl Trng { pub fn new( csrng: CsrngReg, entropy_src: EntropySrcReg, soc_ifc_trng: SocIfcTrngReg, soc_ifc: &SocIfcReg, ) -> CaliptraResult<Self> { // If device is unlocked for debug and RNG support is unavailable, return a fake RNG. let flags: MfgFlags = (soc_ifc.regs().cptra_dbg_manuf_service_reg().read() & 0xffff).into(); if !soc_ifc.regs().cptra_security_state().read().debug_locked() & flags.contains(MfgFlags::RNG_SUPPORT_UNAVAILABLE) { Ok(Self::MfgMode()) } else if soc_ifc.regs().cptra_hw_config().read().i_trng_en() { Ok(Self::Internal(Csrng::new(csrng, entropy_src, soc_ifc)?)) } else { Ok(Self::External(TrngExt::new(soc_ifc_trng))) } } /// # Safety /// /// If the hardware itrng is enabled, the caller MUST ensure that the /// peripheral is in a state where new entropy is accessible via the /// generate command. pub unsafe fn assume_initialized( csrng: CsrngReg, entropy_src: EntropySrcReg, soc_ifc_trng: SocIfcTrngReg, soc_ifc: &SocIfcReg, ) -> Self { if soc_ifc.regs().cptra_hw_config().read().i_trng_en() { Self::Internal(Csrng::assume_initialized(csrng, entropy_src)) } else { Self::External(TrngExt::new(soc_ifc_trng)) } } /// Stir in additional data to the internal state of the TRNG, if supported. /// This is analagous to the NIST update command in SP800-90A. pub fn stir(&mut self, additional_data: &[u32]) -> CaliptraResult<()> { extern "C" { fn cfi_panic_handler(code: u32) -> !; } match self { Self::Internal(csrng) => csrng.update(additional_data), Self::External(_) => Err(CaliptraError::DRIVER_TRNG_UPDATE_NOT_SUPPORTED)?, Self::MfgMode() => Ok(()), _ => unsafe { cfi_panic_handler(CaliptraError::ROM_CFI_PANIC_UNEXPECTED_MATCH_BRANCH.into()) }, } } pub fn generate(&mut self) -> CaliptraResult<Array4x12> { extern "C" { fn cfi_panic_handler(code: u32) -> !; } match self { Self::Internal(csrng) => Ok(csrng.generate12()?.into()), Self::External(trng_ext) => trng_ext.generate(), Self::MfgMode() => { unsafe { let soc_ifc = SocIfcReg::new(); if soc_ifc.regs().cptra_security_state().read().debug_locked() { cfi_panic_handler( CaliptraError::ROM_CFI_PANIC_FAKE_TRNG_USED_WITH_DEBUG_LOCK.into(), ) } } Ok(array::from_fn(|_| 0xdeadbeef_u32).into()) } _ => unsafe { cfi_panic_handler(CaliptraError::ROM_CFI_PANIC_UNEXPECTED_MATCH_BRANCH.into()) }, } } pub fn generate4(&mut self) -> CaliptraResult<(u32, u32, u32, u32)> { extern "C" { fn cfi_panic_handler(code: u32) -> !; } match self { Self::Internal(csrng) => { let a = csrng.generate12()?; Ok((a[0], a[1], a[2], a[3])) } Self::External(trng_ext) => trng_ext.generate4(), Self::MfgMode() => { unsafe { let soc_ifc = SocIfcReg::new(); if soc_ifc.regs().cptra_security_state().read().debug_locked() { cfi_panic_handler( CaliptraError::ROM_CFI_PANIC_FAKE_TRNG_USED_WITH_DEBUG_LOCK.into(), ) } } Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef)) } _ => unsafe { cfi_panic_handler(CaliptraError::ROM_CFI_PANIC_UNEXPECTED_MATCH_BRANCH.into()) }, } } pub fn generate16(&mut self) -> CaliptraResult<Array4x16> { let a = self.generate()?; let b = self.generate()?; let mut result = [0u32; 16]; result[..12].copy_from_slice(&a.0); result[12..].copy_from_slice(&b.0[..4]); Ok(Array4x16::from(result)) } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/ml_kem.rs
drivers/src/ml_kem.rs
/*++ Licensed under the Apache-2.0 license. File Name: ml_kem.rs Abstract: File contains API for ML-KEM-1024 Cryptography operations --*/ #![allow(dead_code)] use crate::{ array::{LEArray4x392, LEArray4x792, LEArray4x8}, kv_access::{KvAccess, KvAccessErr}, wait, CaliptraError, CaliptraResult, KeyReadArgs, KeyWriteArgs, }; #[cfg(not(feature = "no-cfi"))] use caliptra_cfi_derive::cfi_impl_fn; use caliptra_cfi_derive::Launder; use caliptra_registers::abr::{AbrReg, RegisterBlock}; #[must_use] #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Launder)] pub enum MlKemResult { Success = 0xAAAAAAAA, OperationFailed = 0x55555555, } /// ML-KEM-1024 Encapsulation Key (1568 bytes) pub type MlKem1024EncapsKey = LEArray4x392; /// ML-KEM-1024 Decapsulation Key (3168 bytes) pub type MlKem1024DecapsKey = LEArray4x792; /// ML-KEM-1024 Ciphertext (1568 bytes) pub type MlKem1024Ciphertext = LEArray4x392; /// ML-KEM-1024 Shared Key (32 bytes) pub type MlKem1024SharedKey = LEArray4x8; /// ML-KEM-1024 Message (32 bytes) pub type MlKem1024Message = LEArray4x8; /// ML-KEM-1024 Seed (32 bytes) pub type MlKem1024Seed = LEArray4x8; // Control register constants. const KEYGEN: u32 = 1; const ENCAPS: u32 = 2; const DECAPS: u32 = 3; const KEYGEN_DECAPS: u32 = 4; /// ML-KEM-1024 Seeds #[derive(Debug, Copy, Clone)] pub enum MlKem1024Seeds<'a> { /// Array pair (seed_d, seed_z) Arrays(&'a MlKem1024Seed, &'a MlKem1024Seed), /// Key Vault Key (contains both seeds) Key(KeyReadArgs), } impl<'a> From<(&'a MlKem1024Seed, &'a MlKem1024Seed)> for MlKem1024Seeds<'a> { /// Converts to this type from the input type. fn from(value: (&'a MlKem1024Seed, &'a MlKem1024Seed)) -> Self { Self::Arrays(value.0, value.1) } } impl From<KeyReadArgs> for MlKem1024Seeds<'_> { /// Converts to this type from the input type. fn from(value: KeyReadArgs) -> Self { Self::Key(value) } } /// ML-KEM-1024 Message source #[derive(Debug, Copy, Clone)] pub enum MlKem1024MessageSource<'a> { /// Array Array(&'a MlKem1024Message), /// Key Vault Key Key(KeyReadArgs), } impl<'a> From<&'a MlKem1024Message> for MlKem1024MessageSource<'a> { /// Converts to this type from the input type. fn from(value: &'a MlKem1024Message) -> Self { Self::Array(value) } } impl From<KeyReadArgs> for MlKem1024MessageSource<'_> { /// Converts to this type from the input type. fn from(value: KeyReadArgs) -> Self { Self::Key(value) } } /// ML-KEM-1024 Shared Key output #[derive(Debug)] pub enum MlKem1024SharedKeyOut<'a> { /// Array Array(&'a mut MlKem1024SharedKey), /// Key Vault Key Key(KeyWriteArgs), } impl<'a> From<&'a mut MlKem1024SharedKey> for MlKem1024SharedKeyOut<'a> { /// Converts to this type from the input type. fn from(value: &'a mut MlKem1024SharedKey) -> Self { Self::Array(value) } } impl From<KeyWriteArgs> for MlKem1024SharedKeyOut<'_> { /// Converts to this type from the input type. fn from(value: KeyWriteArgs) -> Self { Self::Key(value) } } /// ML-KEM-1024 API pub struct MlKem1024 { mlkem: AbrReg, } impl MlKem1024 { pub fn new(mlkem: AbrReg) -> Self { Self { mlkem } } // Wait on the provided condition OR the error condition defined in this function // In the event of the error condition being set, clear the error bits and return an error fn wait<F>(regs: RegisterBlock<ureg::RealMmioMut>, condition: F) -> CaliptraResult<()> where F: Fn() -> bool, { let err_condition = || { (u32::from(regs.intr_block_rf().error_global_intr_r().read()) != 0) || (u32::from(regs.intr_block_rf().error_internal_intr_r().read()) != 0) || regs.mlkem_status().read().error() }; // Wait for either the given condition or the error condition wait::until(|| (condition() || err_condition())); if err_condition() { // Clear the errors // error_global_intr_r is RO regs.intr_block_rf() .error_internal_intr_r() .write(|_| u32::from(regs.intr_block_rf().error_internal_intr_r().read()).into()); return Err(CaliptraError::DRIVER_MLKEM_HW_ERROR); } Ok(()) } /// Generate ML-KEM-1024 Key Pair /// /// # Arguments /// /// * `seeds` - Either arrays of seed_d and seed_z or a key vault key containing both seeds. /// /// # Returns /// /// * `(MlKem1024EncapsKey, MlKem1024DecapsKey)` - Generated ML-KEM-1024 key pair pub fn key_pair( &mut self, seeds: MlKem1024Seeds, ) -> CaliptraResult<(MlKem1024EncapsKey, MlKem1024DecapsKey)> { self.zeroize_internal()?; let mlkem = self.mlkem.regs_mut(); // Copy seeds to the hardware match seeds { MlKem1024Seeds::Arrays(seed_d, seed_z) => { seed_d.write_to_reg(mlkem.mlkem_seed_d()); seed_z.write_to_reg(mlkem.mlkem_seed_z()); } MlKem1024Seeds::Key(key) => KvAccess::copy_from_kv( key, mlkem.kv_mlkem_seed_rd_status(), mlkem.kv_mlkem_seed_rd_ctrl(), ) .map_err(|err| err.into_read_seed_err())?, } // Program the command register for key generation mlkem.mlkem_ctrl().write(|w| w.ctrl(KEYGEN)); // Wait for hardware ready MlKem1024::wait(mlkem, || mlkem.mlkem_status().read().valid())?; // Copy keys let encaps_key = MlKem1024EncapsKey::read_from_reg(mlkem.mlkem_encaps_key()); let decaps_key = MlKem1024DecapsKey::read_from_reg(mlkem.mlkem_decaps_key()); // Clear the hardware when done mlkem.mlkem_ctrl().write(|w| w.zeroize(true)); Ok((encaps_key, decaps_key)) } /// Encapsulate a shared secret /// /// # Arguments /// /// * `encaps_key` - Encapsulation key. /// * `message` - Message source (array or key vault). /// * `shared_key_out` - Shared key output destination. /// /// # Returns /// /// * `MlKem1024Ciphertext` - Generated ciphertext #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn encapsulate( &mut self, encaps_key: MlKem1024EncapsKey, message: MlKem1024MessageSource, shared_key_out: MlKem1024SharedKeyOut, ) -> CaliptraResult<MlKem1024Ciphertext> { self.zeroize_internal()?; let mlkem = self.mlkem.regs_mut(); // Copy encapsulation key encaps_key.write_to_reg(mlkem.mlkem_encaps_key()); // Copy message match message { MlKem1024MessageSource::Array(msg) => msg.write_to_reg(mlkem.mlkem_msg()), MlKem1024MessageSource::Key(key) => KvAccess::copy_from_kv( key, mlkem.kv_mlkem_msg_rd_status(), mlkem.kv_mlkem_msg_rd_ctrl(), ) .map_err(|err| err.into_read_msg_err())?, } // Set up shared key output destination let mut shared_key_out = shared_key_out; match &mut shared_key_out { MlKem1024SharedKeyOut::Array(_) => { // No key vault setup needed for array output } MlKem1024SharedKeyOut::Key(key) => { mlkem.kv_mlkem_sharedkey_wr_ctrl().write(|w| { w.write_en(true) .write_entry(key.id.into()) .hmac_key_dest_valid(key.usage.hmac_key()) .hmac_block_dest_valid(key.usage.hmac_data()) .mldsa_seed_dest_valid(key.usage.mldsa_seed()) .ecc_pkey_dest_valid(key.usage.ecc_key_gen_seed()) .ecc_seed_dest_valid(key.usage.ecc_private_key()) .aes_key_dest_valid(key.usage.aes_key()) .mlkem_seed_dest_valid(key.usage.mlkem_seed()) .mlkem_msg_dest_valid(key.usage.mlkem_msg()) }); } } // Program the command register for encapsulation mlkem.mlkem_ctrl().write(|w| w.ctrl(ENCAPS)); // Wait for hardware ready MlKem1024::wait(mlkem, || mlkem.mlkem_status().read().valid())?; // Copy results match &mut shared_key_out { MlKem1024SharedKeyOut::Array(shared_key) => { **shared_key = MlKem1024SharedKey::read_from_reg(mlkem.mlkem_shared_key()); } MlKem1024SharedKeyOut::Key(_) => { // Wait for key vault write to complete MlKem1024::wait(mlkem, || { mlkem.kv_mlkem_sharedkey_wr_status().read().valid() })?; } } let ciphertext = MlKem1024Ciphertext::read_from_reg(mlkem.mlkem_ciphertext()); // Clear the hardware when done mlkem.mlkem_ctrl().write(|w| w.zeroize(true)); Ok(ciphertext) } /// Decapsulate a shared secret /// /// # Arguments /// /// * `decaps_key` - Decapsulation key. /// * `ciphertext` - Ciphertext to decapsulate. /// * `shared_key_out` - Shared key output destination. /// /// # Returns /// /// * `()` - Success #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn decapsulate( &mut self, decaps_key: MlKem1024DecapsKey, ciphertext: &MlKem1024Ciphertext, shared_key_out: MlKem1024SharedKeyOut, ) -> CaliptraResult<()> { self.zeroize_internal()?; let mlkem = self.mlkem.regs_mut(); // Copy decapsulation key and ciphertext decaps_key.write_to_reg(mlkem.mlkem_decaps_key()); ciphertext.write_to_reg(mlkem.mlkem_ciphertext()); // Set up shared key output destination let mut shared_key_out = shared_key_out; match &mut shared_key_out { MlKem1024SharedKeyOut::Array(_) => { // No key vault setup needed for array output } MlKem1024SharedKeyOut::Key(key) => { mlkem.kv_mlkem_sharedkey_wr_ctrl().write(|w| { w.write_en(true) .write_entry(key.id.into()) .hmac_key_dest_valid(key.usage.hmac_key()) .hmac_block_dest_valid(key.usage.hmac_data()) .mldsa_seed_dest_valid(key.usage.mldsa_seed()) .ecc_pkey_dest_valid(key.usage.ecc_private_key()) .ecc_seed_dest_valid(key.usage.ecc_key_gen_seed()) .aes_key_dest_valid(key.usage.aes_key()) .mlkem_seed_dest_valid(key.usage.mlkem_seed()) .mlkem_msg_dest_valid(key.usage.mlkem_msg()) }); } } // Program the command register for decapsulation mlkem.mlkem_ctrl().write(|w| w.ctrl(DECAPS)); // Wait for hardware ready MlKem1024::wait(mlkem, || mlkem.mlkem_status().read().valid())?; // Copy results match &mut shared_key_out { MlKem1024SharedKeyOut::Array(shared_key) => { **shared_key = MlKem1024SharedKey::read_from_reg(mlkem.mlkem_shared_key()); } MlKem1024SharedKeyOut::Key(_) => { // Wait for key vault write to complete MlKem1024::wait(mlkem, || { mlkem.kv_mlkem_sharedkey_wr_status().read().valid() })?; } } // Clear the hardware when done mlkem.mlkem_ctrl().write(|w| w.zeroize(true)); Ok(()) } /// Generate key pair and immediately decapsulate (saves memory for decaps key) /// /// # Arguments /// /// * `seeds` - Either arrays of seed_d and seed_z or a key vault key containing both seeds. /// * `ciphertext` - Ciphertext to decapsulate. /// * `shared_key_out` - Shared key output destination. /// /// # Returns /// /// * `()` - Success #[cfg_attr(not(feature = "no-cfi"), cfi_impl_fn)] pub fn keygen_decapsulate( &mut self, seeds: MlKem1024Seeds, ciphertext: &MlKem1024Ciphertext, shared_key_out: MlKem1024SharedKeyOut, ) -> CaliptraResult<()> { self.zeroize_internal()?; let mlkem = self.mlkem.regs_mut(); // Copy seeds to the hardware match seeds { MlKem1024Seeds::Arrays(seed_d, seed_z) => { seed_d.write_to_reg(mlkem.mlkem_seed_d()); seed_z.write_to_reg(mlkem.mlkem_seed_z()); } MlKem1024Seeds::Key(key) => KvAccess::copy_from_kv( key, mlkem.kv_mlkem_seed_rd_status(), mlkem.kv_mlkem_seed_rd_ctrl(), ) .map_err(|err| err.into_read_seed_err())?, } // Copy ciphertext ciphertext.write_to_reg(mlkem.mlkem_ciphertext()); // Set up shared key output destination let mut shared_key_out = shared_key_out; match &mut shared_key_out { MlKem1024SharedKeyOut::Array(_) => { // No key vault setup needed for array output } MlKem1024SharedKeyOut::Key(key) => { mlkem.kv_mlkem_sharedkey_wr_ctrl().write(|w| { w.write_en(true) .write_entry(key.id.into()) .hmac_key_dest_valid(key.usage.hmac_key()) .hmac_block_dest_valid(key.usage.hmac_data()) .mldsa_seed_dest_valid(key.usage.mldsa_seed()) .ecc_pkey_dest_valid(key.usage.ecc_key_gen_seed()) .ecc_seed_dest_valid(key.usage.ecc_private_key()) .aes_key_dest_valid(key.usage.aes_key()) .mlkem_seed_dest_valid(key.usage.mlkem_seed()) .mlkem_msg_dest_valid(key.usage.mlkem_msg()) }); } } // Program the command register for keygen + decapsulation mlkem.mlkem_ctrl().write(|w| w.ctrl(KEYGEN_DECAPS)); // Wait for hardware ready MlKem1024::wait(mlkem, || mlkem.mlkem_status().read().valid())?; // Copy results match &mut shared_key_out { MlKem1024SharedKeyOut::Array(shared_key) => { **shared_key = MlKem1024SharedKey::read_from_reg(mlkem.mlkem_shared_key()); } MlKem1024SharedKeyOut::Key(_) => { // Wait for key vault write to complete MlKem1024::wait(mlkem, || { mlkem.kv_mlkem_sharedkey_wr_status().read().valid() })?; } } // Clear the hardware when done mlkem.mlkem_ctrl().write(|w| w.zeroize(true)); Ok(()) } /// Zeroize the hardware registers. /// /// This is useful to call from a fatal-error-handling routine. /// /// # Safety /// /// The caller must be certain that the results of any pending cryptographic /// operations will not be used after this function is called. /// /// This function is safe to call from a trap handler. pub unsafe fn zeroize() { let mut mlkem_reg = AbrReg::new(); let mlkem = mlkem_reg.regs_mut(); mlkem.mlkem_ctrl().write(|f| f.zeroize(true)); // Wait for hardware ready. Ignore errors let _ = MlKem1024::wait(mlkem, || mlkem.mlkem_status().read().ready()); } /// Zeroize the hardware registers without waiting. /// /// This is useful to call from a fatal-error-handling routine. /// /// # Safety /// /// The caller must be certain that the results of any pending cryptographic /// operations will not be used after this function is called. /// /// This function is safe to call from a trap handler. pub unsafe fn zeroize_no_wait() { let mut mlkem_reg = AbrReg::new(); let mlkem = mlkem_reg.regs_mut(); mlkem.mlkem_ctrl().write(|f| f.zeroize(true)); } fn zeroize_internal(&mut self) -> CaliptraResult<()> { let mlkem = self.mlkem.regs_mut(); // Wait for hardware ready MlKem1024::wait(mlkem, || mlkem.mlkem_status().read().ready())?; // Clear the hardware before start mlkem.mlkem_ctrl().write(|w| w.zeroize(true)); // Wait for hardware ready MlKem1024::wait(mlkem, || mlkem.mlkem_status().read().ready())?; Ok(()) } } /// ML-KEM key access error trait trait MlKemKeyAccessErr { /// Convert to read seed operation error fn into_read_seed_err(self) -> CaliptraError; /// Convert to read message operation error fn into_read_msg_err(self) -> CaliptraError; } impl MlKemKeyAccessErr for KvAccessErr { /// Convert to read seed operation error fn into_read_seed_err(self) -> CaliptraError { match self { KvAccessErr::KeyRead => CaliptraError::DRIVER_MLKEM_READ_SEED_KV_READ, KvAccessErr::KeyWrite => CaliptraError::DRIVER_MLKEM_READ_SEED_KV_WRITE, KvAccessErr::Generic => CaliptraError::DRIVER_MLKEM_READ_SEED_KV_UNKNOWN, } } /// Convert to read message operation error fn into_read_msg_err(self) -> CaliptraError { match self { KvAccessErr::KeyRead => CaliptraError::DRIVER_MLKEM_READ_MSG_KV_READ, KvAccessErr::KeyWrite => CaliptraError::DRIVER_MLKEM_READ_MSG_KV_WRITE, KvAccessErr::Generic => CaliptraError::DRIVER_MLKEM_READ_MSG_KV_UNKNOWN, } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/csrng.rs
drivers/src/csrng.rs
/*++ Licensed under the Apache-2.0 license. Inspired by OpenTitan's driver interface functions for the entropy_src and CSRNG peripherals: https://opentitan.org/book/sw/device/lib/dif/dif_entropy_src_h.html https://opentitan.org/book/sw/device/lib/dif/dif_csrng_h.html An overview of the entropy_src and CSRNG peripherals can be found at: https://opentitan.org/book/hw/ip/entropy_src/index.html https://opentitan.org/book/hw/ip/csrng/index.html File Name: csrng.rs Abstract: Software interface to the Cryptographically Secure Random Number Generator (CSRNG) peripheral. --*/ use crate::{wait, CaliptraError, CaliptraResult}; use caliptra_registers::csrng::CsrngReg; use caliptra_registers::entropy_src::{self, regs::AlertFailCountsReadVal, EntropySrcReg}; use caliptra_registers::soc_ifc::{self, SocIfcReg}; use core::mem::MaybeUninit; // https://opentitan.org/book/hw/ip/csrng/doc/theory_of_operation.html#command-description pub const MAX_SEED_WORDS: usize = 12; const WORDS_PER_BLOCK: usize = 4; /// A unique handle to the underlying CSRNG peripheral. pub struct Csrng { csrng: CsrngReg, entropy_src: EntropySrcReg, } impl Csrng { /// Returns a handle to the CSRNG in TRNG mode. /// /// The CSRNG will gather seed material from the entropy_src peripheral. /// /// # Safety /// /// No other handles to the CSRNG should exist. /// /// # Errors /// /// Returns an error if the internal seed command fails. pub fn new( csrng: CsrngReg, entropy_src: EntropySrcReg, soc_ifc: &SocIfcReg, ) -> CaliptraResult<Self> { Self::with_seed(csrng, entropy_src, soc_ifc, Seed::EntropySrc) } /// # Safety /// /// The caller MUST ensure that the CSRNG peripheral is in a state where new /// entropy is accessible via the generate command. pub unsafe fn assume_initialized(csrng: CsrngReg, entropy_src: EntropySrcReg) -> Self { Self { csrng, entropy_src } } /// Returns a handle to the CSRNG configured to use the provided [`Seed`]. /// /// # Safety /// /// No other handles to the CSRNG should exist. /// /// # Errors /// /// Returns an error if the internal seed command fails. pub fn with_seed( csrng: CsrngReg, entropy_src: EntropySrcReg, soc_ifc: &SocIfcReg, seed: Seed, ) -> CaliptraResult<Self> { const FALSE: u32 = MultiBitBool::False as u32; const TRUE: u32 = MultiBitBool::True as u32; let mut result = Self { csrng, entropy_src }; let e = result.entropy_src.regs_mut(); // Configure and enable entropy_src if needed. if e.module_enable().read().module_enable() == FALSE { set_health_check_thresholds(e, soc_ifc.regs()); e.conf().write(|w| { w.fips_enable(TRUE) .entropy_data_reg_enable(FALSE) .threshold_scope(TRUE) .rng_bit_enable(FALSE) }); e.module_enable().write(|w| w.module_enable(TRUE)); check_for_alert_state(result.entropy_src.regs())?; } let c = result.csrng.regs_mut(); if c.ctrl().read().enable() == FALSE { c.ctrl() .write(|w| w.enable(TRUE).sw_app_enable(TRUE).read_int_state(TRUE)); } send_command(&mut result.csrng, Command::Uninstantiate)?; send_command(&mut result.csrng, Command::Instantiate(seed))?; Ok(result) } /// Return 12 randomly generated [`u32`]s. /// /// # Errors /// /// Returns an error if the internal generate command fails. /// /// # Examples /// /// ```no_run /// let mut csrng = ...; /// /// let random_words: [u32; 12] = csrng.generate()?; /// /// for word in random_words { /// // Do something with `word`. /// } /// ``` pub fn generate12(&mut self) -> CaliptraResult<[u32; 12]> { check_for_alert_state(self.entropy_src.regs())?; send_command( &mut self.csrng, Command::Generate { num_128_bit_blocks: 12 / WORDS_PER_BLOCK, }, )?; let mut result = MaybeUninit::<[u32; 12]>::uninit(); let dest = result.as_mut_ptr() as *mut u32; unsafe { wait::until(|| self.csrng.regs().genbits_vld().read().genbits_vld()); dest.add(0).write(self.csrng.regs().genbits().read()); dest.add(1).write(self.csrng.regs().genbits().read()); dest.add(2).write(self.csrng.regs().genbits().read()); dest.add(3).write(self.csrng.regs().genbits().read()); wait::until(|| self.csrng.regs().genbits_vld().read().genbits_vld()); dest.add(4).write(self.csrng.regs().genbits().read()); dest.add(5).write(self.csrng.regs().genbits().read()); dest.add(6).write(self.csrng.regs().genbits().read()); dest.add(7).write(self.csrng.regs().genbits().read()); wait::until(|| self.csrng.regs().genbits_vld().read().genbits_vld()); dest.add(8).write(self.csrng.regs().genbits().read()); dest.add(9).write(self.csrng.regs().genbits().read()); dest.add(10).write(self.csrng.regs().genbits().read()); dest.add(11).write(self.csrng.regs().genbits().read()); Ok(result.assume_init()) } } pub fn reseed(&mut self, seed: Seed) -> CaliptraResult<()> { send_command(&mut self.csrng, Command::Reseed(seed)) } pub fn update(&mut self, additional_data: &[u32]) -> CaliptraResult<()> { // if we are given too much data, do multiple updates for data in additional_data.chunks(MAX_SEED_WORDS) { send_command(&mut self.csrng, Command::Update(data))?; } Ok(()) } /// Returns the number of failing health checks. pub fn health_fail_counts(&self) -> HealthFailCounts { let e = self.entropy_src.regs(); HealthFailCounts { total: e.alert_summary_fail_counts().read().any_fail_count(), specific: e.alert_fail_counts().read(), } } pub fn uninstantiate(mut self) { let _ = send_command(&mut self.csrng, Command::Uninstantiate); } } fn check_for_alert_state( entropy_src: entropy_src::RegisterBlock<ureg::RealMmio>, ) -> CaliptraResult<()> { // https://opentitan.org/book/hw/ip/entropy_src/doc/theory_of_operation.html#main-state-machine-diagram // https://github.com/chipsalliance/caliptra-rtl/blob/main/src/entropy_src/rtl/entropy_src_main_sm_pkg.sv const ALERT_HANG: u32 = 0x1fb; const CONT_HT_RUNNING: u32 = 0x1a2; const BOOT_PHASE_DONE: u32 = 0x8e; loop { match entropy_src.main_sm_state().read().main_sm_state() { ALERT_HANG => { let alert_counts = entropy_src.alert_fail_counts().read(); if alert_counts.repcnt_fail_count() > 0 { return Err(CaliptraError::DRIVER_CSRNG_REPCNT_HEALTH_CHECK_FAILED); } if alert_counts.adaptp_lo_fail_count() > 0 || alert_counts.adaptp_hi_fail_count() > 0 { return Err(CaliptraError::DRIVER_CSRNG_ADAPTP_HEALTH_CHECK_FAILED); } return Err(CaliptraError::DRIVER_CSRNG_OTHER_HEALTH_CHECK_FAILED); } CONT_HT_RUNNING | BOOT_PHASE_DONE => { return Ok(()); } _ => (), } } } /// Variants that describe seed inputs to the CSRNG. pub enum Seed<'a> { /// Use a non-deterministic seed. EntropySrc, /// Use a deterministic seed. The number of seed words should be at least /// one and no more than twelve. Constant(&'a [u32]), } enum Command<'a> { Instantiate(Seed<'a>), Reseed(Seed<'a>), Generate { num_128_bit_blocks: usize }, Update(&'a [u32]), Uninstantiate, } #[repr(u32)] enum MultiBitBool { False = 9, True = 6, } /// Contains counts of failing health checks. /// /// This struct is returned by the [`health_fail_counts`] function on [`Csrng`]. /// /// [`health_fail_counts`]: Csrng::health_fail_counts pub struct HealthFailCounts { /// The total number of failing health check alerts. pub total: u32, /// The counts of specific failing health checks. pub specific: AlertFailCountsReadVal, } fn send_command(csrng: &mut CsrngReg, command: Command) -> CaliptraResult<()> { // https://opentitan.org/book/hw/ip/csrng/doc/theory_of_operation.html#general-command-format let acmd: u32; let clen: usize; let flag0: MultiBitBool; let glen: usize; let extra_words: &[u32]; let err: CaliptraError; match command { Command::Instantiate(ref seed) | Command::Reseed(ref seed) => { acmd = if matches!(command, Command::Instantiate(_)) { err = CaliptraError::DRIVER_CSRNG_INSTANTIATE; 1 } else { err = CaliptraError::DRIVER_CSRNG_RESEED; 2 }; match seed { Seed::EntropySrc => { clen = 0; flag0 = MultiBitBool::False; extra_words = &[]; } Seed::Constant(constant) => { clen = constant.len().min(MAX_SEED_WORDS); flag0 = MultiBitBool::True; extra_words = &constant[..clen]; } } glen = 0; } Command::Generate { num_128_bit_blocks } => { acmd = 3; clen = 0; flag0 = MultiBitBool::False; glen = num_128_bit_blocks; extra_words = &[]; err = CaliptraError::DRIVER_CSRNG_GENERATE; } Command::Update(words) => { acmd = 4; clen = words.len().min(MAX_SEED_WORDS); flag0 = MultiBitBool::True; glen = 0; extra_words = &words[..clen]; err = CaliptraError::DRIVER_CSRNG_UPDATE; } Command::Uninstantiate => { acmd = 5; clen = 0; flag0 = MultiBitBool::False; glen = 0; extra_words = &[]; err = CaliptraError::DRIVER_CSRNG_UNINSTANTIATE; } } // Write mandatory 32-bit command header. csrng.regs_mut().cmd_req().write(|w| { w.acmd(acmd) .clen(clen as u32) .flag0(flag0 as u32) .glen(glen as u32) }); // Write optional extra words. for &word in extra_words { csrng.regs_mut().cmd_req().write(|_| word.into()); } // Wait for command. loop { let reg = csrng.regs().sw_cmd_sts().read(); // Order matters. Check for errors first. if reg.cmd_sts() != 0 || u32::from(csrng.regs().err_code().read()) != 0 { // TODO: Somehow convey additional error information found in // the ERR_CODE register. return Err(err); } // TODO: if the hardware is fixed to make the ack flag sticky, we should // check that as well before exiting the loop. if reg.cmd_rdy() { return Ok(()); } } } fn set_health_check_thresholds( e: entropy_src::RegisterBlock<ureg::RealMmioMut>, soc_ifc: soc_ifc::RegisterBlock<ureg::RealMmio>, ) { // Configure thresholds for the two approved NIST health checks: // 1. Repetition Count Test // 2. Adaptive Proportion Test { // The Repetition Count test fails if: // * An RNG wire repeats the same bit THRESHOLD times in a row. // See section 4.4.1 of NIST.SP.800-90B for more information of about this test. // If the SOC doesn't specify a threshold, use this default, which assumes a min-entropy of 1. const DEFAULT_THRESHOLD: u32 = 41; let threshold = soc_ifc .cptra_i_trng_entropy_config_1() .read() .repetition_count(); e.repcnt_thresholds().write(|w| { w.fips_thresh(if threshold == 0 { DEFAULT_THRESHOLD } else { threshold }) }); } { // The Adaptive Proportion test fails if: // * Any window has more than the HI threshold of 1's; or, // * Any window has less than the LO threshold of 1's. // See section 4.4.2 of NIST.SP.800-90B for more information of about this test. // Use 75% and 25% of the 2048 bit FIPS window size for the default HI and LO thresholds // respectively. const WINDOW_SIZE_BITS: u32 = 2048; const DEFAULT_HI: u32 = 3 * (WINDOW_SIZE_BITS / 4); const DEFAULT_LO: u32 = WINDOW_SIZE_BITS / 4; // TODO: What to do if HI <= LO? let threshold_hi = soc_ifc .cptra_i_trng_entropy_config_0() .read() .high_threshold(); let threshold_lo = soc_ifc .cptra_i_trng_entropy_config_0() .read() .low_threshold(); e.adaptp_hi_thresholds().write(|w| { w.fips_thresh(if threshold_hi == 0 { DEFAULT_HI } else { threshold_hi }) }); e.adaptp_lo_thresholds().write(|w| { w.fips_thresh(if threshold_lo == 0 { DEFAULT_LO } else { threshold_lo }) }); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/key_vault.rs
drivers/src/key_vault.rs
/*++ Licensed under the Apache-2.0 license. File Name: key_vault.rs Abstract: File contains API for controlling the Key Vault --*/ use bitfield::bitfield; use crate::{CaliptraError, CaliptraResult}; use caliptra_registers::kv::KvReg; use zerocopy::{IntoBytes, KnownLayout, TryFromBytes}; /// Key Identifier #[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromBytes, IntoBytes, KnownLayout)] #[repr(u8)] pub enum KeyId { KeyId0 = 0, KeyId1 = 1, KeyId2 = 2, KeyId3 = 3, KeyId4 = 4, KeyId5 = 5, KeyId6 = 6, KeyId7 = 7, KeyId8 = 8, KeyId9 = 9, KeyId10 = 10, KeyId11 = 11, KeyId12 = 12, KeyId13 = 13, KeyId14 = 14, KeyId15 = 15, KeyId16 = 16, KeyId17 = 17, KeyId18 = 18, KeyId19 = 19, KeyId20 = 20, KeyId21 = 21, KeyId22 = 22, KeyId23 = 23, } impl zeroize::Zeroize for KeyId { fn zeroize(&mut self) { // This is a NOP as these enums are just a handle. // This trait is implemented so the slots can be serialized into `PersistentData`. } } impl TryFrom<u8> for KeyId { type Error = (); fn try_from(original: u8) -> Result<Self, Self::Error> { match original { 0 => Ok(Self::KeyId0), 1 => Ok(Self::KeyId1), 2 => Ok(Self::KeyId2), 3 => Ok(Self::KeyId3), 4 => Ok(Self::KeyId4), 5 => Ok(Self::KeyId5), 6 => Ok(Self::KeyId6), 7 => Ok(Self::KeyId7), 8 => Ok(Self::KeyId8), 9 => Ok(Self::KeyId9), 10 => Ok(Self::KeyId10), 11 => Ok(Self::KeyId11), 12 => Ok(Self::KeyId12), 13 => Ok(Self::KeyId13), 14 => Ok(Self::KeyId14), 15 => Ok(Self::KeyId15), 16 => Ok(Self::KeyId16), 17 => Ok(Self::KeyId17), 18 => Ok(Self::KeyId18), 19 => Ok(Self::KeyId19), 20 => Ok(Self::KeyId20), 21 => Ok(Self::KeyId21), 22 => Ok(Self::KeyId22), 23 => Ok(Self::KeyId23), _ => Err(()), } } } impl From<KeyId> for u8 { /// Converts to this type from the input type. fn from(key_id: KeyId) -> Self { key_id as Self } } impl From<KeyId> for u32 { /// Converts to this type from the input type. fn from(key_id: KeyId) -> Self { key_id as Self } } impl From<KeyId> for usize { /// Converts to this type from the input type. fn from(key_id: KeyId) -> Self { key_id as Self } } bitfield! { /// Key Usage #[derive(Debug, Default, PartialEq, Eq, Clone, Copy)] pub struct KeyUsage(u32); /// Flag indicating if the key can be used as HMAC key pub hmac_key, set_hmac_key: 0; /// Flag indicating if the key can be used as HMAC data pub hmac_data, set_hmac_data: 1; /// Flag indicating if the key can be used as MLDSA Key Generation seed pub mldsa_seed, set_mldsa_key_gen_seed: 2; /// Flag indicating if the key can be used as ECC Private Key pub ecc_private_key, set_ecc_private_key: 3; /// Flag indicating if the key can be used as ECC Key Generation Seed pub ecc_key_gen_seed, set_ecc_key_gen_seed: 4; /// Flag indicating if the key can be used as AES key pub aes_key, set_aes_key: 5; /// Flag indicating if the key can be used as ML-KEM seed pub mlkem_seed, set_mlkem_seed: 6; /// Flag indicating if the key can be used as ML-KEM message pub mlkem_msg, set_mlkem_msg: 7; /// Flag indicating if the key can be used as DMA data pub dma_data, set_dma_data: 8; } impl KeyUsage { pub fn set_hmac_key_en(&mut self) -> KeyUsage { self.set_hmac_key(true); *self } pub fn set_hmac_data_en(&mut self) -> KeyUsage { self.set_hmac_data(true); *self } pub fn set_mldsa_key_gen_seed_en(&mut self) -> KeyUsage { self.set_mldsa_key_gen_seed(true); *self } pub fn set_ecc_private_key_en(&mut self) -> KeyUsage { self.set_ecc_private_key(true); *self } pub fn set_ecc_key_gen_seed_en(&mut self) -> KeyUsage { self.set_ecc_key_gen_seed(true); *self } pub fn set_aes_key_en(&mut self) -> KeyUsage { self.set_aes_key(true); *self } pub fn set_mlkem_seed_en(&mut self) -> KeyUsage { self.set_mlkem_seed(true); *self } pub fn set_mlkem_msg_en(&mut self) -> KeyUsage { self.set_mlkem_msg(true); *self } pub fn set_dma_data_en(&mut self) -> KeyUsage { self.set_dma_data(true); *self } } /// Caliptra Key Vault pub struct KeyVault { kv: KvReg, } impl KeyVault { pub fn new(kv: KvReg) -> Self { KeyVault { kv } } /// Erase all the keys in the key vault /// /// Note: The keys that have "use" or "write" lock set will not be erased pub fn erase_all_keys(&mut self) { const KEY_IDS: [KeyId; 24] = [ KeyId::KeyId0, KeyId::KeyId1, KeyId::KeyId2, KeyId::KeyId3, KeyId::KeyId4, KeyId::KeyId5, KeyId::KeyId6, KeyId::KeyId7, KeyId::KeyId8, KeyId::KeyId9, KeyId::KeyId10, KeyId::KeyId11, KeyId::KeyId12, KeyId::KeyId13, KeyId::KeyId14, KeyId::KeyId15, KeyId::KeyId16, KeyId::KeyId17, KeyId::KeyId18, KeyId::KeyId19, KeyId::KeyId20, KeyId::KeyId21, KeyId::KeyId22, KeyId::KeyId23, ]; for id in KEY_IDS { if !self.key_use_lock(id) && !self.key_write_lock(id) { let kv = self.kv.regs_mut(); kv.key_ctrl().at(id.into()).write(|w| w.clear(true)); } } } /// Erase specified key /// /// # Arguments /// /// * `id` - Key ID to erase pub fn erase_key(&mut self, id: KeyId) -> CaliptraResult<()> { if self.key_use_lock(id) { return Err(CaliptraError::DRIVER_KV_ERASE_USE_LOCK_SET_FAILURE); } if self.key_write_lock(id) { return Err(CaliptraError::DRIVER_KV_ERASE_WRITE_LOCK_SET_FAILURE); } let kv = self.kv.regs_mut(); kv.key_ctrl().at(id.into()).write(|w| w.clear(true)); Ok(()) } /// Retrieve the write lock status for a key /// /// # Arguments /// /// * `id` - Key ID /// /// # Returns /// * `true` - If the key is write locked /// * `false` - If the Key is not write locked pub fn key_write_lock(&self, id: KeyId) -> bool { let kv = self.kv.regs(); kv.key_ctrl().at(id.into()).read().lock_wr() } /// Set the write lock for a key /// /// # Arguments /// /// * `id` - Key ID pub fn set_key_write_lock(&mut self, id: KeyId) { let kv = self.kv.regs_mut(); kv.key_ctrl().at(id.into()).write(|w| w.lock_wr(true)) } /// Clear the write lock for a key /// /// # Arguments /// /// * `id` - Key ID pub fn clear_key_write_lock(&mut self, id: KeyId) { let kv = self.kv.regs_mut(); kv.key_ctrl().at(id.into()).write(|w| w.lock_wr(false)) } /// Retrieve the use lock status for a key /// /// # Arguments /// /// * `id` - Key ID /// /// # Returns /// * `true` - If the key is use locked /// * `false` - If the Key is not use locked pub fn key_use_lock(&mut self, id: KeyId) -> bool { let kv = self.kv.regs_mut(); kv.key_ctrl().at(id.into()).read().lock_use() } /// Set the use lock for a key /// /// # Arguments /// /// * `id` - Key ID pub fn set_key_use_lock(&mut self, id: KeyId) { let kv = self.kv.regs_mut(); kv.key_ctrl().at(id.into()).write(|w| w.lock_use(true)) } /// Clear the use lock for a key /// /// # Arguments /// /// * `id` - Key ID pub fn clear_key_use_lock(&mut self, id: KeyId) { let kv = self.kv.regs_mut(); kv.key_ctrl().at(id.into()).write(|w| w.lock_use(false)) } /// Retrieve the Key usage for a key /// /// # Arguments /// /// * `id` - Key ID /// /// # Returns /// * `KeyUsage` - Key Usage pub fn key_usage(&mut self, id: KeyId) -> KeyUsage { let kv = self.kv.regs_mut(); let val = kv.key_ctrl().at(id.into()).read(); KeyUsage(val.dest_valid()) } /// Erase the key vault /// This is useful to call from a fatal-error-handling routine. /// /// # Safety /// /// The caller must be certain that the results of any pending cryptographic /// operations will not be used after this function is called. /// /// This function is safe to call from a trap handler. pub unsafe fn zeroize() { KeyVault::new(unsafe { KvReg::new() }).erase_all_keys() } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/src/hand_off.rs
drivers/src/hand_off.rs
// Licensed under the Apache-2.0 license. use crate::bounded_address::RomAddr; use crate::{persistent, soc_ifc}; use crate::{Ecc384PubKey, Ecc384Signature, KeyId, ResetReason}; use bitfield::{bitfield_bitrange, bitfield_fields}; use caliptra_error::CaliptraError; use caliptra_image_types::RomInfo; use core::mem::size_of; use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, TryFromBytes}; use zeroize::Zeroize; pub const FHT_MARKER: u32 = 0x54484643; pub const FHT_INVALID_ADDRESS: u32 = u32::MAX; #[repr(C)] #[derive(IntoBytes, Immutable, KnownLayout, Copy, Clone, Debug, FromBytes, PartialEq, Zeroize)] pub struct HandOffDataHandle(pub u32); pub const FHT_INVALID_HANDLE: HandOffDataHandle = HandOffDataHandle(u32::MAX); bitfield_bitrange! {struct HandOffDataHandle(u32)} impl HandOffDataHandle { bitfield_fields! { u32; reg_num, set_reg_num: 7, 0; reg_type, set_reg_type: 11, 8; vault, set_vault : 15, 12; reserved, _: 31, 16; } pub fn is_valid(&self) -> bool { self.0 != u32::MAX } } #[repr(u32)] pub enum Vault { KeyVault = 1, PcrBank = 2, DataVault = 3, } impl From<Vault> for u32 { fn from(val: Vault) -> u32 { match val { Vault::KeyVault => 1, Vault::PcrBank => 2, Vault::DataVault => 3, } } } impl TryFrom<u32> for Vault { type Error = (); fn try_from(val: u32) -> Result<Self, Self::Error> { match val { 1_u32 => Ok(Vault::KeyVault), 2_u32 => Ok(Vault::PcrBank), 3_u32 => Ok(Vault::DataVault), _ => Err(()), } } } pub enum DataStore { KeyVaultSlot(KeyId), //PlatformConfigRegister(PcrId), Invalid, } impl From<HandOffDataHandle> for u32 { fn from(value: HandOffDataHandle) -> u32 { value.0 } } #[allow(non_snake_case)] pub enum DataVaultRegister { Sticky32BitReg = 1, Sticky384BitReg = 2, NonSticky32BitReg = 3, NonSticky384BitReg = 4, } impl TryInto<DataStore> for HandOffDataHandle { type Error = CaliptraError; fn try_into(self) -> Result<DataStore, Self::Error> { let vault = Vault::try_from(self.vault()) .map_err(|_| CaliptraError::DRIVER_HANDOFF_INVALID_VAULT)?; match vault { Vault::KeyVault => Ok(DataStore::KeyVaultSlot( KeyId::try_from(self.reg_num() as u8) .map_err(|_| CaliptraError::DRIVER_HANDOFF_INVALID_KEY_ID)?, )), _ => Err(CaliptraError::DRIVER_BAD_DATASTORE_VAULT_TYPE), } } } impl From<DataStore> for HandOffDataHandle { fn from(val: DataStore) -> HandOffDataHandle { match val { DataStore::KeyVaultSlot(key_id) => { let mut me = Self(0); me.set_vault(u32::from(Vault::KeyVault)); me.set_reg_num(key_id.into()); me } _ => { let mut me = Self(0); me.set_vault(0); me.set_reg_type(0); me.set_reg_num(0); me } } } } const FHT_RESERVED_SIZE: usize = 1664; /// The Firmware Handoff Table is a data structure that is resident at a well-known /// location in DCCM. It is initially populated by ROM and modified by FMC as a way /// to pass parameters and configuration information from one firmware layer to the next. const _: () = assert!(size_of::<FirmwareHandoffTable>() == persistent::FHT_SIZE as usize); #[repr(C)] #[derive(Clone, Debug, IntoBytes, TryFromBytes, Immutable, KnownLayout, Zeroize)] pub struct FirmwareHandoffTable { /// Magic Number marking start of table. Value must be 0x54484643 /// (‘CFHT’ when viewed as little-endian ASCII). pub fht_marker: u32, /// Major version of FHT. pub fht_major_ver: u16, /// Minor version of FHT. Initially written by ROM but may be changed to /// a higher version by FMC. pub fht_minor_ver: u16, /// Physical base address of Manifest in DCCM SRAM. pub manifest_load_addr: u32, /// Physical base address of FIPS Module in ROM or ICCM SRAM. /// May be NULL if there is no discrete module. pub fips_fw_load_addr_hdl: HandOffDataHandle, /// Index of FMC CDI value in the Key Vault. Value of 0xFF indicates not present. pub fmc_cdi_kv_hdl: HandOffDataHandle, /// Index of FMC Private Alias Key in the Key Vault. pub fmc_ecc_priv_key_kv_hdl: HandOffDataHandle, /// Index of FMC Alias MLDSA key pair generation seed in the Key Vault. pub fmc_mldsa_keypair_seed_kv_hdl: HandOffDataHandle, /// Index of RT CDI value in the Key Vault. pub rt_cdi_kv_hdl: HandOffDataHandle, /// Index of RT Private Alias Key in the Key Vault. pub rt_priv_key_kv_hdl: HandOffDataHandle, /// ECC LdevId TBS Address pub ecc_ldevid_tbs_addr: u32, /// ECC FmcAlias TBS Address pub ecc_fmcalias_tbs_addr: u32, /// ECC LdevId TBS Size pub ecc_ldevid_tbs_size: u16, /// ECC FmcAlias TBS Size pub ecc_fmcalias_tbs_size: u16, /// MLDSA LdevId TBS Address pub mldsa_ldevid_tbs_addr: u32, /// MLDSA FmcAlias TBS Address pub mldsa_fmcalias_tbs_addr: u32, /// MLDSA LdevId TBS Size pub mldsa_ldevid_tbs_size: u16, /// MLDSA FmcAlias TBS Size pub mldsa_fmcalias_tbs_size: u16, /// PCR log Address pub pcr_log_addr: u32, /// Last empty PCR log entry slot index pub pcr_log_index: u32, /// Measurement log Address pub meas_log_addr: u32, // Last empty measurement log entry slot index pub meas_log_index: u32, /// Fuse log Address pub fuse_log_addr: u32, /// RtAlias public key. pub rt_dice_ecc_pub_key: Ecc384PubKey, /// RtAlias certificate signature. pub rt_dice_ecc_sign: Ecc384Signature, /// IDevID ECDSA public key pub idev_dice_ecdsa_pub_key: Ecc384PubKey, /// IDevID MLDSA public key address in DCCM pub idev_dice_mldsa_pub_key_load_addr: u32, /// Address of RomInfo struct pub rom_info_addr: RomAddr<RomInfo>, /// ECC RtAlias TBS Size pub rtalias_ecc_tbs_size: u16, /// Maximum value FW SVN can take. pub fw_key_ladder_max_svn: u16, /// Index of FW key ladder value in the Key Vault. pub fw_key_ladder_kv_hdl: HandOffDataHandle, /// Reserved for future use. pub reserved: [u8; FHT_RESERVED_SIZE], } impl Default for FirmwareHandoffTable { fn default() -> Self { Self { fht_marker: 0, fht_major_ver: 0, fht_minor_ver: 0, manifest_load_addr: FHT_INVALID_ADDRESS, fips_fw_load_addr_hdl: FHT_INVALID_HANDLE, fmc_cdi_kv_hdl: FHT_INVALID_HANDLE, fmc_ecc_priv_key_kv_hdl: FHT_INVALID_HANDLE, fmc_mldsa_keypair_seed_kv_hdl: FHT_INVALID_HANDLE, rt_cdi_kv_hdl: FHT_INVALID_HANDLE, rt_priv_key_kv_hdl: FHT_INVALID_HANDLE, ecc_ldevid_tbs_addr: 0, ecc_fmcalias_tbs_addr: 0, ecc_ldevid_tbs_size: 0, ecc_fmcalias_tbs_size: 0, mldsa_ldevid_tbs_addr: 0, mldsa_fmcalias_tbs_addr: 0, mldsa_ldevid_tbs_size: 0, mldsa_fmcalias_tbs_size: 0, pcr_log_addr: 0, pcr_log_index: 0, meas_log_addr: 0, meas_log_index: 0, fuse_log_addr: 0, rt_dice_ecc_pub_key: Ecc384PubKey::default(), rt_dice_ecc_sign: Ecc384Signature::default(), idev_dice_ecdsa_pub_key: Ecc384PubKey::default(), idev_dice_mldsa_pub_key_load_addr: 0, rom_info_addr: RomAddr::new(FHT_INVALID_ADDRESS), rtalias_ecc_tbs_size: 0, fw_key_ladder_max_svn: 0, fw_key_ladder_kv_hdl: HandOffDataHandle(0), reserved: [0u8; FHT_RESERVED_SIZE], } } } /// Print the Firmware Handoff Table. pub fn print_fht(fht: &FirmwareHandoffTable) { crate::cprintln!("Firmware Handoff Table"); crate::cprintln!("----------------------"); crate::cprintln!("FHT Marker: 0x{:08x}", fht.fht_marker); crate::cprintln!("FHT Major Version: {}", fht.fht_major_ver); crate::cprintln!("FHT Minor Version: {}", fht.fht_minor_ver); crate::cprintln!("Manifest Load Address: 0x{:08x}", fht.manifest_load_addr); crate::cprintln!( "FIPS FW Load Address: 0x{:08x}", fht.fips_fw_load_addr_hdl.0 ); crate::cprintln!("FMC CDI KV Handle: 0x{:08x}", fht.fmc_cdi_kv_hdl.0); crate::cprintln!( "FMC ECC Private Key KV Handle: 0x{:08x}", fht.fmc_ecc_priv_key_kv_hdl.0 ); crate::cprintln!( "FMC MLDSA Key Pair Generation Seed KV Handle: 0x{:08x}", fht.fmc_mldsa_keypair_seed_kv_hdl.0 ); crate::cprintln!("RT CDI KV Handle: 0x{:08x}", fht.rt_cdi_kv_hdl.0); crate::cprintln!( "RT Private Key KV Handle: 0x{:08x}", fht.rt_priv_key_kv_hdl.0 ); crate::cprintln!( "IdevId MLDSA Public Key Address: 0x{:08x}", fht.idev_dice_mldsa_pub_key_load_addr ); crate::cprintln!("LdevId TBS Address: 0x{:08x}", fht.ecc_ldevid_tbs_addr); crate::cprintln!("LdevId TBS Size: {} bytes", fht.ecc_ldevid_tbs_size); crate::cprintln!("FmcAlias TBS Address: 0x{:08x}", fht.ecc_fmcalias_tbs_addr); crate::cprintln!("FmcAlias TBS Size: {} bytes", fht.ecc_fmcalias_tbs_size); crate::cprintln!("RtAlias TBS Size: {} bytes", fht.rtalias_ecc_tbs_size); crate::cprintln!("PCR log Address: 0x{:08x}", fht.pcr_log_addr); crate::cprintln!("PCR log Index: {}", fht.pcr_log_index); crate::cprintln!("Measurement log Address: {}", fht.meas_log_addr); crate::cprintln!("Measurement log Index: {}", fht.meas_log_index); crate::cprintln!("Fuse log Address: 0x{:08x}", fht.fuse_log_addr); } impl FirmwareHandoffTable { /// Perform validity check of the table's data. /// The fields below should have been populated by ROM with /// valid data before it transfers control to mutable code. /// This function can only be called from non test case environment /// as this function accesses the registers to get the reset_reason. pub fn is_valid(&self) -> bool { let reset_reason = soc_ifc::reset_reason(); let mut valid = self.fht_marker == FHT_MARKER && self.fmc_cdi_kv_hdl != FHT_INVALID_HANDLE && self.manifest_load_addr != FHT_INVALID_ADDRESS // This is for Gen1 POR. && self.fips_fw_load_addr_hdl == FHT_INVALID_HANDLE && self.ecc_ldevid_tbs_addr != 0 && self.ecc_fmcalias_tbs_addr != 0 && self.pcr_log_addr != 0 && self.meas_log_addr != 0 && self.fuse_log_addr != 0 && self.rom_info_addr.is_valid(); if valid && reset_reason == ResetReason::ColdReset && (self.ecc_ldevid_tbs_size == 0 || self.ecc_fmcalias_tbs_size == 0) { valid = false; } valid } } #[cfg(all(test, target_family = "unix"))] mod tests { use super::*; use core::mem; const FHT_SIZE: usize = 2048; const KEY_ID_FMC_ECDSA_PRIV_KEY: KeyId = KeyId::KeyId7; const KEY_ID_FMC_MLDSA_KEYPAIR_SEED: KeyId = KeyId::KeyId8; fn fmc_ecc_priv_key_store() -> HandOffDataHandle { HandOffDataHandle(((Vault::KeyVault as u32) << 12) | KEY_ID_FMC_ECDSA_PRIV_KEY as u32) } fn fmc_ecc_priv_key(fht: &FirmwareHandoffTable) -> KeyId { let ds: DataStore = fht.fmc_ecc_priv_key_kv_hdl.try_into().unwrap(); match ds { DataStore::KeyVaultSlot(key_id) => key_id, _ => panic!("Invalid FMC ECC private key store"), } } fn fmc_mldsa_keypair_seed_store() -> HandOffDataHandle { HandOffDataHandle(((Vault::KeyVault as u32) << 12) | KEY_ID_FMC_MLDSA_KEYPAIR_SEED as u32) } fn fmc_mldsa_keypair_seed_key(fht: &FirmwareHandoffTable) -> KeyId { let ds: DataStore = fht.fmc_mldsa_keypair_seed_kv_hdl.try_into().unwrap(); match ds { DataStore::KeyVaultSlot(key_id) => key_id, _ => panic!("Invalid FMC key pair generation seed store"), } } #[test] fn test_fht_is_valid() { let fht = crate::hand_off::FirmwareHandoffTable::default(); let valid = fht.fht_marker == FHT_MARKER && fht.fmc_cdi_kv_hdl != FHT_INVALID_HANDLE && fht.manifest_load_addr != FHT_INVALID_ADDRESS // This is for Gen1 POR. && fht.fips_fw_load_addr_hdl == FHT_INVALID_HANDLE && fht.ecc_ldevid_tbs_size == 0 && fht.ecc_fmcalias_tbs_size == 0 && fht.rtalias_ecc_tbs_size == 0 && fht.ecc_ldevid_tbs_addr != 0 && fht.ecc_fmcalias_tbs_addr != 0 && fht.pcr_log_addr != 0 && fht.meas_log_addr != 0 && fht.fuse_log_addr != 0; assert!(!valid); assert_eq!(FHT_SIZE, mem::size_of::<FirmwareHandoffTable>()); } #[test] fn test_fmc_ecc_priv_key_store() { let fht = crate::hand_off::FirmwareHandoffTable { fmc_ecc_priv_key_kv_hdl: fmc_ecc_priv_key_store(), ..Default::default() }; // Check that the key is stored in the KeyVault. assert_eq!(fht.fmc_ecc_priv_key_kv_hdl.vault(), Vault::KeyVault as u32); // Check the key slot is correct assert_eq!( fht.fmc_ecc_priv_key_kv_hdl.reg_num(), KEY_ID_FMC_ECDSA_PRIV_KEY.into() ); assert_eq!(fmc_ecc_priv_key(&fht), KEY_ID_FMC_ECDSA_PRIV_KEY); } #[test] fn test_fmc_mldsa_keypair_seed_store() { let fht = crate::hand_off::FirmwareHandoffTable { fmc_mldsa_keypair_seed_kv_hdl: fmc_mldsa_keypair_seed_store(), ..Default::default() }; // Check that the key is stored in the KeyVault. assert_eq!( fht.fmc_mldsa_keypair_seed_kv_hdl.vault(), Vault::KeyVault as u32 ); // Check the key slot is correct assert_eq!( fht.fmc_mldsa_keypair_seed_kv_hdl.reg_num(), KEY_ID_FMC_MLDSA_KEYPAIR_SEED.into() ); assert_eq!( fmc_mldsa_keypair_seed_key(&fht), KEY_ID_FMC_MLDSA_KEYPAIR_SEED ); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/tests/drivers_integration_tests/main.rs
drivers/tests/drivers_integration_tests/main.rs
// Licensed under the Apache-2.0 license use caliptra_api::SocManager; use std::error::Error; use std::iter; use caliptra_builder::{firmware, FwId}; use caliptra_drivers::{Array4x12, Array4xN, Ecc384PubKey}; use caliptra_drivers_test_bin::{ DoeTestResults, OCP_LOCK_WARM_RESET_MAGIC_BOOT_STATUS, PLAINTEXT_MEK, }; use caliptra_hw_model::{ BootParams, DefaultHwModel, DeviceLifecycle, Fuses, HwModel, InitParams, ModelError, SecurityState, TrngMode, }; use caliptra_hw_model_types::EtrngResponse; use caliptra_registers::mbox::enums::MboxStatusE; use caliptra_registers::soc_ifc::{ meta::{CptraItrngEntropyConfig0, CptraItrngEntropyConfig1}, regs::{CptraItrngEntropyConfig0WriteVal, CptraItrngEntropyConfig1WriteVal}, }; use caliptra_test::{ crypto::derive_ecdsa_keypair, derive::{DoeInput, DoeOutput}, }; use openssl::{hash::MessageDigest, pkey::PKey}; use ureg::ResettableReg; use zerocopy::{FromBytes, IntoBytes}; fn default_init_params() -> InitParams<'static> { InitParams { // The test harness doesn't clear memory on startup. random_sram_puf: false, ..Default::default() } } fn start_driver_test(test_rom: &'static FwId) -> Result<DefaultHwModel, Box<dyn Error>> { let rom = caliptra_builder::build_firmware_rom(test_rom)?; caliptra_hw_model::new( InitParams { rom: &rom, subsystem_mode: true, ..default_init_params() }, BootParams::default(), ) } fn run_driver_test(test_rom: &'static FwId) { let mut model = start_driver_test(test_rom).unwrap(); // Wrap in a line-writer so output from different test threads doesn't multiplex within a line. model.step_until_exit_success().unwrap(); } #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct DoeTestVectors { // The keys output by the DOE block (mostly for reference) doe_output: DoeOutput, // The expected results of the HMAC operations performed by the test. expected_test_results: DoeTestResults, } impl DoeTestVectors { /// A standalone implementation of the cryptographic operations necessary to /// generate the expected DOE test's HMAC results from fuse values and /// silicon secrets, using only openssl. This independent implementation is /// used to validate that the test-vector constants are correct. fn generate(input: &DoeInput) -> Self { use openssl::sign::Signer; fn swap_word_bytes(words: &[u32]) -> Vec<u32> { words.iter().map(|word| word.swap_bytes()).collect() } fn hmac384(key: &[u8], data: &[u8]) -> [u8; 48] { let pkey = PKey::hmac(key).unwrap(); let mut signer = Signer::new(MessageDigest::sha384(), &pkey).unwrap(); signer.update(data).unwrap(); let mut result = [0u8; 48]; signer.sign(&mut result).unwrap(); result } fn ecdsa_keygen(seed: &[u8]) -> Ecc384PubKey { let (_, pub_x, pub_y) = derive_ecdsa_keypair(seed); Ecc384PubKey { x: Array4x12::from(pub_x), y: Array4x12::from(pub_y), } } let mut result = DoeTestVectors { doe_output: DoeOutput::generate(input), expected_test_results: Default::default(), }; result.expected_test_results.hmac_uds_as_key_out_pub = ecdsa_keygen(&hmac384( swap_word_bytes(&result.doe_output.uds[..12]).as_bytes(), "Hello world!".as_bytes(), )); result.expected_test_results.hmac_uds_as_data_out_pub = ecdsa_keygen(&hmac384( swap_word_bytes(&caliptra_drivers_test_bin::DOE_TEST_HMAC_KEY).as_bytes(), swap_word_bytes(&result.doe_output.uds[..]).as_bytes(), )); result .expected_test_results .hmac_field_entropy_as_key_out_pub = ecdsa_keygen(&hmac384( swap_word_bytes(&result.doe_output.field_entropy).as_bytes(), "Hello world!".as_bytes(), )); result .expected_test_results .hmac_field_entropy_as_data_out_pub = ecdsa_keygen(&hmac384( swap_word_bytes(&caliptra_drivers_test_bin::DOE_TEST_HMAC_KEY).as_bytes(), swap_word_bytes(&result.doe_output.field_entropy[0..8]).as_bytes(), )); result } } const DOE_TEST_VECTORS_DEBUG_MODE: DoeTestVectors = DoeTestVectors { doe_output: DoeOutput { // The decrypted UDS as stored in the key vault uds: [ 0x34aa667c, 0x0a52c71f, 0x977a1de2, 0x701ef611, 0x0de19e21, 0x24b49b9d, 0xdf205ff6, 0xa9c04303, 0x0de19e21, 0x24b49b9d, 0xdf205ff6, 0xa9c04303, 0xde19e21, 0x24b49b9d, 0xdf205ff6, 0xa9c04303, ], // The decrypted field entropy as stored in the key vault (with padding) field_entropy: [ 0x34aa667c, 0x0a52c71f, 0x977a1de2, 0x701ef611, 0x0de19e21, 0x24b49b9d, 0xdf205ff6, 0xa9c04303, 0xaaaa_aaaa, 0xaaaa_aaaa, 0xaaaa_aaaa, 0xaaaa_aaaa, ], }, // The expected results of the HMAC operations performed by the test. expected_test_results: DoeTestResults { hmac_uds_as_key_out_pub: Ecc384PubKey { x: Array4xN([ 1687789458, 142258272, 2190842666, 3455247989, 3888056521, 676567898, 1336470794, 2772318121, 1868025422, 1214582545, 729740624, 3009942988, ]), y: Array4xN([ 1187075527, 1937696016, 725517213, 1501324878, 2274800079, 3298049249, 2385708560, 2858668788, 4158119455, 4066756829, 2930473191, 2541516328, ]), }, hmac_uds_as_data_out_pub: Ecc384PubKey { x: Array4xN([ 1438431832, 91501610, 3152050518, 3849598638, 2197378185, 417619109, 77559675, 2990865579, 2668993830, 904442065, 1785111458, 1475988172, ]), y: Array4xN([ 2923137036, 2125179915, 3914711845, 1282782339, 2731413282, 1946917941, 968766149, 1347975894, 3058578942, 1092934175, 3697179863, 384277117, ]), }, hmac_field_entropy_as_key_out_pub: Ecc384PubKey { x: Array4xN([ 2239914737, 538068278, 2639025677, 1218690763, 2952038842, 1448164004, 2126938572, 1397119203, 3400164743, 1553307000, 1579829226, 1671197033, ]), y: Array4xN([ 3709694348, 821080470, 4215236444, 3339301837, 1042205687, 3394791030, 4205793518, 3991744897, 1399279513, 2065955491, 4026223323, 2237883749, ]), }, hmac_field_entropy_as_data_out_pub: Ecc384PubKey { x: Array4xN([ 16127504, 1807623126, 1448292055, 4052217305, 961911699, 747606231, 2311165349, 1941850149, 1401263727, 2590911470, 4055801696, 960530379, ]), y: Array4xN([ 1246980440, 861204768, 2361057385, 1637522451, 1778431949, 1653325401, 3260666418, 2934023501, 2085910263, 534236754, 4209071048, 1469026788, ]), }, }, }; #[test] fn test_generate_doe_vectors_when_debug_not_locked() { // When microcontroller debugging is possible, all the secrets are set by the hardware to // 0xffff_ffff words. let vectors = DoeTestVectors::generate(&DoeInput { doe_obf_key: [0xffff_ffff_u32; 8], doe_iv: caliptra_drivers_test_bin::DOE_TEST_IV, uds_seed: [0xffff_ffff_u32; 16], field_entropy_seed: [0xffff_ffff_u32; 8], // In debug mode, this defaults to 0xaaaa_aaaa keyvault_initial_word_value: 0xaaaa_aaaa, }); assert_eq!(vectors, DOE_TEST_VECTORS_DEBUG_MODE); } #[test] fn test_doe_when_debug_not_locked() { let rom = caliptra_builder::build_firmware_rom(&firmware::driver_tests::DOE).unwrap(); let mut model = caliptra_hw_model::new( InitParams { rom: &rom, security_state: *SecurityState::from(0) .set_debug_locked(false) .set_device_lifecycle(DeviceLifecycle::Unprovisioned), ..default_init_params() }, BootParams::default(), ) .unwrap(); let txn = model.wait_for_mailbox_receive().unwrap(); let test_results = DoeTestResults::read_from_bytes(txn.req.data.as_slice()).unwrap(); assert_eq!( test_results, DOE_TEST_VECTORS_DEBUG_MODE.expected_test_results ) } const DOE_TEST_VECTORS: DoeTestVectors = DoeTestVectors { doe_output: DoeOutput { uds: [ 0x0b21f10f, 0x6963005e, 0x4884d93f, 0x1f91037a, 0x2d37ffe0, 0x3727b5e8, 0xb78b9608, 0x7e0e58d2, 0x420ce5ae, 0x4b1f04f8, 0x33b7af81, 0x72156bd8, 0xf55d652c, 0xfbdb1831, 0x58517e56, 0xfe1eab2f, ], field_entropy: [ 0x3d75d35e, 0xbc44a31e, 0xad27aee5, 0x75cdd170, 0xe51dcaf4, 0x09c096ae, 0xa70ff448, 0x64834722, 0x00000000, 0x00000000, 0x00000000, 0x00000000, ], }, expected_test_results: DoeTestResults { hmac_uds_as_key_out_pub: Ecc384PubKey { x: Array4xN([ 1178783211, 2409029871, 3242977838, 333888818, 19263069, 1643510496, 1837442823, 239210134, 2976376890, 240016293, 1829920246, 604673977, ]), y: Array4xN([ 3252295486, 3312576043, 2990063596, 1387770200, 3920640176, 2062006057, 1799980987, 899709785, 2852029226, 637830070, 1807068751, 2015236177, ]), }, hmac_uds_as_data_out_pub: Ecc384PubKey { x: Array4xN([ 3519766303, 3354676807, 3747479553, 2304531574, 2894772719, 2957721906, 1044720752, 4106894639, 3908320550, 2380496761, 3258940448, 848924534, ]), y: Array4xN([ 22369564, 4258207111, 2470951412, 780425899, 3219800193, 2514363082, 1688427174, 2372591398, 2334049956, 4294170300, 3076839425, 1889260056, ]), }, hmac_field_entropy_as_key_out_pub: Ecc384PubKey { x: Array4xN([ 4052491145, 4186721582, 3342395483, 1632463994, 3193016662, 2204970242, 3835027544, 2485671111, 2469363717, 1330346930, 2623488737, 1958899419, ]), y: Array4xN([ 869015362, 1303913274, 842048451, 2998827085, 1486265410, 3771523089, 3956677016, 2319947800, 4167697556, 3174143636, 820486910, 130118441, ]), }, hmac_field_entropy_as_data_out_pub: Ecc384PubKey { x: Array4xN([ 735969067, 3049012269, 857888742, 684684485, 4194103772, 1793570427, 1430366021, 731826037, 58870749, 3416840020, 1596867363, 2600165352, ]), y: Array4xN([ 3945293618, 150193248, 768912283, 1992928474, 552325555, 2348526265, 299333051, 253904886, 3695053587, 1856777670, 4185130766, 2902538852, ]), }, }, }; #[test] fn test_generate_doe_vectors_when_debug_locked() { let vectors = DoeTestVectors::generate(&DoeInput { doe_obf_key: caliptra_hw_model_types::DEFAULT_CPTRA_OBF_KEY, doe_iv: caliptra_drivers_test_bin::DOE_TEST_IV, uds_seed: caliptra_hw_model_types::DEFAULT_UDS_SEED, field_entropy_seed: caliptra_hw_model_types::DEFAULT_FIELD_ENTROPY, // in debug-locked mode, this defaults to 0 keyvault_initial_word_value: 0x0000_0000, }); assert_eq!(vectors, DOE_TEST_VECTORS); } #[test] fn test_doe_when_debug_locked() { let rom = caliptra_builder::build_firmware_rom(&firmware::driver_tests::DOE).unwrap(); let mut model = caliptra_hw_model::new( InitParams { rom: &rom, security_state: *SecurityState::from(0) .set_debug_locked(true) .set_device_lifecycle(DeviceLifecycle::Production), ..default_init_params() }, BootParams::default(), ) .unwrap(); let txn = model.wait_for_mailbox_receive().unwrap(); let test_results = DoeTestResults::read_from_bytes(txn.req.data.as_slice()).unwrap(); assert_eq!(test_results, DOE_TEST_VECTORS.expected_test_results); txn.respond_success(); model.step_until_exit_success().unwrap(); } #[test] fn test_aes() { run_driver_test(&firmware::driver_tests::AES); } #[test] fn test_ecc384() { run_driver_test(&firmware::driver_tests::ECC384); } #[test] fn test_ecc384_sign_validation_failure() { let mut model = start_driver_test(&firmware::driver_tests::ECC384_SIGN_VALIDATION_FAILURE).unwrap(); model.step_until_exit_failure().unwrap(); assert!(model .output() .take(16384) .contains("CFI Panic code=0x01040055")); } #[test] fn test_ml_dsa87() { run_driver_test(&firmware::driver_tests::ML_DSA87); } // These are split because they don't all fit within the test ROM image #[test] fn test_ml_dsa87_external_mu() { run_driver_test(&firmware::driver_tests::ML_DSA87_EXTERNAL_MU); } #[test] fn test_ml_kem() { run_driver_test(&firmware::driver_tests::ML_KEM); } #[test] fn test_error_reporter() { run_driver_test(&firmware::driver_tests::ERROR_REPORTER); } #[test] fn test_hmac() { run_driver_test(&firmware::driver_tests::HMAC); } #[test] fn test_keyvault() { run_driver_test( if cfg!(any(feature = "fpga_realtime", feature = "fpga_subsystem")) { &firmware::driver_tests::KEYVAULT_FPGA } else { &firmware::driver_tests::KEYVAULT }, ); } #[test] fn test_mailbox_soc_to_uc() { let mut model = start_driver_test(&firmware::driver_tests::MAILBOX_DRIVER_RESPONDER).unwrap(); // Test MailboxRecvTxn::recv_request() { let resp = model .mailbox_execute( 0x5000_0000, &[0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef], ) .unwrap(); // With recv_request(), the mailbox transaction is completed as // successful before the firmware as a chance to look at the buffer (!?), // so give the firmware a chance to print it out. model .step_until_output_and_take( "cmd: 0x50000000\n\ dlen: 8\n\ buf: [67452301, efcdab89, 00000000, 00000000]\n", ) .unwrap(); assert_eq!(resp, None); // Try again, but with a non-multiple-of-4 size let resp = model .mailbox_execute(0x5000_0000, &[0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd]) .unwrap(); model .step_until_output_and_take( "cmd: 0x50000000\n\ dlen: 7\n\ buf: [67452301, 00cdab89, 00000000, 00000000]\n", ) .unwrap(); assert_eq!(resp, None); // Try again, but with no data in the FIFO let resp = model.mailbox_execute(0x5000_0000, &[]).unwrap(); model .step_until_output_and_take( "cmd: 0x50000000\n\ dlen: 0\n\ buf: [00000000, 00000000, 00000000, 00000000]\n", ) .unwrap(); assert_eq!(resp, None); // Try again, but with a non-multiple-of-4 dest buffer (0x5000_0001) let resp = model .mailbox_execute(0x5000_0001, &[0x01, 0x23, 0x45, 0x67, 0x89]) .unwrap(); model .step_until_output_and_take( "cmd: 0x50000001\n\ dlen: 5\n\ buf: [01, 23, 45, 67, 89]\n", ) .unwrap(); assert_eq!(resp, None); // Try again, but with one more byte than will fit in the dest buffer let resp = model .mailbox_execute(0x5000_0001, &[0x01, 0x23, 0x45, 0x67, 0x89, 0xab]) .unwrap(); model .step_until_output_and_take( "cmd: 0x50000001\n\ dlen: 6\n\ buf: [01, 23, 45, 67, 89]\n", ) .unwrap(); assert_eq!(resp, None); // Try again, but with 4 more bytes than will fit in the dest buffer let resp = model .mailbox_execute( 0x5000_0001, &[0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x11], ) .unwrap(); model .step_until_output_and_take( "cmd: 0x50000001\n\ dlen: 9\n\ buf: [01, 23, 45, 67, 89]\n", ) .unwrap(); assert_eq!(resp, None); } // Test MailboxRecvTxn::copy_request { let resp = model .mailbox_execute( 0x6000_0000, &[ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, ], ) .unwrap(); model .step_until_output_and_take( "cmd: 0x60000000\n\ dlen: 16\n\ buf: [67452301, efcdab89]\n\ buf: [33221100, 77665544]\n", ) .unwrap(); assert_eq!(resp, None); // Try again, but with a non-multiple-of-4 size let resp = model .mailbox_execute( 0x6000_0000, &[ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x11, 0x22, 0x33, 0x44, ], ) .unwrap(); model .step_until_output_and_take( "cmd: 0x60000000\n\ dlen: 13\n\ buf: [67452301, efcdab89]\n\ buf: [33221100, 00000044]\n", ) .unwrap(); assert_eq!(resp, None); // Try again, but where the buffer is larger than the last chunk let resp = model .mailbox_execute( 0x6000_0000, &[ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x00, 0x11, 0x22, 0x33, ], ) .unwrap(); model .step_until_output_and_take( "cmd: 0x60000000\n\ dlen: 12\n\ buf: [67452301, efcdab89]\n\ buf: [33221100, 00000000]\n", ) .unwrap(); assert_eq!(resp, None); // Try again, but with no data in the FIFO let resp = model.mailbox_execute(0x6000_0000, &[]).unwrap(); model .step_until_output_and_take( "cmd: 0x60000000\n\ dlen: 0\n", ) .unwrap(); assert_eq!(resp, None); } // Test MailboxRecvTxn completed with success without draining the FIFO { let resp = model .mailbox_execute(0x7000_0000, &[0x88, 0x99, 0xaa, 0xbb]) .unwrap(); model .step_until_output_and_take("cmd: 0x70000000\n") .unwrap(); assert_eq!(resp, None); // Make sure the next command doesn't see the FIFO from the previous command let resp = model .mailbox_execute(0x6000_0000, &[0x07, 0x06, 0x05, 0x04, 0x03]) .unwrap(); model .step_until_output_and_take( "cmd: 0x60000000\n\ dlen: 5\n\ buf: [04050607, 00000003]\n", ) .unwrap(); assert_eq!(resp, None); } // Test MailboxRecvTxn completed with failure without draining the FIFO { assert_eq!( model.mailbox_execute(0x8000_0000, &[0x88, 0x99, 0xaa, 0xbb]), Err(ModelError::MailboxCmdFailed(0)) ); model .step_until_output_and_take("cmd: 0x80000000\n") .unwrap(); // Make sure the next command doesn't see the FIFO from the previous command let resp = model .mailbox_execute(0x6000_0000, &[0x07, 0x06, 0x05, 0x04, 0x03]) .unwrap(); model .step_until_output_and_take( "cmd: 0x60000000\n\ dlen: 5\n\ buf: [04050607, 00000003]\n", ) .unwrap(); assert_eq!(resp, None); } // Test drop_words { let resp = model .mailbox_execute( 0x9000_0000, &[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08], ) .unwrap(); model .step_until_output_and_take( "cmd: 0x90000000\n\ dlen: 8\n\ buf: [08070605]\n", ) .unwrap(); assert_eq!(resp, None); } // Test 4 byte response with no request data { let resp = model.mailbox_execute(0xA000_0000, &[]).unwrap().unwrap(); model .step_until_output_and_take("cmd: 0xa0000000\n") .unwrap(); assert_eq!(resp, [0x12, 0x34, 0x56, 0x78]); } // Test 2 byte response with request data { let resp = model .mailbox_execute(0xB000_0000, &[0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0xa]) .unwrap() .unwrap(); model .step_until_output_and_take( "cmd: 0xb0000000\n\ dlen: 6\n\ buf: [0c0d0e0f, 00000a0b]\n", ) .unwrap(); assert_eq!(resp, [0x98, 0x76]); } // Test 9 byte reponse { let resp = model.mailbox_execute(0xC000_0000, &[]).unwrap().unwrap(); model .step_until_output_and_take("cmd: 0xc0000000\n") .unwrap(); assert_eq!(resp, [0x0A, 0x0B, 0x0C, 0x0D, 0x05, 0x04, 0x03, 0x02, 0x01]); } // Test reponse with 0 bytes (still calls copy_response) { let resp = model.mailbox_execute(0xD000_0000, &[]).unwrap().unwrap(); model .step_until_output_and_take("cmd: 0xd0000000\n") .unwrap(); assert_eq!(resp, [] as [u8; 0]); } // Ensure there isn't any unexpected output for _i in 0..100000 { model.step(); } assert_eq!(model.output().take(usize::MAX), ""); } #[test] fn test_mailbox_uc_to_soc() { let mut model = start_driver_test(&firmware::driver_tests::MAILBOX_DRIVER_SENDER).unwrap(); // 0 byte request let txn = model.wait_for_mailbox_receive().unwrap(); assert_eq!(txn.req.cmd, 0xa000_0000); assert_eq!(txn.req.data, b""); txn.respond_success(); // 3 byte request let txn = model.wait_for_mailbox_receive().unwrap(); assert_eq!(txn.req.cmd, 0xa000_1000); assert_eq!(txn.req.data, b"Hi!"); // NOTE: The current driver doesn't actually look at the result txn.respond_success(); // 4 byte request let txn = model.wait_for_mailbox_receive().unwrap(); assert_eq!(txn.req.cmd, 0xa000_2000); assert_eq!(txn.req.data, b"Hi!!"); txn.respond_success(); // 6 byte request let txn = model.wait_for_mailbox_receive().unwrap(); assert_eq!(txn.req.cmd, 0xa000_3000); assert_eq!(txn.req.data, b"Hello!"); txn.respond_success(); // 8 byte request let txn = model.wait_for_mailbox_receive().unwrap(); assert_eq!(txn.req.cmd, 0xa000_4000); assert_eq!(txn.req.data, b"Hello!!!"); txn.respond_success(); // write_cmd / write_dlen / execute_request used separately let txn = model.wait_for_mailbox_receive().unwrap(); assert_eq!(txn.req.cmd, 0xb000_0000); assert_eq!(txn.req.data, b""); txn.respond_success(); } #[test] fn test_uc_to_soc_error_state() { // This test requires strict control over timing #![cfg_attr(any(feature = "fpga_realtime", feature = "fpga_subsystem"), ignore)] let mut model = start_driver_test(&firmware::driver_tests::MAILBOX_DRIVER_NEGATIVE_TESTS).unwrap(); let txn = model.wait_for_mailbox_receive().unwrap(); let cmd = txn.req.cmd; // Test the receiver can't change the command register when the FSM is in Exec state. assert!(model.soc_mbox().cmd().read() == cmd); model.soc_mbox().cmd().write(|_| cmd + 1); assert!(model.soc_mbox().cmd().read() == cmd); // Check we can't release the lock on the receiver side. model.soc_mbox().execute().write(|w| w.execute(false)); assert!(model.soc_mbox().status().read().mbox_fsm_ps().mbox_error()); // Try to respond... model .soc_mbox() .status() .write(|w| w.status(|_| MboxStatusE::DataReady)); // But we're still in the error state assert!(model.soc_mbox().status().read().mbox_fsm_ps().mbox_error()); // Wait for the test-case to force unlock the mailbox model.step_until(|m| m.soc_mbox().status().read().mbox_fsm_ps().mbox_idle()); let _txn = model.wait_for_mailbox_receive().unwrap(); model.soc_mbox().execute().write(|w| w.execute(true)); assert!(model.soc_mbox().status().read().mbox_fsm_ps().mbox_error()); // Wait for the test-case to force unlock the mailbox model.step_until(|m| m.soc_mbox().status().read().mbox_fsm_ps().mbox_idle()); } #[test] fn test_pcrbank() { run_driver_test(&firmware::driver_tests::PCRBANK); } #[test] fn test_preconditioned_keys() { run_driver_test(&firmware::driver_tests::PRECONDITIONED_KEYS); } #[test] fn test_sha1() { run_driver_test(&firmware::driver_tests::SHA1); } #[test] fn test_sha256() { run_driver_test(&firmware::driver_tests::SHA256); } #[test] fn test_sha384() { run_driver_test(&firmware::driver_tests::SHA384); } #[test] fn test_sha512() { run_driver_test(&firmware::driver_tests::SHA512); } #[test] fn test_sha2_512_384acc() { run_driver_test(&firmware::driver_tests::SHA2_512_384ACC); } #[test] fn test_sha3() { run_driver_test(&firmware::driver_tests::SHA3); } #[test] fn test_status_reporter() { run_driver_test(&firmware::driver_tests::STATUS_REPORTER); } #[test] fn test_lms_24() { run_driver_test(&firmware::driver_tests::TEST_LMS_24); } #[test] fn test_lms_32() { run_driver_test(&firmware::driver_tests::TEST_LMS_32); } #[test] fn test_negative_lms() { run_driver_test(&firmware::driver_tests::TEST_NEGATIVE_LMS); } // Return a series of nibbles that won't fail health tests. // Used for testing the CSRNG's "success paths". fn trng_nibbles() -> impl Iterator<Item = u8> + Clone { // reversed form of // https://github.com/chipsalliance/caliptra-rtl/blob/fa91d66f30223899403f4e65a6f697a6f9100fd1/src/csrng/tb/csrng_tb.sv#L461 // cycled infintely to provide enough entropy bits for FIPS boot-time health checks const TRNG_ENTROPY: &str = "749ED7B4E3DE4E72D5CF367FD9D137113493B80AAA65CD17ABEBCE4FB4E8150105CC347E06539656786DA75F56B36F33"; TRNG_ENTROPY .chars() .map(|b| b.to_digit(16).expect("bad nibble digit") as u8) .cycle() } // Helper function to run CSRNG test binaries with specific entropy nibbles. fn test_csrng_with_nibbles( fwid: &FwId<'static>, itrng_nibbles: Box<dyn Iterator<Item = u8> + Send>, ) { let rom = caliptra_builder::build_firmware_rom(fwid).unwrap(); let mut model = caliptra_hw_model::new( InitParams { rom: &rom, itrng_nibbles, ..default_init_params() }, BootParams::default(), ) .unwrap(); model.step_until_exit_success().unwrap(); } #[test] #[cfg_attr( all( any( feature = "verilator", feature = "fpga_realtime", feature = "fpga_subsystem" ), not(feature = "itrng") ), ignore )] fn test_csrng() { test_csrng_with_nibbles(&firmware::driver_tests::CSRNG, Box::new(trng_nibbles())); } #[test] #[cfg_attr( all( any( feature = "verilator", feature = "fpga_realtime", feature = "fpga_subsystem" ), not(feature = "itrng") ), ignore )] fn test_csrng2() { test_csrng_with_nibbles(&firmware::driver_tests::CSRNG2, Box::new(trng_nibbles())); } #[test] #[cfg_attr( all( any( feature = "verilator", feature = "fpga_realtime", feature = "fpga_subsystem" ), not(feature = "itrng") ), ignore )] fn test_csrng_repetition_count() { // Tests for Repetition Count Test (RCT). fn test_repcnt_finite_repeats( test_fwid: &FwId<'static>, repeat: usize, soc_repcnt_threshold: Option<CptraItrngEntropyConfig1WriteVal>, ) { let rom = caliptra_builder::build_firmware_rom(test_fwid).unwrap(); let itrng_nibbles = Box::new({ // The boot-time health testing requires two consecutive windows of 2048-bits to // pass or fail health tests. So let's set up our windows to begin with the // repeated bits followed by known good entropy bits. const NUM_TEST_WINDOW_NIBBLES: usize = 2048 / 4; let num_good_entropy_nibbles = NUM_TEST_WINDOW_NIBBLES.saturating_sub(repeat + 2); iter::repeat(0b1111) .take(repeat) .chain(iter::once(0b0000)) // Break repetition .chain(trng_nibbles().take(num_good_entropy_nibbles)) .chain(iter::once(0b0000)) // Break repetition .cycle() }); let mut model = caliptra_hw_model::new( InitParams { rom: &rom, itrng_nibbles, ..default_init_params() }, BootParams { initial_repcnt_thresh_reg: soc_repcnt_threshold, ..Default::default() }, ) .unwrap(); model.step_until_exit_success().unwrap(); } // The following tests assumes the CSRNG driver will use this default threshold value. const THRESHOLD: usize = 41; const PASS: &FwId = &firmware::driver_tests::CSRNG_PASS_HEALTH_TESTS; const FAIL: &FwId = &firmware::driver_tests::CSRNG_FAIL_REPCNT_TESTS; // Bits that repeat up to (but excluding) the threshold times should PASS the RCT. test_repcnt_finite_repeats(PASS, THRESHOLD - 1, None); // Bits that repeat at least threshold times should FAIL the RCT. test_repcnt_finite_repeats(FAIL, THRESHOLD, None); // If at least one RNG wire has a stuck bit, RCT should fail. test_csrng_with_nibbles(FAIL, Box::new(iter::repeat(0b1111))); test_csrng_with_nibbles(FAIL, Box::new(iter::repeat(0b0000))); test_csrng_with_nibbles( FAIL, Box::new({ // The third bit is stuck at zero. [0b1011, 0b1010, 0b1000, 0b0000].into_iter().cycle() }), ); { // Test finite repeats again, but this time, exercise the logic to read and set thresholds from // SoC registers. const THRESHOLD: usize = 20; let soc_repcnt_threshold = Some( CptraItrngEntropyConfig1WriteVal::from(CptraItrngEntropyConfig1::RESET_VAL) .repetition_count(THRESHOLD as u32), ); test_repcnt_finite_repeats(PASS, THRESHOLD - 1, soc_repcnt_threshold); test_repcnt_finite_repeats(FAIL, THRESHOLD, soc_repcnt_threshold); } } #[test] #[cfg_attr( all( any( feature = "verilator", feature = "fpga_realtime", feature = "fpga_subsystem" ), not(feature = "itrng") ), ignore )] fn test_csrng_adaptive_proportion() { // Tests for Adaptive Proportion health check. // Assumes the CSRNG configures the adaptive proportion's LO and HI // thresholds to 25% and 75% of the FIPS health window size, i.e., // 512 and 1536 respectively for a 2048 bit window size. // The adaptive proportion test will pass if the number of 1's in a 2048 bit window is in the // range [512, 1536]. Note, inclusive bounds const PASS: &FwId = &firmware::driver_tests::CSRNG_PASS_HEALTH_TESTS; // 512 ones; 1536 zeros - should pass inclusive LO threshold. test_csrng_with_nibbles( PASS, Box::new({ const WINDOW: [u8; 512] = *include_bytes!("test_data/csrng/512_ones_1536_zeros"); // Boot-time health checks require testing two 2048 bit windows. WINDOW.into_iter().chain(WINDOW) }), ); // 1536 ones; 512 zeros - should pass inclusive HI threshold. test_csrng_with_nibbles( PASS, Box::new({
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/fuzz/src/sha256.rs
drivers/fuzz/src/sha256.rs
// Licensed under the Apache-2.0 license use caliptra_drivers::{Array4x8, CaliptraResult, Sha256Alg, Sha256DigestOp}; use std::marker::PhantomData; use sha2::Digest; #[derive(Default)] pub struct Sha256SoftwareDriver {} pub struct Sha256DigestOpSw<'a> { driver: PhantomData<&'a mut Sha256SoftwareDriver>, digest: sha2::Sha256, } impl<'a> Sha256DigestOp<'a> for Sha256DigestOpSw<'a> { fn update(&mut self, data: &[u8]) -> CaliptraResult<()> { self.digest.update(data); Ok(()) } fn finalize(self, digest: &mut Array4x8) -> CaliptraResult<()> { let result = self.digest.finalize(); *digest = Array4x8::from(<[u8; 32]>::try_from(result.as_slice()).unwrap()); Ok(()) } } impl Sha256Alg for Sha256SoftwareDriver { type DigestOp<'a> = Sha256DigestOpSw<'a>; fn digest(&mut self, buf: &[u8]) -> CaliptraResult<Array4x8> { let result = sha2::Sha256::digest(buf); Ok(Array4x8::from(<[u8; 32]>::try_from(result).unwrap())) } fn digest_init(&mut self) -> CaliptraResult<Self::DigestOp<'_>> { Ok(Sha256DigestOpSw { driver: PhantomData::default(), digest: sha2::Sha256::new(), }) } } impl Sha256SoftwareDriver { pub fn new() -> Self { Self {} } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/fuzz/src/fuzz_target_lms.rs
drivers/fuzz/src/fuzz_target_lms.rs
// Licensed under the Apache-2.0 license #![cfg_attr(feature = "libfuzzer-sys", no_main)] #[cfg(all(not(feature = "libfuzzer-sys"), not(feature = "afl")))] compile_error!("Either feature \"libfuzzer-sys\" or \"afl\" must be enabled!"); #[cfg(feature = "libfuzzer-sys")] use libfuzzer_sys::fuzz_target; #[cfg(feature = "afl")] use afl::fuzz; #[cfg(not(feature = "struct-aware"))] use std::mem::size_of; #[cfg(not(feature = "struct-aware"))] use zerocopy::FromBytes; use caliptra_drivers::Lms; mod sha256; use sha256::Sha256SoftwareDriver; // For consistency with the ROM, use its type definitions use caliptra_image_types::{ImageLmsPublicKey, ImageLmsSignature}; #[cfg(feature = "struct-aware")] #[derive(arbitrary::Arbitrary, Debug)] struct StructuredInput<'a> { pub_key: ImageLmsPublicKey, sig: ImageLmsSignature, input: &'a [u8], } #[cfg(feature = "struct-aware")] fn harness_structured(args: StructuredInput) { let _result = Lms::default().verify_lms_signature_generic( &mut Sha256SoftwareDriver::new(), args.input, &args.pub_key, &args.sig, ); } #[cfg(not(feature = "struct-aware"))] fn harness_unstructured(data: &[u8]) { if data.len() < (size_of::<ImageLmsPublicKey>() + size_of::<ImageLmsSignature>()) { return; } // The corpus is seeded with (pub_key, sig, input), so parse the data in this order let mut offset = 0; let pub_key = ImageLmsPublicKey::read_from_prefix(data).unwrap(); offset += size_of::<ImageLmsPublicKey>(); let sig = ImageLmsSignature::read_from_prefix(&data[offset..]).unwrap(); offset += size_of::<ImageLmsSignature>(); let input = &data[offset..]; let _result = Lms::default().verify_lms_signature_generic( &mut Sha256SoftwareDriver::new(), input, &pub_key, &sig, ); } // cargo-fuzz target #[cfg(all(feature = "libfuzzer-sys", not(feature = "struct-aware")))] fuzz_target!(|data: &[u8]| { harness_unstructured(data); }); #[cfg(all(feature = "libfuzzer-sys", feature = "struct-aware"))] fuzz_target!(|data: StructuredInput| { harness_structured(data); }); // cargo-afl target #[cfg(all(feature = "afl", not(feature = "struct-aware")))] fn main() { fuzz!(|data: &[u8]| { harness_unstructured(data); }); } #[cfg(all(feature = "afl", feature = "struct-aware"))] fn main() { fuzz!(|data: StructuredInput| { harness_structured(data); }); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/build.rs
drivers/test-fw/build.rs
/*++ Licensed under the Apache-2.0 license. File Name: build.rs Abstract: Cargo build file --*/ fn main() { if cfg!(feature = "riscv") { println!("cargo:rerun-if-changed=../../test-harness/scripts/rom.ld"); println!("cargo:rustc-link-arg=-Ttest-harness/scripts/rom.ld"); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/scripts/vector_gen/src/mdk.rs
drivers/test-fw/scripts/vector_gen/src/mdk.rs
/*++ Licensed under the Apache-2.0 license. File Name: mdk.rs Abstract: A vector generator for an MDK. --*/ use openssl::{ hash::MessageDigest, pkey::PKey, sign::Signer, symm::{Cipher, Crypter, Mode}, }; pub const PLAINTEXT_MEK: [u8; 64] = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, ]; pub struct Mdk { pub input_key: [u8; 64], pub mdk: [u8; 64], pub encrypted_mek: [u8; 64], } impl Default for Mdk { fn default() -> Self { let mut input_key = [0; 64]; hmac(&[0; 64], &[0], &mut input_key); let mut mdk = [0; 64]; kdf(&input_key, b"OCP_LOCK_MDK", None, &mut mdk); let aes_key = &mdk[0..32]; let cipher = Cipher::aes_256_ecb(); let mut crypter = Crypter::new(cipher, Mode::Encrypt, aes_key, None).unwrap(); crypter.pad(false); // crypter update requires input size + block size. let mut encrypted_data_buf = [0u8; 64 + 16]; let mut count = crypter .update(&PLAINTEXT_MEK, &mut encrypted_data_buf) .unwrap(); count += crypter.finalize(&mut encrypted_data_buf[count..]).unwrap(); let mut encrypted_data = [0u8; 64]; encrypted_data.copy_from_slice(&encrypted_data_buf[..count]); Self { input_key, mdk, encrypted_mek: encrypted_data, } } } fn hmac(key: &[u8], msg: &[u8], tag: &mut [u8]) { let pkey = PKey::hmac(key).unwrap(); let mut signer = Signer::new(MessageDigest::sha512(), &pkey).unwrap(); signer.update(msg).unwrap(); signer.sign(tag).unwrap(); } fn kdf(key: &[u8], label: &[u8], context: Option<&[u8]>, output: &mut [u8; 64]) { let ctr_be = 1_u32.to_be_bytes(); let mut msg = Vec::<u8>::default(); msg.extend_from_slice(&ctr_be); msg.extend_from_slice(label); if let Some(context) = context { msg.push(0x00); msg.extend_from_slice(context); } hmac(key, &msg, output); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/scripts/vector_gen/src/preconditioned_key_extract_gen.rs
drivers/test-fw/scripts/vector_gen/src/preconditioned_key_extract_gen.rs
/*++ Licensed under the Apache-2.0 license. File Name: preconditioned_key_extract_gen.rs Abstract: A vector generator for the preconditioned_key_extract function. https://chipsalliance.github.io/Caliptra/ocp-lock/specification/HEAD/#fig:preconditioned-key-extract --*/ use crate::utils::*; use openssl::symm::{encrypt, Cipher}; pub struct PreconditionedKeyExtractVector { pub input_key: Vec<u8>, pub input_salt: Vec<u8>, pub input_kdf_label: Vec<u8>, pub checksum: [u8; 16], // AES-ECB-Encrypt(input_salt[0..32], 0x0000...) pub kdf_output: [u8; 64], // KDF(input_key, input_kdf_label, checksum) pub output_key: [u8; 64], // HMAC(input_salt, kdf_output) pub fingerprint: [u8; 16], // AES-ECB-Encrypt(output_key[0..32], 0x0000...) } impl Default for PreconditionedKeyExtractVector { fn default() -> PreconditionedKeyExtractVector { PreconditionedKeyExtractVector { input_key: Vec::new(), input_salt: Vec::new(), input_kdf_label: Vec::new(), checksum: [0; 16], kdf_output: [0; 64], output_key: [0; 64], fingerprint: [0; 16], } } } pub fn gen_vector( input_key_length: usize, salt_length: usize, kdf_length: usize, ) -> PreconditionedKeyExtractVector { let cipher = Cipher::aes_256_ecb(); let mut vec = PreconditionedKeyExtractVector::default(); vec.input_key.resize(input_key_length, 0); vec.input_salt.resize(salt_length, 0); vec.input_kdf_label.resize(kdf_length, 0); rand_bytes(&mut vec.input_key); rand_bytes(&mut vec.input_salt); rand_bytes(&mut vec.input_kdf_label); let mut input_key = vec![0; 64]; let mut salt = vec![0; 64]; hmac(&vec.input_key, &[0], &mut input_key, Digest::SHA512); hmac(&vec.input_salt, &[0], &mut salt, Digest::SHA512); let aes_key = &salt[0..32]; let checksum = encrypt(cipher, aes_key, None, &[0u8; 16]).unwrap(); vec.checksum.copy_from_slice(&checksum[0..16]); kdf( &input_key, &vec.input_kdf_label, Some(&vec.checksum), &mut vec.kdf_output, Digest::SHA512, ); hmac(&salt, &vec.kdf_output, &mut vec.output_key, Digest::SHA512); let aes_key = &vec.output_key[0..32]; let fingerprint = encrypt(cipher, aes_key, None, &[0u8; 16]).unwrap(); vec.fingerprint.copy_from_slice(&fingerprint[0..16]); vec }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/scripts/vector_gen/src/hmac384_kdf_vector_gen.rs
drivers/test-fw/scripts/vector_gen/src/hmac384_kdf_vector_gen.rs
/*++ Licensed under the Apache-2.0 license. File Name: hmac384_kdf_vector_gen.rs Abstract: A vector generator for an SP 800-108-compliant KDF. --*/ use crate::utils::*; use caliptra_test::crypto::derive_ecdsa_keypair; pub struct Hmac384KdfVector { pub key_0: [u8; 48], pub msg_0: [u8; 48], pub kdf_key: [u8; 48], // HMAC(key=key_0, msg=msg_0) pub label: Vec<u8>, pub context: Vec<u8>, pub kdf_out: [u8; 48], // KDF(key=kdf_key, label=label, context=context) pub out_pub_x: [u8; 48], // ECDSA_KEYGEN(kdf_out).pub.x pub out_pub_y: [u8; 48], // ECDSA_KEYGEN(kdf_out).pub.y } impl Default for Hmac384KdfVector { fn default() -> Hmac384KdfVector { Hmac384KdfVector { key_0: [0; 48], msg_0: [0; 48], kdf_key: [0; 48], label: Vec::<u8>::default(), context: Vec::<u8>::default(), kdf_out: [0; 48], out_pub_x: [0; 48], out_pub_y: [0; 48], } } } pub fn gen_vector(label_len: usize, context_len: usize) -> Hmac384KdfVector { let mut vec = Hmac384KdfVector::default(); vec.label.resize(label_len, 0); rand_bytes(&mut vec.key_0); rand_bytes(&mut vec.msg_0); rand_bytes(&mut vec.label[..]); let context = if context_len == 0 { None } else { vec.context.resize(context_len, 0); rand_bytes(&mut vec.context[..]); Some(&vec.context[..]) }; hmac(&vec.key_0, &vec.msg_0, &mut vec.kdf_key, Digest::SHA384); kdf( &vec.kdf_key, &vec.label[..], context, &mut vec.kdf_out, Digest::SHA384, ); (_, vec.out_pub_x, vec.out_pub_y) = derive_ecdsa_keypair(&vec.kdf_out); vec }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/scripts/vector_gen/src/hmac384_vector_gen.rs
drivers/test-fw/scripts/vector_gen/src/hmac384_vector_gen.rs
/*++ Licensed under the Apache-2.0 license. File Name: hmac384_vector_gen.rs Abstract: A vector generator for HMAC operations. --*/ use caliptra_test::crypto::derive_ecdsa_keypair; use crate::utils::*; pub struct Hmac384Vector { pub seed: [u8; 48], pub data: Vec<u8>, // key = ECDSA_KEYGEN(seed).priv // out = HMAC(key, data) pub out_pub_x: [u8; 48], // ECDSA_KEYGEN(out).pub.x pub out_pub_y: [u8; 48], // ECDSA_KEYGEN(out).pub.y } impl Default for Hmac384Vector { fn default() -> Hmac384Vector { Hmac384Vector { seed: [0; 48], data: Vec::<u8>::default(), out_pub_x: [0; 48], out_pub_y: [0; 48], } } } pub fn gen_vector(data_len: usize) -> Hmac384Vector { let mut vec = Hmac384Vector::default(); vec.data.resize(data_len, 0); rand_bytes(&mut vec.seed); rand_bytes(&mut vec.data[..]); let (key, _, _) = derive_ecdsa_keypair(&vec.seed); let mut out_0 = [0u8; 48]; hmac(&key, &vec.data[..], &mut out_0, Digest::SHA384); (_, vec.out_pub_x, vec.out_pub_y) = derive_ecdsa_keypair(&out_0); vec }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/scripts/vector_gen/src/utils.rs
drivers/test-fw/scripts/vector_gen/src/utils.rs
// Licensed under the Apache-2.0 license use openssl::{hash::MessageDigest, pkey::PKey, sign::Signer}; pub(crate) enum Digest { SHA384, SHA512, } pub(crate) fn rand_bytes(buf: &mut [u8]) { openssl::rand::rand_bytes(buf).unwrap() } pub(crate) fn hmac(key: &[u8], msg: &[u8], tag: &mut [u8], digest_type: Digest) { let pkey = PKey::hmac(key).unwrap(); let digest = match digest_type { Digest::SHA384 => MessageDigest::sha384(), Digest::SHA512 => MessageDigest::sha512(), }; let mut signer = Signer::new(digest, &pkey).unwrap(); signer.update(msg).unwrap(); signer.sign(tag).unwrap(); } pub(crate) fn kdf<const N: usize>( key: &[u8], label: &[u8], context: Option<&[u8]>, output: &mut [u8; N], digest_type: Digest, ) { let ctr_be = 1_u32.to_be_bytes(); let mut msg = Vec::<u8>::default(); msg.extend_from_slice(&ctr_be); msg.extend_from_slice(label); if let Some(context) = context { msg.push(0x00); msg.extend_from_slice(context); } hmac(key, &msg, output, digest_type); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/scripts/vector_gen/src/main.rs
drivers/test-fw/scripts/vector_gen/src/main.rs
/*++ Licensed under the Apache-2.0 license. File Name: main.rs Abstract: Driver for test vector generators. --*/ mod hmac384_kdf_vector_gen; mod hmac384_vector_gen; mod mdk; mod preconditioned_key_extract_gen; mod utils; use crate::hmac384_kdf_vector_gen::Hmac384KdfVector; use crate::hmac384_vector_gen::Hmac384Vector; use crate::mdk::Mdk; use crate::preconditioned_key_extract_gen::PreconditionedKeyExtractVector; fn hex_arr(bytes: &[u8]) -> String { format!( "[{}]", bytes .iter() .map(|b| format!("0x{:02x}", b)) .collect::<Vec<String>>() .join(", ") ) } fn main() { let vec_d8: Hmac384Vector = hmac384_vector_gen::gen_vector(8); println!("hmac384 data_len=8"); println!(" let seed = {};", hex_arr(&vec_d8.seed)); println!(" let data = {};", hex_arr(&vec_d8.data)); println!(" let out_pub_x = {};", hex_arr(&vec_d8.out_pub_x)); println!(" let out_pub_y = {};", hex_arr(&vec_d8.out_pub_y)); println!(); let vec_d28: Hmac384Vector = hmac384_vector_gen::gen_vector(28); println!("hmac384 data_len=28"); println!(" let seed = {};", hex_arr(&vec_d28.seed)); println!(" let data = {};", hex_arr(&vec_d28.data)); println!(" let out_pub_x = {};", hex_arr(&vec_d28.out_pub_x)); println!(" let out_pub_y = {};", hex_arr(&vec_d28.out_pub_y)); println!(); let vec_d48: Hmac384Vector = hmac384_vector_gen::gen_vector(48); println!("hmac384 data_len=48"); println!(" let seed = {};", hex_arr(&vec_d48.seed)); println!(" let data = {};", hex_arr(&vec_d48.data)); println!(" let out_pub_x = {};", hex_arr(&vec_d48.out_pub_x)); println!(" let out_pub_y = {};", hex_arr(&vec_d48.out_pub_y)); println!(); let vec_kdf_c48: Hmac384KdfVector = hmac384_kdf_vector_gen::gen_vector(4, 48); println!("hmac384_kdf context_len=48"); println!(" let key_0 = {};", hex_arr(&vec_kdf_c48.key_0)); println!(" let msg_0 = {};", hex_arr(&vec_kdf_c48.msg_0)); println!(" let label = {};", hex_arr(&vec_kdf_c48.label)); println!(" let context = {};", hex_arr(&vec_kdf_c48.context)); println!(" let out_pub_x = {};", hex_arr(&vec_kdf_c48.out_pub_x)); println!(" let out_pub_y = {};", hex_arr(&vec_kdf_c48.out_pub_y)); println!(); let vec_kdf_c0: Hmac384KdfVector = hmac384_kdf_vector_gen::gen_vector(4, 0); println!("hmac384_kdf context_len=0"); println!(" let key_0 = {};", hex_arr(&vec_kdf_c0.key_0)); println!(" let msg_0 = {};", hex_arr(&vec_kdf_c0.msg_0)); println!(" let label = {};", hex_arr(&vec_kdf_c0.label)); println!(" let out_pub_x = {};", hex_arr(&vec_kdf_c0.out_pub_x)); println!(" let out_pub_y = {};", hex_arr(&vec_kdf_c0.out_pub_y)); println!(); let mdk = Mdk::default(); println!("mdk"); println!(" let input_key = {};", hex_arr(&mdk.input_key)); println!(" let mdk = {};", hex_arr(&mdk.mdk)); println!(" let mek = {};", hex_arr(&mdk::PLAINTEXT_MEK)); println!(" let encrypted_mek = {};", hex_arr(&mdk.encrypted_mek)); let vec: PreconditionedKeyExtractVector = preconditioned_key_extract_gen::gen_vector(48, 48, 32); println!("preconditioned_key_extract input_key_length=48"); println!(" let input_key = {};", hex_arr(&vec.input_key)); println!(" let salt = {};", hex_arr(&vec.input_salt)); println!(" let kdf_label = {};", hex_arr(&vec.input_kdf_label)); println!(" let checksum = {};", hex_arr(&vec.checksum)); println!(" let kdf_output = {};", hex_arr(&vec.kdf_output)); println!(" let output_key = {};", hex_arr(&vec.output_key)); println!(" let fingerprint = {};", hex_arr(&vec.fingerprint)); println!(); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/lib.rs
drivers/test-fw/src/lib.rs
// Licensed under the Apache-2.0 license #![no_std] use caliptra_drivers::{ Aes, Array4x16, DeobfuscationEngine, Dma, Ecc384PubKey, Hmac, HmacData, HmacKey, HmacMode, KeyId, KeyReadArgs, KeyUsage, KeyVault, KeyWriteArgs, SocIfc, Trng, }; use caliptra_kat::CaliptraResult; use caliptra_registers::{ aes::AesReg, aes_clp::AesClpReg, csrng::CsrngReg, doe::DoeReg, entropy_src::EntropySrcReg, hmac::HmacReg, kv::KvReg, soc_ifc::SocIfcReg, soc_ifc_trng::SocIfcTrngReg, }; /// Code shared between the caliptra-drivers integration_test.rs (running on the /// host) and the test binaries (running inside the hw-model). use core::fmt::Debug; use itertools::Itertools; use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout}; pub const DOE_TEST_IV: [u32; 4] = [0xc6b407a2, 0xd119a37d, 0xb7a5bdeb, 0x26214aed]; pub const DOE_TEST_HMAC_KEY: [u32; 12] = [ 0x15f4a700, 0xd79bd4e1, 0x0f92b714, 0x3a38d570, 0x7cf2ebb4, 0xab47cc6e, 0xa4827e80, 0x32e6d3b4, 0xc6879874, 0x0aa49a0f, 0x4e740e9c, 0x2c9f9aad, ]; /// Constant for OCP LOCK tests. pub const ENCRYPTED_MEK: [u8; 64] = [ 0xa5, 0x30, 0x8a, 0x37, 0xfa, 0x5d, 0xdd, 0x82, 0xee, 0x36, 0xf1, 0x7f, 0x0a, 0x96, 0x0a, 0xc2, 0xbc, 0xe6, 0xde, 0x51, 0xdc, 0xca, 0xa8, 0x69, 0x8e, 0x6b, 0x9b, 0x36, 0xf3, 0xe5, 0x75, 0xfd, 0x55, 0x87, 0x81, 0x23, 0x49, 0x15, 0x4a, 0x12, 0x82, 0xd9, 0x03, 0x01, 0xe6, 0x34, 0xdb, 0xc1, 0x26, 0x5e, 0x85, 0x81, 0x5e, 0x38, 0xc6, 0x90, 0xf9, 0x08, 0xe2, 0x2a, 0x18, 0x37, 0x6e, 0x6f, ]; /// Constant for OCP LOCK tests. pub const PLAINTEXT_MEK: [u8; 64] = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, ]; pub const OCP_LOCK_WARM_RESET_MAGIC_BOOT_STATUS: u32 = 0xFEEB; #[derive(IntoBytes, KnownLayout, Immutable, Clone, Copy, Default, Eq, PartialEq, FromBytes)] #[repr(C)] pub struct DoeTestResults { /// HMAC result of the UDS as key, and b"Hello world!" as data. pub hmac_uds_as_key_out_pub: Ecc384PubKey, /// HMAC result of HMAC_KEY as key, and UDS as data. pub hmac_uds_as_data_out_pub: Ecc384PubKey, // HMAC result of of the field entropy (including padding) as key, and // b"Hello world" as data. pub hmac_field_entropy_as_key_out_pub: Ecc384PubKey, /// HMAC result of HMAC_KEY as key, and field entropy (excluding padding) as /// data. pub hmac_field_entropy_as_data_out_pub: Ecc384PubKey, } impl Debug for DoeTestResults { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("DoeTestResults") .field("hmac_uds_as_key_out_pub", &self.hmac_uds_as_key_out_pub) .field("hmac_uds_as_data_out_pub", &self.hmac_uds_as_data_out_pub) .field( "hmac_field_entropy_as_key_out_pub", &self.hmac_field_entropy_as_key_out_pub, ) .field( "hmac_field_entropy_as_data_out_pub", &self.hmac_field_entropy_as_data_out_pub, ) .finish() } } pub struct TestRegisters { pub soc: SocIfc, pub hmac: Hmac, pub aes: Aes, pub trng: Trng, pub dma: Dma, pub doe: DeobfuscationEngine, pub kv: KeyVault, } impl Default for TestRegisters { fn default() -> Self { let soc_ifc = unsafe { SocIfcReg::new() }; let soc = SocIfc::new(soc_ifc); let hmac = unsafe { Hmac::new(HmacReg::new()) }; let aes = unsafe { Aes::new(AesReg::new(), AesClpReg::new()) }; let trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let dma = Dma::default(); let doe = unsafe { DeobfuscationEngine::new(DoeReg::new()) }; let kv = unsafe { KeyVault::new(KvReg::new()) }; Self { soc, hmac, aes, trng, dma, doe, kv, } } } // OCP LOCK helpers /// Checks KV rules enforced by OCP LOCK hardware. pub fn hmac_kv_sequence_check<T: Iterator<Item = u8> + Clone>( input_key_ids: T, output_key_ids: T, populate_kv: bool, check_result: impl Fn(CaliptraResult<()>), ) { let mut test_regs = TestRegisters::default(); for (input_kv, output_kv) in input_key_ids.cartesian_product(output_key_ids) { let input = KeyId::try_from(input_kv).unwrap(); let output = KeyId::try_from(output_kv).unwrap(); let kv_filter_set = [KeyId::KeyId16, KeyId::KeyId23]; // Only populate the KV in the first test. if populate_kv { populate_slot( &mut test_regs.hmac, &mut test_regs.trng, input, KeyUsage::default().set_hmac_key_en(), ) .unwrap(); } // Skip overwriting MDK and MEK. They have special rules exercised elsewhere. if kv_filter_set.contains(&input) || kv_filter_set.contains(&output) { continue; } check_result(hmac_helper( input, output, &mut test_regs.hmac, &mut test_regs.trng, )); } } /// Populates a KV slot with a known constant. pub fn populate_slot( hmac: &mut Hmac, trng: &mut Trng, slot: KeyId, usage: KeyUsage, ) -> CaliptraResult<()> { hmac.hmac( HmacKey::Array4x16(&Array4x16::default()), HmacData::from(&[0]), trng, KeyWriteArgs::new(slot, usage).into(), HmacMode::Hmac512, ) } /// Performs a HMAC from a KV to another KV. pub fn hmac_helper( input: KeyId, output: KeyId, hmac: &mut Hmac, trng: &mut Trng, ) -> CaliptraResult<()> { hmac.hmac( HmacKey::Key(KeyReadArgs::new(input)), HmacData::from(&[0]), trng, KeyWriteArgs::new( output, KeyUsage::default().set_aes_key_en().set_hmac_key_en(), ) .into(), HmacMode::Hmac512, ) } /// Verifies the OCP LOCK KV release flow pub fn kv_release(test_regs: &mut TestRegisters) { let kv_release_size = test_regs.soc.ocp_lock_get_key_size(); // We expect the MCU TEST ROM to set the OCP LOCK key release size to 0x40. assert_eq!(0x40, kv_release_size); test_regs.dma.ocp_lock_key_vault_release(&test_regs.soc); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/mbox_send_txn_drop.rs
drivers/test-fw/src/bin/mbox_send_txn_drop.rs
// Licensed under the Apache-2.0 license //! A very simple program that uses the driver to send mailbox messages #![no_main] #![no_std] use caliptra_registers::mbox::MboxCsr; // Needed to bring in startup code #[allow(unused)] use caliptra_test_harness::{self, println}; use caliptra_drivers::{self, Mailbox}; #[panic_handler] pub fn panic(_info: &core::panic::PanicInfo) -> ! { let mbox = unsafe { MboxCsr::new() }; println!( "locked state is {} mailbox present state is {} is in error {}", mbox.regs().lock().read().lock(), mbox.regs().status().read().mbox_fsm_ps() as u32, mbox.regs().status().read().mbox_fsm_ps().mbox_error() as u32 ); loop {} } fn mbox_fsm_error() -> bool { let mbox = unsafe { MboxCsr::new() }; mbox.regs().status().read().mbox_fsm_ps().mbox_error() } #[no_mangle] extern "C" fn main() { let mut mbox = Mailbox::new(unsafe { MboxCsr::new() }); // Transition from execute to idle let mut txn = mbox.try_start_send_txn().unwrap(); txn.write_cmd(0).unwrap(); txn.write_dlen(1).unwrap(); txn.execute_request().unwrap(); drop(txn); assert_eq!(mbox_fsm_error(), false); // Transition from rdy_for_data to idle let mut txn = mbox.try_start_send_txn().unwrap(); txn.write_cmd(0).unwrap(); txn.write_dlen(1).unwrap(); drop(txn); assert_eq!(mbox_fsm_error(), false); // Transition from rdy_for_dlen to idle let mut txn = mbox.try_start_send_txn().unwrap(); txn.write_cmd(0).unwrap(); drop(txn); assert_eq!(mbox_fsm_error(), false); // Transition from rdy_for_cmd to idle let txn = mbox.try_start_send_txn().unwrap(); drop(txn); assert_eq!(mbox_fsm_error(), false); let _ = mbox.try_start_send_txn().unwrap(); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/preconditioned_keys_tests.rs
drivers/test-fw/src/bin/preconditioned_keys_tests.rs
// Licensed under the Apache-2.0 license #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::preconditioned_key::preconditioned_key_extract; use caliptra_drivers::{ Aes, AesKey, AesOperation, Array4x12, Array4x16, Hmac, HmacData, HmacKey, HmacMode, HmacTag, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, Trng, }; use caliptra_kat::CaliptraError; use caliptra_registers::aes::AesReg; use caliptra_registers::aes_clp::AesClpReg; use caliptra_registers::csrng::CsrngReg; use caliptra_registers::entropy_src::EntropySrcReg; use caliptra_registers::hmac::HmacReg; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_registers::soc_ifc_trng::SocIfcTrngReg; use caliptra_test_harness::test_suite; const OUTPUT_KEY_ID: KeyId = KeyId::KeyId15; const SALT_KEY_ID: KeyId = KeyId::KeyId9; const INPUT_KEY_ID: KeyId = KeyId::KeyId13; fn test_preconditioned_key_combo( key: HmacKey, salt: HmacKey, label: &[u8], result: &[u8], key_in_kv: bool, salt_in_kv: bool, ) { let mut aes = unsafe { Aes::new(AesReg::new(), AesClpReg::new()) }; let mut hmac = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let mut entropy_gen = || trng.generate4(); CfiCounter::reset(&mut entropy_gen); let input_key_arr = get_populated_kv_slot_value(&mut hmac, &mut trng, key); let input_key = if key_in_kv { let input_key = HmacKey::Key(KeyReadArgs::new(INPUT_KEY_ID)); populate_kv_slot(&mut hmac, &mut trng, INPUT_KEY_ID, key); input_key } else { HmacKey::Array4x16(&input_key_arr) }; let salt_key_arr = get_populated_kv_slot_value(&mut hmac, &mut trng, salt); let salt_key = if salt_in_kv { let salt_key = HmacKey::Key(KeyReadArgs::new(SALT_KEY_ID)); populate_kv_slot(&mut hmac, &mut trng, SALT_KEY_ID, salt); salt_key } else { HmacKey::Array4x16(&salt_key_arr) }; let output_key = HmacTag::Key(KeyWriteArgs::new( OUTPUT_KEY_ID, KeyUsage::default().set_hmac_key_en().set_aes_key_en(), )); preconditioned_key_extract( input_key, output_key, label, salt_key, &mut trng, &mut hmac, &mut aes, ) .unwrap(); let fingerprint = get_kv_slot_fingerprint(&mut aes, OUTPUT_KEY_ID); assert_eq!(fingerprint, result); } fn test_preconditioned_key(key: HmacKey, salt: HmacKey, label: &[u8], result: &[u8]) { test_preconditioned_key_combo(key, salt, label, result, true, true); test_preconditioned_key_combo(key, salt, label, result, true, false); test_preconditioned_key_combo(key, salt, label, result, false, true); test_preconditioned_key_combo(key, salt, label, result, false, false); } fn test_preconditioned_key_384_seed() { // Populated by [drivers/test-fw/scripts/vector_gen/src/preconditioned_key_extract_gen.rs]. let input_key_seed = Array4x12::from([ 0x6a, 0xf7, 0x86, 0x29, 0xa5, 0x7d, 0xb4, 0x76, 0xae, 0x6d, 0x05, 0x4e, 0x2b, 0xb9, 0xd5, 0x97, 0x14, 0x7d, 0x2b, 0xff, 0x19, 0x35, 0xd6, 0xa0, 0x58, 0x50, 0x2b, 0xa9, 0x2a, 0x95, 0xe0, 0x71, 0x75, 0x79, 0xfc, 0xe7, 0xd4, 0xe6, 0xbe, 0x4c, 0x35, 0x97, 0x65, 0x0d, 0xc7, 0x08, 0x89, 0x56, ]); let salt_seed = Array4x12::from([ 0x6f, 0x60, 0x19, 0x56, 0xe0, 0x22, 0x9a, 0xaf, 0xbe, 0x5f, 0x9d, 0x07, 0xe9, 0x9d, 0xbd, 0x0e, 0x16, 0x76, 0x74, 0x5c, 0x4c, 0x9c, 0x1e, 0xa9, 0xcd, 0xad, 0xe1, 0x4c, 0x5b, 0x7b, 0x25, 0x59, 0x71, 0xdf, 0xc8, 0xe1, 0x12, 0xa3, 0x00, 0xff, 0x26, 0x66, 0xdb, 0x27, 0x4d, 0x2d, 0x19, 0x5e, ]); const KDF_LABEL: &[u8] = &[ 0xcb, 0x92, 0x12, 0x26, 0x25, 0xb2, 0x69, 0x48, 0xba, 0x67, 0x6d, 0x2a, 0xeb, 0x5a, 0xcd, 0x26, 0x9d, 0xd1, 0x32, 0xbc, 0xb5, 0x37, 0x5f, 0x73, 0xcd, 0xe9, 0xff, 0xb7, 0x2d, 0x70, 0xef, 0x45, ]; const EXPECTED_RESULT: &[u8; 16] = &[ 0x1a, 0xaa, 0x29, 0xfc, 0xb8, 0xf5, 0x80, 0xd2, 0x14, 0xbd, 0x61, 0x78, 0xb1, 0xd7, 0xd2, 0xd8, ]; test_preconditioned_key( HmacKey::Array4x12(&input_key_seed), HmacKey::Array4x12(&salt_seed), KDF_LABEL, EXPECTED_RESULT, ); } fn test_preconditioned_key_512_seed() { // Populated by [drivers/test-fw/scripts/vector_gen/src/preconditioned_key_extract_gen.rs]. let input_key_seed = Array4x16::from([ 0x3b, 0xf0, 0x85, 0x0f, 0x8a, 0x54, 0x4a, 0x9e, 0x09, 0x11, 0x84, 0xb1, 0x2e, 0xe4, 0x02, 0x85, 0x2f, 0xc9, 0x3c, 0xc2, 0x1d, 0xb4, 0xd9, 0x84, 0x56, 0x9a, 0x74, 0xf9, 0x19, 0x13, 0xf0, 0xd6, 0x44, 0x7e, 0xe7, 0x15, 0x93, 0xfc, 0xb0, 0x53, 0xf6, 0xfe, 0x70, 0x69, 0x04, 0xd8, 0xd7, 0x2e, 0xf1, 0x41, 0x92, 0x03, 0x2c, 0xc9, 0x7d, 0x0a, 0x4d, 0x05, 0xc1, 0xd1, 0x06, 0x69, 0x7f, 0xd0, ]); let salt_seed = Array4x16::from([ 0x21, 0xfd, 0xf1, 0xdf, 0x10, 0x72, 0xee, 0xd0, 0x3e, 0xad, 0xc8, 0xe3, 0x55, 0x8b, 0x0f, 0x27, 0x6b, 0xa6, 0x66, 0x50, 0xef, 0x73, 0xa3, 0x51, 0x15, 0x7a, 0xfc, 0xd8, 0x64, 0xf8, 0x7b, 0xde, 0xb8, 0x4e, 0x4c, 0xc0, 0x02, 0xa7, 0xa3, 0x20, 0xe1, 0x4b, 0xac, 0x89, 0x08, 0x00, 0x2f, 0xc2, 0xdf, 0xd6, 0x57, 0x76, 0xf8, 0x92, 0x2c, 0xe5, 0x5a, 0xf2, 0x65, 0xd3, 0x82, 0xd4, 0x46, 0x90, ]); const KDF_LABEL: &[u8] = &[ 0xb7, 0x38, 0x58, 0x5f, 0x26, 0xf0, 0xf1, 0x47, 0x07, 0x6d, 0x91, 0x03, 0x3b, 0x17, 0x19, 0x48, 0xd1, 0x97, 0xa6, 0xba, 0x73, 0x9c, 0x7f, 0x19, 0xb7, 0xd6, 0x64, 0xf0, 0xd1, 0x21, 0x1f, 0x8a, ]; const EXPECTED_RESULT: &[u8; 16] = &[ 0xd4, 0x5a, 0x49, 0x3e, 0xcc, 0xb6, 0x73, 0x63, 0xde, 0x77, 0x2f, 0x31, 0xbe, 0xe8, 0xd1, 0xcc, ]; test_preconditioned_key( HmacKey::Array4x16(&input_key_seed), HmacKey::Array4x16(&salt_seed), KDF_LABEL, EXPECTED_RESULT, ); } fn test_preconditioned_key_arg_invariants() { let mut aes = unsafe { Aes::new(AesReg::new(), AesClpReg::new()) }; let mut hmac = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let mut entropy_gen = || trng.generate4(); CfiCounter::reset(&mut entropy_gen); // HmacTag MUST be a KV slot. assert_eq!( preconditioned_key_extract( HmacKey::Array4x16(&Array4x16::default()), HmacTag::Array4x12(&mut Array4x12::default()), &[0], HmacKey::Array4x16(&Array4x16::default()), &mut trng, &mut hmac, &mut aes, ), Err(CaliptraError::RUNTIME_DRIVER_PRECONDITIONED_KEY_INVALID_INPUT) ); // Salt MUST be `Array4x16`. assert_eq!( preconditioned_key_extract( HmacKey::Array4x16(&Array4x16::default()), HmacTag::Key(KeyWriteArgs::new( OUTPUT_KEY_ID, KeyUsage::default().set_hmac_key_en().set_aes_key_en(), )), &[0], HmacKey::Array4x12(&Array4x12::default()), &mut trng, &mut hmac, &mut aes, ), Err(CaliptraError::RUNTIME_DRIVER_PRECONDITIONED_KEY_INVALID_INPUT) ); } test_suite! { test_preconditioned_key_384_seed, test_preconditioned_key_512_seed, test_preconditioned_key_arg_invariants, } fn populate_kv_slot(hmac: &mut Hmac, trng: &mut Trng, key_id: KeyId, seed: HmacKey) { hmac.hmac( seed, HmacData::from(&[0]), trng, KeyWriteArgs::new( key_id, KeyUsage::default().set_hmac_key_en().set_aes_key_en(), ) .into(), HmacMode::Hmac512, ) .unwrap(); } fn get_populated_kv_slot_value(hmac: &mut Hmac, trng: &mut Trng, seed: HmacKey) -> Array4x16 { let mut tag: Array4x16 = Array4x16::default(); hmac.hmac( seed, HmacData::from(&[0]), trng, HmacTag::Array4x16(&mut tag), HmacMode::Hmac512, ) .unwrap(); tag } fn get_kv_slot_fingerprint(aes: &mut Aes, key_id: KeyId) -> [u8; 16] { let mut output = [0; 16]; aes.aes_256_ecb( AesKey::KV(KeyReadArgs::new(key_id)), AesOperation::Encrypt, &[0; 16], &mut output, ) .unwrap(); output }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/dma_aes_tests.rs
drivers/test-fw/src/bin/dma_aes_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: dma_sha384_tests.rs Abstract: File contains test cases for DMA SHA384 operations --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::sha2_512_384::Sha2DigestOpTrait; use caliptra_drivers::{ cprintln, Aes, AesGcmIv, AesKey, AesOperation, Array4x12, Dma, DmaReadTarget, DmaReadTransaction, LEArray4x8, Sha2_512_384, SocIfc, Trng, }; use caliptra_registers::aes::AesReg; use caliptra_registers::aes_clp::AesClpReg; use caliptra_registers::csrng::CsrngReg; use caliptra_registers::entropy_src::EntropySrcReg; use caliptra_registers::mcu_sram; use caliptra_registers::sha512::Sha512Reg; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_registers::soc_ifc_trng::SocIfcTrngReg; use caliptra_test_harness::test_suite; use zerocopy::IntoBytes; const MCU_SRAM_OFFSET: *mut u32 = mcu_sram::McuSram::PTR; const MCU_SRAM_SIZE: usize = 256 * 1024; const KEY: LEArray4x8 = LEArray4x8::new([ 0xb4f7eaf0, 0x50f4421b, 0x05bc3506, 0x11deced9, 0x593d36a5, 0x708828a6, 0xffbc27f5, 0x046e4deb, ]); const IV: [u32; 3] = [0x7816f318, 0x95a57710, 0x074c2dc7]; const EXPECTED_CIPHERTEXT: [u8; 2080] = [ 0x3a, 0x14, 0xd4, 0xef, 0xaf, 0xc6, 0x50, 0x46, 0x6a, 0x78, 0xbd, 0xc6, 0xf3, 0xd9, 0xd2, 0x5c, 0x71, 0x55, 0x0d, 0xa5, 0xcb, 0x94, 0xb0, 0xd4, 0xd2, 0x43, 0x1f, 0x3d, 0x00, 0x64, 0x41, 0xe2, 0x0e, 0x9b, 0x8d, 0xa6, 0xbd, 0x55, 0x39, 0x1b, 0xf6, 0x71, 0xad, 0x6e, 0x7d, 0xf6, 0x7f, 0x89, 0xdb, 0x63, 0x21, 0xe7, 0xab, 0xf4, 0x60, 0x57, 0x23, 0x1d, 0xe7, 0x2c, 0x3c, 0x3e, 0x8e, 0x27, 0x86, 0x0f, 0x78, 0x2a, 0xde, 0xc2, 0xf0, 0xdd, 0xf8, 0x42, 0xea, 0x90, 0x4a, 0x03, 0x79, 0x96, 0xaf, 0xc6, 0x25, 0x30, 0x98, 0x27, 0xc1, 0xc9, 0x53, 0x05, 0x24, 0x40, 0xd3, 0x64, 0x30, 0xd7, 0x57, 0x9a, 0xe7, 0xbf, 0xfc, 0xe6, 0xa5, 0x3b, 0x8d, 0x9e, 0x83, 0x79, 0x65, 0xee, 0xb1, 0x9d, 0x7d, 0xbc, 0x17, 0xcf, 0x05, 0x54, 0x50, 0x6e, 0x07, 0x5e, 0xd8, 0x2a, 0x77, 0x32, 0xd0, 0x00, 0x02, 0x20, 0x94, 0x65, 0x0d, 0x4b, 0x07, 0x88, 0x52, 0xbf, 0x00, 0x52, 0xe5, 0x5d, 0x27, 0xf1, 0x31, 0xd5, 0x36, 0x9d, 0x6d, 0x0e, 0x5e, 0x5f, 0x26, 0xbe, 0xd6, 0xcf, 0x6a, 0x33, 0x82, 0xcd, 0xeb, 0x1b, 0xf6, 0x6f, 0xd4, 0x99, 0xe2, 0xab, 0x1c, 0xc1, 0xf7, 0xdc, 0x14, 0x83, 0x59, 0xe2, 0x9e, 0x02, 0xc2, 0x25, 0x11, 0xc1, 0x08, 0x42, 0xef, 0x65, 0x38, 0x9d, 0x4c, 0xb3, 0x9c, 0xbb, 0x61, 0x93, 0x27, 0x17, 0x7b, 0xac, 0xcf, 0xbc, 0x7b, 0x52, 0x0f, 0xff, 0x02, 0xab, 0x84, 0xe2, 0xe4, 0x95, 0x8e, 0x79, 0x25, 0xe2, 0xc8, 0x4e, 0xf5, 0x83, 0x10, 0xc2, 0xfb, 0x27, 0x63, 0x71, 0x74, 0x0a, 0x93, 0x78, 0xf8, 0x5f, 0xa3, 0x62, 0x72, 0x1f, 0xb0, 0xb0, 0xe9, 0x27, 0xab, 0x81, 0x92, 0x05, 0x76, 0xdd, 0xb8, 0x6d, 0xb6, 0xe1, 0x5e, 0x97, 0x5b, 0x26, 0xc3, 0x23, 0x00, 0x7e, 0xb8, 0xdf, 0xba, 0xed, 0xee, 0x53, 0x33, 0x5c, 0x26, 0xe1, 0x3a, 0x79, 0x6d, 0xee, 0x15, 0x67, 0xb2, 0x7d, 0x9d, 0x53, 0xd3, 0xba, 0x96, 0xdf, 0x0e, 0xde, 0xcd, 0xbe, 0x57, 0x04, 0xb9, 0xf4, 0xf5, 0x79, 0xcb, 0x58, 0x85, 0x28, 0x28, 0x17, 0x1d, 0xeb, 0xc8, 0x67, 0xab, 0x42, 0xa1, 0x14, 0x67, 0xb4, 0x8d, 0xe1, 0x3b, 0x20, 0x21, 0x53, 0x42, 0xe5, 0x83, 0xcf, 0x2a, 0x99, 0x81, 0xb1, 0xd5, 0x61, 0x83, 0x42, 0xfc, 0x4e, 0x9e, 0x74, 0x63, 0xd4, 0x76, 0x51, 0xdf, 0x8b, 0x5f, 0x92, 0x4e, 0xc0, 0x4a, 0x01, 0xe1, 0xbc, 0x5d, 0x92, 0x27, 0x5c, 0xc9, 0x5d, 0xc2, 0xcf, 0x8f, 0xc8, 0x3c, 0x4e, 0x76, 0x78, 0x2f, 0x2b, 0xcb, 0xb3, 0x53, 0xe5, 0x0f, 0x75, 0x4a, 0x6f, 0x0c, 0x86, 0x9c, 0xe8, 0x2d, 0xa2, 0xee, 0xb6, 0x8c, 0x73, 0x71, 0xa4, 0x9e, 0x8b, 0x21, 0x4d, 0xea, 0x1d, 0x56, 0x35, 0x58, 0x25, 0xd3, 0x56, 0x54, 0x9f, 0x50, 0x52, 0xbe, 0xb4, 0x9a, 0x42, 0xe3, 0xe9, 0xe0, 0x57, 0x76, 0x1f, 0xc6, 0xa1, 0xe3, 0xff, 0xc7, 0x1e, 0xfb, 0x0f, 0x9f, 0xff, 0xd8, 0x46, 0xaa, 0x81, 0xd9, 0x6a, 0xc2, 0xc5, 0x15, 0xa2, 0xa2, 0x0a, 0xfb, 0xc6, 0xa1, 0x89, 0x6f, 0x0b, 0x8f, 0x37, 0x49, 0xf6, 0xec, 0x3e, 0x2c, 0x7b, 0x2d, 0xa0, 0x53, 0x35, 0xdf, 0xdf, 0x46, 0x54, 0x96, 0xfd, 0xf4, 0x01, 0xd9, 0x99, 0x47, 0xc8, 0xa0, 0xdf, 0x34, 0xe6, 0x65, 0x7a, 0x74, 0x1e, 0x0a, 0x57, 0xa9, 0xb2, 0x1a, 0xae, 0x3d, 0x3b, 0x66, 0x1d, 0x4e, 0x23, 0x02, 0x07, 0x06, 0x4c, 0x27, 0x66, 0xa8, 0x5d, 0xa6, 0x1b, 0xa6, 0x08, 0xd8, 0x83, 0x33, 0x97, 0x06, 0x32, 0xe2, 0x82, 0xb5, 0x13, 0x2e, 0x22, 0x1e, 0x01, 0x99, 0xf0, 0xc5, 0x82, 0x8d, 0xe2, 0xd3, 0x45, 0xd9, 0x45, 0xb4, 0xed, 0x8d, 0x05, 0x26, 0x26, 0x3a, 0x24, 0x30, 0xf4, 0x74, 0x6b, 0xbb, 0x86, 0x2c, 0xf8, 0x6d, 0x9e, 0xba, 0xc3, 0xe2, 0x72, 0x12, 0x87, 0x93, 0x38, 0x68, 0xed, 0x1d, 0x8b, 0xff, 0x03, 0x74, 0x90, 0x74, 0x00, 0x82, 0xed, 0x7f, 0xf6, 0x07, 0x60, 0x8e, 0x6e, 0x70, 0xfa, 0x42, 0x2d, 0x45, 0x1b, 0xd6, 0xa8, 0xfe, 0xf5, 0x2a, 0xaa, 0xfc, 0xf6, 0x92, 0xb8, 0x80, 0x58, 0xad, 0x25, 0xfb, 0x6a, 0x13, 0x7c, 0xae, 0x39, 0x61, 0xdf, 0x56, 0xf1, 0x58, 0xc6, 0xd1, 0x95, 0xb7, 0x5f, 0x13, 0x06, 0x8f, 0xd5, 0x97, 0x36, 0xf0, 0xaf, 0x0c, 0x78, 0x3f, 0xa4, 0x89, 0x18, 0xf4, 0x5a, 0x4b, 0x10, 0xc6, 0x03, 0x50, 0xd6, 0x8e, 0xba, 0x38, 0xfe, 0xd9, 0xf4, 0x29, 0x58, 0xfc, 0xca, 0x8d, 0x29, 0x79, 0xd1, 0x0e, 0xd1, 0x3b, 0x84, 0xe3, 0x09, 0xa9, 0xb2, 0x75, 0x4c, 0xd7, 0x78, 0x1c, 0xdd, 0x7c, 0x59, 0xc9, 0x62, 0xb8, 0x74, 0xca, 0x38, 0xd1, 0x28, 0x44, 0xaa, 0x1d, 0xbb, 0x22, 0x16, 0x67, 0x7e, 0xc0, 0x29, 0x19, 0x77, 0xa3, 0xcc, 0x83, 0x73, 0xfc, 0xba, 0x16, 0x80, 0x6f, 0xa9, 0x45, 0xdf, 0xfa, 0xde, 0x6e, 0xf3, 0xb9, 0xa7, 0x2f, 0x87, 0x69, 0x6e, 0x1b, 0xfa, 0x07, 0x71, 0x57, 0xb9, 0x0a, 0xf4, 0x41, 0x04, 0xfc, 0x61, 0x04, 0x21, 0x59, 0x69, 0xe1, 0xf2, 0x57, 0x4b, 0x92, 0xfd, 0x47, 0x6f, 0x10, 0x97, 0xb1, 0x2b, 0x44, 0x68, 0x79, 0x8f, 0xe3, 0x3b, 0x77, 0xf4, 0xc0, 0xf0, 0xac, 0x4b, 0x89, 0x0b, 0x83, 0x2d, 0xa7, 0x78, 0x25, 0x0b, 0x0b, 0xfc, 0xbd, 0x69, 0xe9, 0x8a, 0x02, 0x04, 0xb9, 0x5d, 0x2d, 0x14, 0x70, 0xca, 0x9c, 0x03, 0x7f, 0xde, 0x3a, 0xce, 0x6f, 0x35, 0x06, 0x52, 0xf6, 0x48, 0xfd, 0xaa, 0x87, 0xfd, 0xfd, 0x80, 0xd1, 0xb9, 0xe2, 0x90, 0x03, 0xb4, 0xef, 0xbc, 0xe5, 0x47, 0xa0, 0x4d, 0x9c, 0x40, 0x02, 0xeb, 0x44, 0xa7, 0x77, 0x21, 0xee, 0x95, 0xd3, 0x0a, 0x96, 0x09, 0x5c, 0x20, 0xf1, 0x45, 0x8c, 0x81, 0x4c, 0xe0, 0xa7, 0xcf, 0x8d, 0xac, 0xf5, 0x63, 0x0c, 0xa6, 0xe4, 0xd9, 0x18, 0x22, 0xde, 0xf0, 0x5f, 0x4d, 0xc6, 0xb5, 0xa5, 0xb9, 0x9a, 0xbc, 0x7f, 0xf8, 0xd0, 0xbc, 0xb0, 0x89, 0x52, 0x8c, 0x02, 0xd9, 0x9b, 0x61, 0xc8, 0xaf, 0x5f, 0x43, 0x0a, 0xdb, 0xc0, 0xe3, 0xcf, 0x46, 0x67, 0x3c, 0x0b, 0x73, 0x6f, 0x67, 0x33, 0xfd, 0xf5, 0x85, 0x3f, 0x89, 0x9e, 0x04, 0xee, 0xe7, 0x53, 0x2c, 0xf5, 0x5e, 0x84, 0xef, 0xc1, 0x42, 0x40, 0x20, 0xe1, 0x67, 0x97, 0x49, 0xef, 0x31, 0xe7, 0x26, 0x5b, 0xa1, 0x22, 0x6c, 0x28, 0x72, 0x8d, 0xff, 0xb8, 0x34, 0x51, 0x9d, 0x75, 0xfd, 0x07, 0x21, 0x28, 0xd4, 0xb9, 0xb0, 0x0c, 0x1f, 0xde, 0x20, 0xa1, 0x2b, 0xf3, 0x7a, 0x5c, 0xf1, 0xb9, 0xcf, 0x10, 0x8e, 0xc4, 0x0b, 0x43, 0x20, 0x1a, 0xe9, 0x6b, 0xb8, 0x7c, 0x5b, 0xfb, 0x21, 0x47, 0xf6, 0xcd, 0xe9, 0xc6, 0x3d, 0xcb, 0x67, 0x2c, 0xca, 0x12, 0x36, 0xec, 0x96, 0x66, 0x03, 0xed, 0xf8, 0x56, 0x24, 0x12, 0x84, 0x2b, 0x9b, 0xc8, 0xff, 0x24, 0xa5, 0x4c, 0x65, 0x0a, 0xbf, 0x86, 0xfe, 0x6d, 0xe4, 0xda, 0x28, 0x7e, 0xa6, 0x52, 0x52, 0x09, 0x6c, 0x79, 0xdf, 0x2a, 0x99, 0x93, 0xf4, 0xa7, 0x6f, 0xf1, 0x69, 0xb1, 0x59, 0x48, 0xe6, 0x0e, 0x67, 0xb1, 0xcf, 0xdb, 0x75, 0x42, 0x75, 0x12, 0x9b, 0x03, 0x0f, 0x05, 0x69, 0xed, 0xb0, 0x26, 0x00, 0x6b, 0xfe, 0x2d, 0x19, 0xb8, 0xb4, 0x15, 0x46, 0xf4, 0x4b, 0xfe, 0xc2, 0x07, 0x1b, 0x9f, 0x63, 0x49, 0x45, 0xe6, 0x10, 0x7b, 0xff, 0x84, 0x6d, 0xb3, 0x86, 0xf3, 0x27, 0xd0, 0x79, 0x17, 0x33, 0xa4, 0xe5, 0x49, 0xc8, 0xa6, 0x29, 0xf3, 0x33, 0x0b, 0xb6, 0xee, 0xfe, 0x7a, 0xe4, 0x85, 0xd3, 0x73, 0x85, 0x27, 0xa2, 0xe4, 0xf1, 0x89, 0x67, 0x1a, 0x28, 0x79, 0xb3, 0xda, 0x17, 0xe4, 0x67, 0x3c, 0x35, 0x8e, 0x6d, 0x75, 0x97, 0x24, 0x24, 0xb6, 0x53, 0xee, 0xf2, 0x43, 0xf2, 0x1d, 0x39, 0xd6, 0xe7, 0xa6, 0x36, 0x53, 0x83, 0x2d, 0x43, 0x20, 0x37, 0x56, 0x4e, 0x4a, 0x0c, 0xbf, 0x09, 0xf0, 0x51, 0x40, 0xe2, 0xc4, 0xf1, 0x38, 0xe8, 0xa6, 0x82, 0xc9, 0xed, 0xa0, 0xb5, 0x88, 0x41, 0x35, 0x1c, 0xfb, 0xae, 0xc5, 0x7b, 0x37, 0xee, 0x6a, 0x72, 0x20, 0xc5, 0xd6, 0x0b, 0x8b, 0xbc, 0x31, 0xff, 0x33, 0xd2, 0x84, 0xcb, 0xfd, 0x24, 0x59, 0x5e, 0x74, 0xc3, 0x96, 0x6c, 0x2e, 0x19, 0x80, 0x89, 0xcf, 0xed, 0xa9, 0xf9, 0x16, 0xa6, 0x8c, 0xf3, 0x33, 0x2f, 0x3a, 0xaf, 0xea, 0x83, 0x74, 0xf1, 0xce, 0x35, 0xd9, 0x26, 0xd3, 0x6d, 0x89, 0xe6, 0xaa, 0x64, 0x56, 0x4b, 0x5a, 0x77, 0x84, 0x27, 0x7d, 0xf7, 0x07, 0xf1, 0xe0, 0xcb, 0x2b, 0x20, 0x96, 0xba, 0xa7, 0x5f, 0x03, 0x38, 0x7c, 0xc1, 0x3f, 0x2e, 0x29, 0xca, 0x77, 0x18, 0x64, 0x3a, 0x50, 0x89, 0x0f, 0x0a, 0x5b, 0xc1, 0xf8, 0x15, 0xb8, 0xe8, 0xa7, 0xc9, 0x19, 0x9a, 0x07, 0xaf, 0xed, 0x24, 0x5b, 0x00, 0xc7, 0x15, 0x60, 0xa6, 0x27, 0x71, 0xc6, 0x91, 0xb7, 0xbd, 0x11, 0xed, 0xe2, 0x98, 0x68, 0xe9, 0x1a, 0x33, 0x46, 0xf6, 0xcb, 0xfe, 0x6c, 0xa1, 0x6f, 0xa7, 0x62, 0xca, 0xca, 0x8f, 0xb8, 0x2c, 0x01, 0xe9, 0x8c, 0x95, 0xd2, 0xb6, 0x6b, 0x1f, 0x64, 0x82, 0x9e, 0x32, 0xe6, 0x25, 0xf7, 0x07, 0x8b, 0xbf, 0xc8, 0xc4, 0xc3, 0xdd, 0x38, 0x96, 0x97, 0x47, 0xd6, 0x53, 0x66, 0x65, 0xbc, 0x95, 0x76, 0xa8, 0xf3, 0x12, 0xcf, 0x1d, 0xc9, 0x71, 0xd6, 0xf8, 0x89, 0xc9, 0xfc, 0x9a, 0x3c, 0x53, 0x5b, 0x04, 0x43, 0x00, 0xfd, 0x48, 0x9b, 0x53, 0xf7, 0xfc, 0x0c, 0x31, 0xf0, 0x6c, 0x26, 0x0e, 0x2c, 0xc2, 0xb0, 0xfe, 0x34, 0x46, 0x38, 0x06, 0x2b, 0x19, 0x03, 0x22, 0x16, 0xd2, 0xbf, 0xb0, 0xb9, 0x2c, 0x7a, 0xb3, 0xc4, 0x3e, 0xdf, 0xbd, 0xf6, 0x2f, 0x60, 0xbf, 0xdd, 0xa2, 0x37, 0x80, 0x53, 0x80, 0xda, 0xd3, 0xb8, 0x45, 0x7b, 0xa7, 0x73, 0xd5, 0x4f, 0xfa, 0xaa, 0x00, 0x09, 0x2c, 0x28, 0xb9, 0xe6, 0xf9, 0xcb, 0x92, 0x0b, 0x17, 0xbe, 0x02, 0x96, 0x48, 0x23, 0x25, 0xf2, 0x68, 0x4b, 0x54, 0xdb, 0x24, 0x73, 0x45, 0x0a, 0xdb, 0x64, 0x07, 0xba, 0xb4, 0xb7, 0x48, 0xc6, 0xc1, 0xbd, 0xa9, 0xa7, 0xeb, 0xa3, 0xfc, 0x83, 0xa0, 0xfc, 0x90, 0xd7, 0xf6, 0x84, 0x75, 0x2f, 0xcc, 0x30, 0x1c, 0xda, 0x98, 0xcb, 0x2a, 0x4f, 0x05, 0x5e, 0x15, 0x08, 0x7b, 0x05, 0xed, 0x51, 0xb5, 0xd3, 0xa7, 0x42, 0xfe, 0xcd, 0x45, 0x0d, 0x58, 0xef, 0x8f, 0x29, 0x6e, 0xb5, 0x6e, 0x40, 0xa1, 0x16, 0x3e, 0xbe, 0x49, 0x12, 0xf7, 0x4d, 0xa2, 0x44, 0xd3, 0xfc, 0xc4, 0xd3, 0x60, 0xc1, 0x28, 0x7b, 0x54, 0x08, 0x71, 0xde, 0xd0, 0xc9, 0xc4, 0x9a, 0x7b, 0x38, 0xf7, 0x12, 0xcd, 0xdd, 0x76, 0xee, 0xed, 0x4d, 0x2d, 0x44, 0x8b, 0xb3, 0x0c, 0x83, 0x2c, 0x46, 0xc5, 0x44, 0x6e, 0x1e, 0x17, 0xca, 0xc3, 0x06, 0x0c, 0x0a, 0xe2, 0x1b, 0xde, 0x88, 0x79, 0x7f, 0x41, 0x53, 0x64, 0x4d, 0x28, 0x40, 0xc5, 0x49, 0xa8, 0xd9, 0x3c, 0x55, 0xf0, 0xa5, 0x61, 0xc3, 0x6d, 0xd6, 0x62, 0x9c, 0x8a, 0x54, 0x70, 0xe3, 0xb7, 0xaf, 0xdc, 0x57, 0x46, 0xee, 0x76, 0x0e, 0x52, 0x05, 0xef, 0x7d, 0x80, 0xe4, 0x42, 0xf9, 0xe6, 0x55, 0x82, 0x93, 0x54, 0x1c, 0x06, 0x14, 0xc3, 0xe8, 0x42, 0x88, 0x3f, 0xbc, 0x52, 0x45, 0x50, 0x9f, 0x06, 0xa7, 0x8d, 0xf4, 0xdd, 0xe1, 0x5b, 0x84, 0xda, 0x6b, 0xf4, 0xaf, 0xef, 0x05, 0x1d, 0xcc, 0x6d, 0x5d, 0xd6, 0x66, 0xd6, 0x16, 0xf3, 0x38, 0x26, 0xe2, 0xfd, 0x44, 0x14, 0xb1, 0x8b, 0x2b, 0x0d, 0xf2, 0x8c, 0x48, 0x89, 0x59, 0x17, 0x26, 0xc4, 0x88, 0xb6, 0xef, 0x70, 0xb5, 0xed, 0xed, 0x94, 0x6c, 0x3f, 0x5c, 0xe5, 0x01, 0x33, 0x6f, 0x47, 0x99, 0x04, 0x6b, 0xda, 0x09, 0xee, 0x9f, 0x4b, 0x40, 0x5a, 0xa3, 0x99, 0x01, 0xde, 0x69, 0x10, 0x8d, 0x43, 0x20, 0x64, 0x79, 0x1d, 0x2d, 0xd4, 0xf4, 0x85, 0xab, 0x3a, 0xd5, 0x5b, 0x75, 0xca, 0x83, 0x39, 0x6b, 0x7b, 0xd1, 0x91, 0xbc, 0x33, 0x58, 0x0c, 0xda, 0x61, 0x64, 0xef, 0x96, 0xe4, 0x7e, 0x83, 0xff, 0x4f, 0xd9, 0x16, 0x29, 0x50, 0x1b, 0xb0, 0xde, 0x64, 0x92, 0xbd, 0x77, 0x9a, 0xb3, 0x13, 0x3f, 0xa9, 0x1c, 0x88, 0x21, 0x71, 0x0d, 0x0f, 0x35, 0xfe, 0xf3, 0x44, 0x90, 0x20, 0xfb, 0xa6, 0x87, 0x5c, 0x19, 0x39, 0x37, 0xb1, 0xb8, 0xe0, 0x4d, 0x4f, 0x94, 0xd5, 0x13, 0x1d, 0xe8, 0xac, 0xc1, 0x8a, 0x75, 0xa6, 0x70, 0x15, 0x71, 0xfd, 0x8d, 0xa3, 0xb4, 0xf3, 0xb8, 0xd9, 0x9c, 0x4a, 0xe9, 0x20, 0x85, 0x6e, 0x9c, 0xca, 0xdb, 0x3d, 0x21, 0xfd, 0x88, 0x14, 0xc1, 0xfe, 0x99, 0xc4, 0xbf, 0x7c, 0xe3, 0x07, 0xb5, 0x90, 0xbb, 0xe0, 0xa8, 0x78, 0xd5, 0xbf, 0x83, 0x9a, 0x49, 0x81, 0x90, 0x36, 0xab, 0x30, 0xa0, 0xa1, 0x4e, 0x8d, 0x2d, 0xbd, 0xf9, 0x30, 0x0b, 0xcb, 0xc9, 0xde, 0x73, 0x1b, 0x1c, 0x63, 0xc7, 0x01, 0x02, 0x55, 0x47, 0x22, 0x1f, 0x59, 0xbf, 0x65, 0xe7, 0x4e, 0xad, 0xe5, 0xca, 0xa1, 0x12, 0xb0, 0x87, 0xb8, 0x82, 0x15, 0xab, 0x93, 0xf5, 0xd6, 0x7c, 0x18, 0x22, 0xc3, 0xcc, 0x0d, 0x76, 0x26, 0x7f, 0x41, 0x54, 0xdd, 0xcd, 0x30, 0x1f, 0xcc, 0x2c, 0x48, 0x91, 0xc7, 0xdb, 0xb9, 0xac, 0x8e, 0x9e, 0xa3, 0x02, 0xfc, 0x5a, 0xe8, 0xed, 0xcf, 0x3c, 0xb8, 0x84, 0x3f, 0xac, 0xd0, 0xfe, 0x9c, 0xc5, 0x08, 0xa6, 0x2f, 0x1e, 0xe6, 0x18, 0x4c, 0x78, 0x80, 0x93, 0xe5, 0x81, 0x65, 0xd0, 0xe3, 0xad, 0x1d, 0xd2, 0x35, 0xe9, 0xf3, 0x58, 0x56, 0x37, 0xe4, 0x8b, 0x46, 0xe1, 0xe0, 0xd2, 0xd9, 0xab, 0x91, 0x16, 0x4b, 0x2b, 0x35, 0xff, 0xcb, 0x39, 0x5d, 0x70, 0x2c, 0xd3, 0x4a, 0x05, 0x5e, 0xfc, 0x23, 0xb7, 0x1d, 0x11, 0xe2, 0x58, 0xfe, 0xf0, 0x88, 0xc8, 0xf4, 0xb0, 0x60, 0x34, 0x6c, 0x64, 0x9f, 0x1c, 0x7f, 0x50, 0xfb, 0x9b, 0xfd, 0xe4, 0x74, 0xde, 0x4a, 0x05, 0x37, 0x9f, 0xc6, 0xcb, 0x7d, 0x8e, 0x79, 0xc3, 0xcd, 0xb0, 0xcc, 0x80, 0x37, 0x13, 0xb9, 0x30, 0x50, 0x69, 0x13, 0x06, 0xb7, 0x0b, 0x8b, 0x04, 0xb6, 0x2e, 0x7a, 0x08, 0xdf, 0x66, 0x41, 0x5f, 0xc1, 0x11, 0x5a, 0xcf, 0x9c, 0x30, 0x9b, 0xbe, 0xf8, 0xf2, 0x2c, 0xc4, 0xb6, 0xe2, 0xfb, 0x85, 0x9a, 0x4d, 0xf2, 0xaf, 0x41, 0xc2, 0x82, 0x49, 0x47, 0xd3, 0x13, 0x93, 0x23, 0xd3, 0x0d, 0xc7, 0x79, 0xff, 0xdb, 0xff, 0xb7, 0x0d, 0x4b, 0x30, 0x9c, 0xa4, 0xf6, 0x4e, 0x92, 0xad, 0x23, 0xe8, 0x51, 0x1b, 0x14, 0xb9, 0x91, 0x5c, 0x59, 0xef, 0x97, 0x53, 0x47, 0x7d, 0xa9, 0xc7, 0xa3, 0x59, 0xe5, 0xd2, 0xdb, 0xce, 0xd0, 0x0b, 0x4b, 0x54, 0x9f, 0x41, 0x5d, 0xb8, 0xf3, 0x8f, 0x35, 0x6e, 0xf4, 0xd9, 0xec, 0xa7, 0x83, 0x5e, 0x64, 0x18, 0x52, 0xef, 0x9e, 0x22, 0xcc, 0x39, 0x62, 0x74, 0xbf, 0x7d, 0x4a, 0x78, 0x4e, 0xe8, 0x4a, 0xde, 0x3e, 0x56, 0x27, 0x04, 0xbf, 0xbb, 0x81, 0x5f, 0xa2, 0x8d, 0x14, 0x50, 0x0f, 0x0b, 0x44, ]; const _: () = assert!(EXPECTED_CIPHERTEXT.len() % 4 == 0); fn zeroize_axi(dma: &mut Dma, addr: u64, len: usize) { // TODO: this would be faster if we queued up 256 bytes at a time for i in (0..len).step_by(4) { dma.write_dword((addr + i as u64).into(), 0); } } fn dma_aes(dma: &mut Dma, aes: &mut Aes, trng: &mut Trng, src: u64, dst: u64, max_len: usize) { // prep AES GCM let key = KEY; aes.initialize_aes_gcm( trng, AesGcmIv::Array(&IV.into()), AesKey::Array(&key), &[], AesOperation::Encrypt, ) .unwrap(); aes.gcm_set_text(16); dma.setup_dma_read(DmaReadTransaction { read_addr: src.into(), // MCU SRAM, which should be zero fixed_addr: false, length: max_len as u32, target: DmaReadTarget::AxiWr(dst.into(), false), aes_mode: true, aes_gcm: true, block_mode: caliptra_drivers::dma::BlockMode::Other, }); dma.wait_for_dma_complete(); } fn run_dma_aes_test( dma: &mut Dma, aes: &mut Aes, trng: &mut Trng, src: u64, dst: u64, max_len: usize, ) { let mut output = [0u32; EXPECTED_CIPHERTEXT.len() / 4]; dma_aes(dma, aes, trng, src, dst, max_len); dma.flush(); let len = max_len.div_ceil(4).min(output.len()); dma.setup_dma_read(DmaReadTransaction { read_addr: dst.into(), // MCU SRAM, which should be encrypted output fixed_addr: false, length: (len * 4) as u32, target: DmaReadTarget::AhbFifo, aes_mode: false, aes_gcm: false, block_mode: caliptra_drivers::dma::BlockMode::Other, }); dma.dma_read_fifo(&mut output[..len]); dma.wait_for_dma_complete(); let output: &[u8] = output.as_bytes(); assert_eq!(&output[..len * 4], &EXPECTED_CIPHERTEXT[..len * 4]); } fn test_dma_aes_mcu_sram_inplace() { // Init CFI CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut dma = Dma::default(); let soc = unsafe { SocIfc::new(SocIfcReg::new()) }; // test only runs in subsystem mode if !soc.subsystem_mode() { return; } let mut aes = unsafe { Aes::new(AesReg::new(), AesClpReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // Read and decrypt 0s from MCU SRAM to MCU SRAM let mcu_sram_offset = MCU_SRAM_OFFSET as u64; let mcu_base_addr = soc.mci_base_addr() + mcu_sram_offset; let zeroize_mcu_sram = |dma: &mut Dma| { zeroize_axi(dma, mcu_base_addr, EXPECTED_CIPHERTEXT.len()); }; let src = mcu_base_addr; let dst = mcu_base_addr; for max_len in (4..EXPECTED_CIPHERTEXT.len()).step_by(4) { zeroize_mcu_sram(&mut dma); run_dma_aes_test(&mut dma, &mut aes, &mut trng, src, dst, max_len); } cprintln!("AES DMA OK"); } fn test_dma_aes_mcu_sram() { // Init CFI CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut dma = Dma::default(); let soc = unsafe { SocIfc::new(SocIfcReg::new()) }; // test only runs in subsystem mode if !soc.subsystem_mode() { return; } let mut aes = unsafe { Aes::new(AesReg::new(), AesClpReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // Read and decrypt 0s from MCU SRAM to MCU SRAM let mcu_sram_offset = MCU_SRAM_OFFSET as u64; let mcu_base_addr = soc.mci_base_addr() + mcu_sram_offset; let zeroize_mcu_sram = |dma: &mut Dma| { zeroize_axi(dma, mcu_base_addr, EXPECTED_CIPHERTEXT.len() * 3); }; let src = mcu_base_addr; let dst = mcu_base_addr + (EXPECTED_CIPHERTEXT.len() * 2) as u64; // ensure no overlap for max_len in (4..EXPECTED_CIPHERTEXT.len()).step_by(4) { zeroize_mcu_sram(&mut dma); run_dma_aes_test(&mut dma, &mut aes, &mut trng, src, dst, max_len); } cprintln!("AES DMA OK"); } fn test_dma_aes_mcu_sram_256kb() { // Init CFI CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut dma = Dma::default(); let soc = unsafe { SocIfc::new(SocIfcReg::new()) }; // test only runs in subsystem mode if !soc.subsystem_mode() { return; } let mut sha = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let mut op = sha.sha384_digest_init().expect("SHA384 init failed"); // Zeroize MCU SRAM zeroize_axi( &mut dma, soc.mci_base_addr() + MCU_SRAM_OFFSET as u64, MCU_SRAM_SIZE, ); // Encrypt MCU SRAM let mut aes = unsafe { Aes::new(AesReg::new(), AesClpReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let mcu_sram_offset = MCU_SRAM_OFFSET as u64; let mcu_base_addr = soc.mci_base_addr() + mcu_sram_offset; dma_aes( &mut dma, &mut aes, &mut trng, mcu_base_addr, mcu_base_addr, MCU_SRAM_SIZE, ); // Compute SHA384 of MCU SRAM for i in (0..MCU_SRAM_SIZE).step_by(4) { let read_addr = mcu_base_addr + i as u64; op.update(&dma.read_dword(read_addr.into()).to_le_bytes()) .expect("SHA384 update failed"); } let mut digest = Array4x12::default(); op.finalize(&mut digest).expect("SHA384 finalize failed"); // computed in Python let expected_digest = Array4x12::new([ 0x6c6a0577, 0x126d7546, 0xf2223614, 0x5a74e7ba, 0x6f835173, 0xd1dc46f0, 0xf0e62026, 0xcc8c8407, 0x09afbd27, 0xec2713ff, 0xb6ca302c, 0x77720db6, ]); // Compare the results assert_eq!( digest, expected_digest, "DMA SHA384 result should match regular SHA384 result" ); let tag = aes .compute_tag(0, MCU_SRAM_SIZE) .expect("AES compute_tag failed"); let expected_tag: [u8; 16] = [ 0x57, 0x55, 0x1b, 0x03, 0x7e, 0x3a, 0x39, 0x0b, 0xd2, 0x93, 0x79, 0xf1, 0x76, 0x29, 0x9e, 0x1c, ]; assert_eq!( tag.as_bytes(), expected_tag, "AES tag should match expected tag" ); } test_suite! { test_dma_aes_mcu_sram, test_dma_aes_mcu_sram_inplace, test_dma_aes_mcu_sram_256kb, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/test_success.rs
drivers/test-fw/src/bin/test_success.rs
// Licensed under the Apache-2.0 license //! A very simple ROM. Prints an 'S' character followed by a request to exit //! with success. Used for testing the toolchain and test infrastructure. #![no_main] #![no_std] #[panic_handler] pub fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } #[no_mangle] extern "C" fn main() { let mut soc_ifc = unsafe { caliptra_registers::soc_ifc::SocIfcReg::new() }; soc_ifc .regs_mut() .cptra_generic_output_wires() .at(0) .write(|_| b'S'.into()); // 0xff means exit with success soc_ifc .regs_mut() .cptra_generic_output_wires() .at(0) .write(|_| 0xff); loop {} }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/trng_driver_responder.rs
drivers/test-fw/src/bin/trng_driver_responder.rs
// Licensed under the Apache-2.0 license //! A very simple program that responds with TRNG data through the mailbox #![no_main] #![no_std] // Needed to bring in startup code #[allow(unused)] use caliptra_test_harness::{self, println}; use caliptra_drivers::{self, Trng}; use caliptra_registers::{ csrng::CsrngReg, entropy_src::EntropySrcReg, mbox::MboxCsr, soc_ifc::SocIfcReg, soc_ifc_trng::SocIfcTrngReg, }; use zerocopy::IntoBytes; #[panic_handler] pub fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } #[no_mangle] extern "C" fn cfi_panic_handler(code: u32) -> ! { println!("[TRNG] CFI Panic code=0x{:08X}", code); loop {} } #[no_mangle] extern "C" fn main() { let csrng_reg = unsafe { CsrngReg::new() }; let entropy_src_reg = unsafe { EntropySrcReg::new() }; let soc_ifc_trng = unsafe { SocIfcTrngReg::new() }; let mut soc_ifc = unsafe { SocIfcReg::new() }; let mut mbox = unsafe { MboxCsr::new() }; let mut trng = Trng::new(csrng_reg, entropy_src_reg, soc_ifc_trng, &soc_ifc).unwrap(); loop { if !mbox.regs().status().read().mbox_fsm_ps().mbox_execute_uc() { continue; } match trng.generate() { Ok(data) => { mbox.regs_mut() .dlen() .write(|_| data.0.as_bytes().len() as u32); for word in data.0 { mbox.regs_mut().datain().write(|_| word); } mbox.regs_mut() .status() .write(|w| w.status(|w| w.data_ready())); } Err(e) => { soc_ifc .regs_mut() .cptra_fw_error_non_fatal() .write(|_| e.into()); mbox.regs_mut() .status() .write(|w| w.status(|w| w.cmd_failure())); } } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/test_failure.rs
drivers/test-fw/src/bin/test_failure.rs
// Licensed under the Apache-2.0 license //! A very simple ROM. Prints an 'F' character followed by a request to exit //! with failure. Used for testing the toolchain and test infrastructure. #![no_main] #![no_std] #[panic_handler] pub fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } #[no_mangle] extern "C" fn main() { let mut soc_ifc = unsafe { caliptra_registers::soc_ifc::SocIfcReg::new() }; soc_ifc .regs_mut() .cptra_generic_output_wires() .at(0) .write(|_| b'F'.into()); // 0xff means exit with failure soc_ifc .regs_mut() .cptra_generic_output_wires() .at(0) .write(|_| 0x01); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/negative_tests_lms.rs
drivers/test-fw/src/bin/negative_tests_lms.rs
/* Licensed under the Apache-2.0 license. File Name: lms_24_tests.rs Abstract: File contains test cases for LMS signature verification using SHA256/192. --*/ #![no_std] #![no_main] use caliptra_drivers::{CaliptraError, Lms, LmsResult, Sha256}; use caliptra_lms_types::{ bytes_to_words_6, LmotsAlgorithmType, LmotsSignature, LmsAlgorithmType, LmsIdentifier, LmsPublicKey, LmsSignature, }; use caliptra_registers::sha256::Sha256Reg; use caliptra_test_harness::test_suite; use zerocopy::{LittleEndian, U32}; fn test_failures_lms_24() { let mut sha256 = unsafe { Sha256::new(Sha256Reg::new()) }; const MESSAGE: [u8; 33] = [ 116, 104, 105, 115, 32, 105, 115, 32, 116, 104, 101, 32, 109, 101, 115, 115, 97, 103, 101, 32, 73, 32, 119, 97, 110, 116, 32, 115, 105, 103, 110, 101, 100, ]; const LMS_IDENTIFIER: LmsIdentifier = [ 158, 20, 249, 74, 242, 177, 66, 175, 101, 91, 176, 36, 80, 31, 240, 7, ]; const Q: u32 = 0; const LMOTS_TYPE: LmotsAlgorithmType = LmotsAlgorithmType::LmotsSha256N24W4; const LMS_TYPE: LmsAlgorithmType = LmsAlgorithmType::LmsSha256N24H15; const LMS_PUBLIC_HASH: [U32<LittleEndian>; 6] = bytes_to_words_6([ 0x03, 0x2a, 0xa2, 0xbd, 0x9b, 0x31, 0xe9, 0xbd, 0x33, 0x4b, 0x46, 0x2e, 0x27, 0x79, 0x20, 0x75, 0xbd, 0xad, 0xdd, 0xae, 0xf9, 0xed, 0xb1, 0x24, ]); const NONCE: [U32<LittleEndian>; 6] = bytes_to_words_6([ 0xb4, 0x24, 0x09, 0xdb, 0xdd, 0x4a, 0x1c, 0x49, 0xfc, 0x79, 0x37, 0x94, 0x75, 0xe9, 0xc7, 0x67, 0x1c, 0x7f, 0x51, 0x53, 0xf7, 0x53, 0x5a, 0xc4, ]); const Y: [[U32<LittleEndian>; 6]; 51] = [ bytes_to_words_6([ 0x72, 0x53, 0xaf, 0x69, 0xc8, 0x5a, 0x5b, 0x96, 0x10, 0x55, 0xcc, 0x03, 0xb7, 0xe1, 0xee, 0x83, 0xab, 0xb0, 0x32, 0xb3, 0x14, 0x58, 0xfa, 0x69, ]), bytes_to_words_6([ 0x00, 0xd4, 0xf4, 0xfc, 0xda, 0x35, 0x7d, 0xc9, 0xa9, 0x44, 0x10, 0x23, 0x3d, 0x4b, 0x00, 0xb4, 0xb9, 0x2c, 0xa8, 0x6e, 0xf0, 0xf8, 0xfd, 0x13, ]), bytes_to_words_6([ 0xd2, 0xad, 0x7e, 0x03, 0xec, 0x32, 0xc0, 0x59, 0x8f, 0x9b, 0x64, 0xfd, 0x8c, 0x6f, 0x82, 0x79, 0xf7, 0x8e, 0x88, 0xe7, 0x7b, 0x4c, 0xdb, 0x89, ]), bytes_to_words_6([ 0x6c, 0xe4, 0x9e, 0x66, 0x3b, 0x32, 0x6b, 0x29, 0x1d, 0xe5, 0xc9, 0xdb, 0xdf, 0xab, 0x05, 0x68, 0x1d, 0xb5, 0x86, 0x68, 0x1e, 0x80, 0xe6, 0xaf, ]), bytes_to_words_6([ 0xba, 0x95, 0x8f, 0xbe, 0x1c, 0x83, 0xbe, 0x4e, 0x1a, 0xd2, 0x3f, 0x0e, 0x0e, 0x97, 0xa6, 0xb0, 0xe8, 0x00, 0xf3, 0xce, 0x97, 0xb5, 0xfc, 0xb0, ]), bytes_to_words_6([ 0x94, 0x9e, 0x57, 0xed, 0x65, 0xb9, 0x5c, 0x2c, 0xb9, 0xbb, 0x4c, 0x84, 0x4e, 0x4e, 0x4c, 0xe3, 0x1f, 0x63, 0xf1, 0x2b, 0x01, 0x5d, 0x35, 0xbc, ]), bytes_to_words_6([ 0xad, 0xef, 0xb1, 0xee, 0x3a, 0xb2, 0xc4, 0x6d, 0x0c, 0x3b, 0x52, 0x4d, 0x92, 0x40, 0xed, 0xf1, 0xcc, 0xc7, 0x09, 0xa7, 0xf9, 0x78, 0x55, 0x13, ]), bytes_to_words_6([ 0xf7, 0x8c, 0xf3, 0xcc, 0x15, 0xe1, 0xb9, 0xb1, 0x71, 0xa9, 0x2f, 0x26, 0x33, 0x47, 0x59, 0x5c, 0x24, 0xf2, 0xd5, 0xbe, 0xae, 0xa6, 0x97, 0x93, ]), bytes_to_words_6([ 0x4a, 0x52, 0x99, 0xfe, 0x4c, 0x7e, 0x6c, 0x83, 0x30, 0x9f, 0x98, 0xc0, 0x5e, 0xc3, 0xd6, 0x27, 0x9d, 0x33, 0x50, 0x81, 0xef, 0xa7, 0x48, 0x31, ]), bytes_to_words_6([ 0x6b, 0x34, 0x75, 0x7d, 0xf9, 0x1a, 0x72, 0x39, 0xaf, 0xf2, 0x6b, 0x46, 0x5e, 0xc4, 0x80, 0x9e, 0x22, 0x22, 0x9b, 0xee, 0x79, 0xac, 0x90, 0x11, ]), bytes_to_words_6([ 0xac, 0xb3, 0xee, 0xa6, 0x42, 0x30, 0xb3, 0xd4, 0xeb, 0x54, 0x1a, 0xad, 0xa7, 0xb5, 0x6d, 0x44, 0x15, 0x93, 0x81, 0x7a, 0x1c, 0x0a, 0x47, 0x3b, ]), bytes_to_words_6([ 0x02, 0x02, 0x95, 0xb8, 0x60, 0x41, 0x64, 0xb9, 0xbe, 0xdb, 0x11, 0xef, 0xb0, 0x39, 0x43, 0x9e, 0x88, 0xa3, 0x0e, 0x5d, 0x9a, 0xf4, 0x80, 0x69, ]), bytes_to_words_6([ 0x16, 0xca, 0xa9, 0x22, 0xec, 0x5d, 0x33, 0x0b, 0x09, 0x54, 0xa3, 0x17, 0x8d, 0x1c, 0xd8, 0xbd, 0xd2, 0x8c, 0x64, 0xfc, 0x07, 0x9e, 0xd8, 0x23, ]), bytes_to_words_6([ 0xbc, 0x7a, 0xbb, 0x42, 0x76, 0xda, 0x10, 0x58, 0xa2, 0x3c, 0xf4, 0x00, 0x08, 0x63, 0xea, 0x20, 0x04, 0x5b, 0xe2, 0xf2, 0xb8, 0xdc, 0x7e, 0xcf, ]), bytes_to_words_6([ 0x0b, 0x30, 0xc2, 0x12, 0x8e, 0xa5, 0x37, 0xb9, 0x0e, 0x76, 0x4b, 0x3a, 0x49, 0x79, 0xd6, 0x6d, 0x67, 0x30, 0x71, 0x90, 0x90, 0xdb, 0x89, 0x5b, ]), bytes_to_words_6([ 0x61, 0xbb, 0xc3, 0x6a, 0x85, 0x37, 0x69, 0x4c, 0x23, 0x4f, 0x5a, 0x11, 0xe5, 0xc3, 0x0d, 0xa5, 0x39, 0x7b, 0x7f, 0x7c, 0x87, 0xf4, 0xec, 0xdc, ]), bytes_to_words_6([ 0xd6, 0x63, 0x57, 0xdb, 0xa0, 0x08, 0xa1, 0x87, 0x8a, 0x89, 0x2a, 0x58, 0x0c, 0x5a, 0x72, 0x7a, 0xf2, 0x03, 0x16, 0x1c, 0x13, 0x54, 0x14, 0xc9, ]), bytes_to_words_6([ 0x3e, 0xe0, 0xf7, 0xa9, 0x34, 0xc5, 0xd2, 0x2b, 0xf5, 0x93, 0x05, 0x03, 0xaa, 0xd9, 0xb8, 0x6d, 0x79, 0x7e, 0xf9, 0xea, 0xce, 0x0d, 0x39, 0x9e, ]), bytes_to_words_6([ 0x6f, 0x80, 0xb7, 0x3e, 0x9a, 0x46, 0xa9, 0x23, 0x11, 0x09, 0xa1, 0x54, 0x1d, 0xf7, 0x21, 0x36, 0x13, 0x87, 0x3f, 0x73, 0xb6, 0xb9, 0xb8, 0xca, ]), bytes_to_words_6([ 0x7e, 0x66, 0xc4, 0x94, 0x75, 0xd8, 0xc1, 0x7e, 0xea, 0xf4, 0xa2, 0x2b, 0x1e, 0x9c, 0x0f, 0x74, 0xfc, 0x5a, 0xb0, 0xe2, 0x16, 0xba, 0x54, 0x75, ]), bytes_to_words_6([ 0xb0, 0x82, 0x56, 0x96, 0x36, 0xdc, 0xbf, 0xfd, 0xd8, 0xea, 0x96, 0x55, 0xb7, 0x8b, 0x3a, 0x99, 0x1d, 0x32, 0xd7, 0xf2, 0x96, 0x7a, 0xd8, 0x74, ]), bytes_to_words_6([ 0xd5, 0x39, 0x88, 0x92, 0xfb, 0xd4, 0x5d, 0xba, 0x66, 0xa7, 0xc5, 0x01, 0x46, 0xf2, 0x29, 0x7c, 0x3c, 0x27, 0xac, 0xd8, 0x8c, 0xe0, 0x10, 0x8b, ]), bytes_to_words_6([ 0xd1, 0x50, 0x2d, 0x6a, 0x79, 0xb4, 0x93, 0xc5, 0x35, 0x00, 0xc2, 0x36, 0xba, 0x26, 0xab, 0xad, 0x8f, 0x57, 0x91, 0x23, 0xe6, 0xc1, 0x0e, 0xc9, ]), bytes_to_words_6([ 0xf4, 0xa0, 0x60, 0xd3, 0xe2, 0x85, 0x2b, 0x9a, 0xd9, 0x7f, 0xe4, 0xb4, 0x58, 0x70, 0x33, 0x8a, 0x3f, 0xcc, 0x47, 0xb1, 0xf1, 0xd1, 0x0c, 0xd2, ]), bytes_to_words_6([ 0xfd, 0x28, 0x15, 0xbd, 0x21, 0xdd, 0x0a, 0xea, 0x78, 0xac, 0x0b, 0xe6, 0xd9, 0xb1, 0x34, 0xe0, 0xc2, 0x50, 0x73, 0xd9, 0x42, 0x5b, 0xea, 0x4e, ]), bytes_to_words_6([ 0x8e, 0x2d, 0x99, 0x28, 0xf2, 0x3e, 0x8b, 0xf3, 0xed, 0x62, 0x8f, 0xf8, 0x88, 0x39, 0x6e, 0x74, 0x9e, 0x55, 0xae, 0x66, 0xf5, 0x9a, 0x84, 0x6c, ]), bytes_to_words_6([ 0x7f, 0xc4, 0x7b, 0x8b, 0x66, 0xd5, 0xd3, 0xdc, 0x47, 0xac, 0x7f, 0x28, 0x58, 0xb9, 0x3b, 0xa0, 0x46, 0xa4, 0x6e, 0x82, 0x6b, 0x8f, 0x3a, 0xa9, ]), bytes_to_words_6([ 0x6a, 0x9b, 0x98, 0x75, 0x46, 0x04, 0xea, 0x7c, 0xbc, 0xc8, 0xb9, 0xb4, 0xba, 0xb9, 0x43, 0xda, 0xcf, 0x60, 0x21, 0x9c, 0xb1, 0xd4, 0xed, 0x67, ]), bytes_to_words_6([ 0x1c, 0x32, 0x0a, 0xf7, 0xae, 0x84, 0x83, 0x75, 0xeb, 0x9c, 0xc7, 0xb0, 0xec, 0x30, 0x45, 0xbe, 0x79, 0xfd, 0x11, 0x7c, 0xcd, 0x26, 0x97, 0x5e, ]), bytes_to_words_6([ 0x3c, 0x2d, 0x4a, 0x35, 0x2e, 0x10, 0x3c, 0x3d, 0x76, 0x89, 0xb3, 0xac, 0xf2, 0xcc, 0x56, 0xd0, 0xed, 0x7a, 0x6f, 0x58, 0x76, 0xec, 0x40, 0x96, ]), bytes_to_words_6([ 0x1a, 0x5a, 0xad, 0x8c, 0xe1, 0x08, 0xa7, 0xcb, 0x3b, 0xf1, 0x1b, 0x01, 0x1c, 0xb6, 0x0e, 0x47, 0xf3, 0x45, 0x87, 0xf3, 0xf7, 0x95, 0x47, 0x72, ]), bytes_to_words_6([ 0x86, 0xe5, 0x24, 0xa6, 0x0d, 0xfa, 0xef, 0x82, 0xfc, 0x6c, 0x8d, 0xa1, 0x81, 0x95, 0x85, 0x58, 0x93, 0x27, 0xf6, 0x29, 0x69, 0xc9, 0x77, 0xb7, ]), bytes_to_words_6([ 0xe9, 0x4a, 0xe9, 0xbf, 0xae, 0x42, 0x14, 0x93, 0xfc, 0xb7, 0x14, 0x38, 0x47, 0x2f, 0x0d, 0x03, 0x7c, 0x82, 0x43, 0xe1, 0x6e, 0x29, 0x75, 0x3f, ]), bytes_to_words_6([ 0xd4, 0x9c, 0xc3, 0xdd, 0xc5, 0x59, 0x7b, 0x23, 0x87, 0xe7, 0x03, 0xa9, 0x9a, 0xc9, 0x97, 0x73, 0x13, 0xfa, 0xa7, 0x19, 0x5b, 0x41, 0xda, 0x72, ]), bytes_to_words_6([ 0x6c, 0xe0, 0x02, 0xa4, 0xe9, 0x27, 0x72, 0xf4, 0xea, 0x74, 0xf4, 0xe9, 0x09, 0xbf, 0x80, 0x28, 0xfd, 0xd7, 0x7f, 0x8a, 0x09, 0xc0, 0x60, 0x51, ]), bytes_to_words_6([ 0x19, 0xc7, 0xb9, 0x88, 0x70, 0x58, 0xd5, 0x45, 0x6b, 0xba, 0x3c, 0x62, 0x80, 0x27, 0xc8, 0x8d, 0xf7, 0xa8, 0xf7, 0xa9, 0xfe, 0xf5, 0xa6, 0x41, ]), bytes_to_words_6([ 0x9a, 0x5b, 0x69, 0xed, 0xc4, 0xac, 0x81, 0x98, 0x1f, 0xeb, 0x40, 0xb8, 0xc7, 0xa9, 0xa7, 0x6d, 0x1c, 0x5a, 0x81, 0x72, 0x17, 0xcb, 0xa8, 0xf8, ]), bytes_to_words_6([ 0x5c, 0x67, 0xb8, 0x99, 0x6f, 0x89, 0xda, 0x71, 0x20, 0xae, 0x5e, 0xe6, 0x2c, 0x16, 0xab, 0x59, 0x1c, 0x81, 0xb5, 0x82, 0xc6, 0x88, 0x6f, 0x6e, ]), bytes_to_words_6([ 0x7f, 0xca, 0xf9, 0x20, 0xad, 0xd6, 0xe6, 0x0d, 0x89, 0xb9, 0xf9, 0xa1, 0x32, 0xcf, 0x69, 0xbb, 0xf8, 0x73, 0xf5, 0x80, 0xc9, 0x69, 0x63, 0xf4, ]), bytes_to_words_6([ 0x01, 0x9d, 0x0d, 0x47, 0x23, 0xdd, 0xc6, 0x64, 0xd7, 0x7d, 0xcc, 0x4d, 0x5f, 0x5b, 0x6d, 0x14, 0xa6, 0x9a, 0xe2, 0x2b, 0x36, 0x3c, 0x61, 0x48, ]), bytes_to_words_6([ 0x7f, 0xe2, 0xb3, 0xcb, 0xa1, 0x23, 0x2b, 0x2f, 0x94, 0x2e, 0x0e, 0x33, 0x04, 0x40, 0xd4, 0xd3, 0x1b, 0x68, 0xdc, 0xe4, 0x83, 0x4a, 0xd7, 0x28, ]), bytes_to_words_6([ 0xf0, 0x45, 0xa8, 0x69, 0x91, 0x8c, 0x0f, 0x7f, 0x11, 0x6c, 0x06, 0xf7, 0x03, 0xcb, 0x76, 0x9b, 0x6a, 0x6c, 0x36, 0x20, 0x77, 0xcf, 0xf4, 0x4f, ]), bytes_to_words_6([ 0x81, 0x03, 0xed, 0xe3, 0x52, 0x13, 0xcb, 0x73, 0x98, 0x0e, 0x15, 0xd9, 0xa6, 0x32, 0xdb, 0xcd, 0xaa, 0x77, 0xa8, 0xdb, 0x71, 0xc4, 0x63, 0xd7, ]), bytes_to_words_6([ 0xb5, 0x1f, 0x08, 0xcb, 0x63, 0x81, 0x18, 0x3e, 0xa1, 0x35, 0x13, 0xbe, 0xea, 0x35, 0x6a, 0xcd, 0x5a, 0x35, 0xc4, 0x4f, 0x57, 0x82, 0xdc, 0xbf, ]), bytes_to_words_6([ 0xd2, 0xf2, 0x32, 0x3b, 0xbb, 0x5c, 0x57, 0x71, 0x72, 0xfd, 0x27, 0xf3, 0x70, 0x96, 0x9d, 0xf5, 0x91, 0x0a, 0x9e, 0x0e, 0xb9, 0x9c, 0xd0, 0x29, ]), bytes_to_words_6([ 0x3b, 0xae, 0x2c, 0x0d, 0xeb, 0x53, 0x95, 0x20, 0x71, 0xc7, 0x0d, 0xd5, 0x19, 0x46, 0x9f, 0x55, 0x24, 0xec, 0x52, 0xde, 0x83, 0xe1, 0x0d, 0x28, ]), bytes_to_words_6([ 0x5a, 0x60, 0x9b, 0xcb, 0x30, 0x30, 0xe7, 0xdd, 0xdc, 0x50, 0x30, 0xb6, 0x68, 0xe3, 0xfb, 0x84, 0x41, 0x90, 0x18, 0x3f, 0xd5, 0xa1, 0x1e, 0xe4, ]), bytes_to_words_6([ 0xb4, 0xce, 0x3e, 0x30, 0xb6, 0x24, 0xae, 0x97, 0x70, 0x5f, 0xac, 0x89, 0x1c, 0x7e, 0x22, 0x6e, 0x2e, 0x0d, 0xfd, 0xd3, 0x12, 0x7e, 0xfe, 0x7d, ]), bytes_to_words_6([ 0x80, 0x51, 0x45, 0x80, 0x62, 0xfd, 0xa1, 0xff, 0x6e, 0x81, 0x70, 0x39, 0x43, 0xf5, 0xb7, 0xd2, 0x39, 0xa2, 0xfc, 0xee, 0x1d, 0xd2, 0xc0, 0x4f, ]), bytes_to_words_6([ 0x43, 0x72, 0xfd, 0x39, 0xf2, 0xaa, 0x8b, 0x76, 0xda, 0x11, 0x2a, 0xb7, 0x28, 0x4e, 0xc2, 0xff, 0xce, 0xde, 0x59, 0x5e, 0x87, 0xd8, 0x42, 0x1a, ]), bytes_to_words_6([ 0x3f, 0xbe, 0x60, 0x0b, 0x2f, 0x2a, 0x0f, 0x44, 0x12, 0xde, 0xcf, 0x64, 0xb7, 0x97, 0xb7, 0x1d, 0xb2, 0x46, 0xfc, 0xdd, 0x46, 0xca, 0xf9, 0x11, ]), ]; const PATH: [[U32<LittleEndian>; 6]; 15] = [ bytes_to_words_6([ 0xbe, 0x59, 0x73, 0xbc, 0xe7, 0x93, 0x5f, 0x53, 0x40, 0xe9, 0x26, 0xa9, 0xfc, 0xb3, 0xcb, 0x9d, 0x2d, 0x29, 0x22, 0x19, 0x28, 0xd3, 0x77, 0x01, ]), bytes_to_words_6([ 0xac, 0xca, 0x20, 0x2f, 0x08, 0x49, 0x75, 0x99, 0xf8, 0x3e, 0xd4, 0x24, 0xff, 0x25, 0xd2, 0xa8, 0xb6, 0x16, 0xf1, 0xe2, 0x48, 0xf0, 0xf1, 0xba, ]), bytes_to_words_6([ 0xcd, 0xd8, 0x16, 0x9b, 0x7e, 0x86, 0xba, 0x21, 0xd1, 0x59, 0xaa, 0x85, 0x62, 0x2e, 0x9d, 0x21, 0x7c, 0x74, 0x76, 0xd5, 0xf3, 0xa7, 0xcd, 0xfb, ]), bytes_to_words_6([ 0xeb, 0x44, 0x55, 0x41, 0xa7, 0xa5, 0xa3, 0xab, 0x78, 0x92, 0xb3, 0x71, 0x81, 0x43, 0x94, 0x6e, 0xa0, 0xc1, 0xe4, 0xff, 0x83, 0x7f, 0xb0, 0xf3, ]), bytes_to_words_6([ 0x68, 0xfe, 0xed, 0x20, 0xc9, 0x09, 0x01, 0xc1, 0xda, 0xcd, 0xf3, 0x0b, 0x90, 0xd3, 0x3f, 0x6f, 0x4b, 0x17, 0x93, 0xa5, 0x57, 0x06, 0xc5, 0x43, ]), bytes_to_words_6([ 0x3a, 0x01, 0x82, 0x46, 0xba, 0xe1, 0x03, 0xe7, 0x97, 0x94, 0xfc, 0x1f, 0xa5, 0xc2, 0x03, 0xfd, 0x8b, 0xf0, 0xc7, 0x77, 0xb4, 0x07, 0xaa, 0xde, ]), bytes_to_words_6([ 0xa1, 0x63, 0x82, 0xeb, 0x04, 0x9d, 0x45, 0x83, 0x62, 0xf7, 0xb6, 0x3e, 0x30, 0x04, 0xf9, 0x2c, 0x92, 0x66, 0x0e, 0x63, 0x17, 0x18, 0xf7, 0x60, ]), bytes_to_words_6([ 0x08, 0x42, 0x49, 0x45, 0x57, 0xac, 0x9b, 0x94, 0x7a, 0x21, 0x46, 0xb1, 0x22, 0xd2, 0xe7, 0x5f, 0x3a, 0x3d, 0x75, 0x9e, 0x5a, 0xba, 0xee, 0x58, ]), bytes_to_words_6([ 0x1c, 0xbb, 0xea, 0x87, 0xbc, 0x7a, 0xf8, 0xfe, 0x78, 0xc7, 0x0c, 0x66, 0x00, 0x41, 0xc5, 0x3e, 0xda, 0xcf, 0x17, 0x3d, 0x95, 0x7a, 0x2c, 0xe1, ]), bytes_to_words_6([ 0xaa, 0x37, 0x7c, 0x8c, 0x02, 0x5b, 0xb4, 0x98, 0xc7, 0x6d, 0x96, 0x07, 0x21, 0x44, 0x82, 0x06, 0x7d, 0xe2, 0xb5, 0x4a, 0x0e, 0xf4, 0xec, 0xec, ]), bytes_to_words_6([ 0x50, 0x86, 0x6a, 0x67, 0x69, 0xe6, 0xef, 0xb3, 0x9d, 0xaf, 0x9e, 0xc4, 0xaf, 0x6c, 0xe9, 0x3b, 0xe8, 0x72, 0x3d, 0x8c, 0xa5, 0xd8, 0x98, 0x07, ]), bytes_to_words_6([ 0x4b, 0xe3, 0x74, 0xde, 0xa1, 0x9a, 0x32, 0x52, 0xf9, 0xc5, 0xbe, 0x94, 0x37, 0x97, 0xf7, 0xa1, 0x01, 0xb7, 0x43, 0x68, 0xe6, 0x6f, 0x2f, 0x55, ]), bytes_to_words_6([ 0x1e, 0xec, 0xde, 0xb6, 0xde, 0xcb, 0x87, 0x2d, 0x70, 0x47, 0x59, 0x93, 0x50, 0xc2, 0x06, 0xaf, 0x36, 0xb2, 0x09, 0x63, 0xb9, 0x7e, 0xc6, 0x87, ]), bytes_to_words_6([ 0x25, 0xf0, 0x11, 0x78, 0x5c, 0x1f, 0xe2, 0x2d, 0xee, 0x81, 0xe8, 0x1f, 0x60, 0x8a, 0x76, 0xb7, 0xac, 0x8b, 0xb9, 0xc3, 0xf1, 0xac, 0x68, 0x4f, ]), bytes_to_words_6([ 0x73, 0xd6, 0x27, 0xd5, 0x6a, 0xf2, 0x6e, 0x31, 0x2d, 0xbf, 0xf6, 0x7f, 0x94, 0x0a, 0x83, 0x0a, 0xd5, 0x38, 0x67, 0x4b, 0xc5, 0x9b, 0x4e, 0x39, ]), ]; let lms_sig = LmsSignature { q: Q.into(), ots: LmotsSignature { ots_type: LMOTS_TYPE, nonce: NONCE, y: Y, }, tree_type: LMS_TYPE, tree_path: PATH, }; const LMS_PUBLIC_KEY: LmsPublicKey<6> = LmsPublicKey { id: LMS_IDENTIFIER, digest: LMS_PUBLIC_HASH, tree_type: LMS_TYPE, otstype: LMOTS_TYPE, }; let result = Lms::default() .verify_lms_signature(&mut sha256, &MESSAGE, &LMS_PUBLIC_KEY, &lms_sig) .unwrap(); assert_eq!(result, LmsResult::Success); let new_message = "this is a different message".as_bytes(); let result = Lms::default() .verify_lms_signature(&mut sha256, &new_message, &LMS_PUBLIC_KEY, &lms_sig) .unwrap(); assert_ne!(result, LmsResult::Success); let new_lms: LmsIdentifier = [0u8; 16]; let new_lms_public_key = LmsPublicKey { id: new_lms, ..LMS_PUBLIC_KEY }; let result = Lms::default() .verify_lms_signature(&mut sha256, &MESSAGE, &new_lms_public_key, &lms_sig) .unwrap(); assert_ne!(result, LmsResult::Success); let new_q = Q + 1; let new_lms_sig = LmsSignature { q: new_q.into(), ..lms_sig }; let result = Lms::default() .verify_lms_signature(&mut sha256, &MESSAGE, &LMS_PUBLIC_KEY, &new_lms_sig) .unwrap(); assert_ne!(result, LmsResult::Success); let new_public_key = LmsPublicKey { digest: [U32::ZERO; 6], ..LMS_PUBLIC_KEY }; let result = Lms::default() .verify_lms_signature(&mut sha256, &MESSAGE, &new_public_key, &lms_sig) .unwrap(); assert_ne!(result, LmsResult::Success); let new_lms_sig = LmsSignature { tree_path: [[U32::ZERO; 6]; 15], ..lms_sig }; let result = Lms::default() .verify_lms_signature(&mut sha256, &MESSAGE, &LMS_PUBLIC_KEY, &new_lms_sig) .unwrap(); assert_ne!(result, LmsResult::Success); assert_eq!( Lms::default().verify_lms_signature( &mut sha256, &MESSAGE, &new_public_key, &LmsSignature { tree_type: LmsAlgorithmType::new(12345), ..lms_sig } ), Err(CaliptraError::DRIVER_LMS_INVALID_LMS_ALGO_TYPE) ); assert_eq!( Lms::default().verify_lms_signature( &mut sha256, &MESSAGE, &LmsPublicKey { otstype: LmotsAlgorithmType::new(23456), ..new_public_key }, &LmsSignature { ots: LmotsSignature { ots_type: LmotsAlgorithmType::new(23456), ..lms_sig.ots }, ..lms_sig } ), Err(CaliptraError::DRIVER_LMS_INVALID_LMOTS_ALGO_TYPE) ); // TODO: Maybe this should just be INVALID_LMOTS_ALGORITHM_TYPE? assert_eq!( Lms::default().verify_lms_signature( &mut sha256, &MESSAGE, &LmsPublicKey { otstype: LmotsAlgorithmType::LmotsSha256N32W4, ..new_public_key }, &LmsSignature { ots: LmotsSignature { ots_type: LmotsAlgorithmType::LmotsSha256N32W4, ..lms_sig.ots }, ..lms_sig } ), Err(CaliptraError::DRIVER_LMS_INVALID_PVALUE) ); assert_eq!( Lms::default().verify_lms_signature_generic( &mut sha256, &MESSAGE, &LmsPublicKey { otstype: LmotsAlgorithmType::LmotsSha256N32W8, ..new_public_key }, &LmsSignature { q: Q.into(), ots: LmotsSignature { ots_type: LmotsAlgorithmType::LmotsSha256N32W8, nonce: NONCE, y: [Default::default(); 34], }, tree_type: LMS_TYPE, tree_path: PATH, } ), Err(CaliptraError::DRIVER_LMS_INVALID_HASH_WIDTH) ); assert_eq!( Lms::default().verify_lms_signature( &mut sha256, &MESSAGE, &LmsPublicKey { otstype: LmotsAlgorithmType::LmotsSha256N32W4, ..new_public_key }, &LmsSignature { q: Q.into(), ots: LmotsSignature { ots_type: LmotsAlgorithmType::LmotsSha256N32W8, ..lms_sig.ots }, ..lms_sig } ), Err(CaliptraError::DRIVER_LMS_SIGNATURE_LMOTS_DOESNT_MATCH_PUBKEY_LMOTS) ); assert_eq!( Lms::default().verify_lms_signature( &mut sha256, &MESSAGE, &LmsPublicKey { tree_type: LmsAlgorithmType::LmsSha256N24H10, ..new_public_key }, &LmsSignature { q: Q.into(), tree_type: LmsAlgorithmType::LmsSha256N24H20, ..lms_sig } ), Err(CaliptraError::DRIVER_LMS_INVALID_TREE_HEIGHT) ); } test_suite! { test_failures_lms_24, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/aes_tests.rs
drivers/test-fw/src/bin/aes_tests.rs
// Licensed under the Apache-2.0 license #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{ Aes, AesKey, Array4x12, Ecc384, Ecc384PrivKeyOut, Ecc384Scalar, Ecc384Seed, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, Trng, }; use caliptra_registers::aes::AesReg; use caliptra_registers::aes_clp::AesClpReg; use caliptra_registers::csrng::CsrngReg; use caliptra_registers::ecc::EccReg; use caliptra_registers::entropy_src::EntropySrcReg; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_registers::soc_ifc_trng::SocIfcTrngReg; use caliptra_test_harness::test_suite; use zerocopy::transmute; // From NIST example vector const KEY_EMPTY: [u8; 32] = [ 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4, ]; const EXPECTED_MAC_EMPTY: [u8; 16] = [ 0x02, 0x89, 0x62, 0xf6, 0x1b, 0x7b, 0xf8, 0x9e, 0xfc, 0x6b, 0x55, 0x1f, 0x46, 0x67, 0xd9, 0x83, ]; // From ACVP test vector const KEY_4256: [u8; 32] = [ 0xbb, 0x2e, 0xd8, 0x64, 0xae, 0xa7, 0xd3, 0xea, 0x26, 0x9a, 0x19, 0xda, 0x45, 0x93, 0x32, 0xff, 0x19, 0x2e, 0x79, 0x88, 0x99, 0x32, 0xb5, 0x3e, 0xe1, 0x87, 0xa1, 0x41, 0xa3, 0xd9, 0x38, 0xd8, ]; const M_4256: [u8; 532] = [ 0x22, 0x03, 0x0e, 0x8c, 0xf9, 0xdb, 0xdb, 0x8d, 0xe4, 0x2a, 0xa1, 0xb9, 0x87, 0xf5, 0x73, 0x4f, 0xb5, 0x33, 0x1e, 0x22, 0x44, 0xb5, 0x77, 0xec, 0xd0, 0x8e, 0xaf, 0x1b, 0x57, 0x37, 0x26, 0x4c, 0x9c, 0x2c, 0xff, 0x11, 0x71, 0xbb, 0xae, 0xa1, 0xfb, 0x30, 0x62, 0x91, 0x01, 0xd5, 0x52, 0x28, 0x7e, 0x12, 0xfe, 0xcc, 0xa1, 0x76, 0x4f, 0x22, 0x15, 0x7f, 0x48, 0xa7, 0x7d, 0xd6, 0xbe, 0x46, 0xbb, 0xa3, 0x8f, 0xda, 0x1e, 0xf1, 0x61, 0xb3, 0x00, 0xc0, 0x99, 0x94, 0xd8, 0x8d, 0x6b, 0x19, 0x36, 0x2d, 0xf2, 0x15, 0x7d, 0xe1, 0xef, 0x2b, 0x06, 0x1d, 0x03, 0xd3, 0x6f, 0xae, 0x62, 0x94, 0xc5, 0x3a, 0x1e, 0x6d, 0xee, 0x89, 0x55, 0x70, 0x28, 0x7c, 0xae, 0x91, 0xa2, 0x56, 0x40, 0x19, 0x52, 0xb8, 0x56, 0xdf, 0x6b, 0x83, 0x80, 0xda, 0x10, 0x7d, 0x63, 0x73, 0x62, 0x89, 0x30, 0xae, 0x51, 0x3b, 0xeb, 0x18, 0xa6, 0xbe, 0xd1, 0x8d, 0x0c, 0x5d, 0x99, 0xfe, 0xbc, 0xff, 0xa9, 0x6a, 0x91, 0x65, 0x5c, 0xa0, 0x5d, 0xb3, 0xd0, 0xb0, 0x52, 0xc5, 0x2b, 0xbf, 0x16, 0x62, 0xce, 0xc1, 0x7b, 0x6a, 0x90, 0x4b, 0xc1, 0xd1, 0x7e, 0xaf, 0x58, 0xb3, 0x93, 0x3b, 0x34, 0xd3, 0x9f, 0x3b, 0x3d, 0x7a, 0xd5, 0x30, 0x4b, 0xac, 0x19, 0xe1, 0x87, 0xac, 0xea, 0x25, 0x6d, 0x29, 0x40, 0x9f, 0x99, 0xcd, 0xd1, 0x5c, 0x3b, 0xe6, 0xe5, 0x67, 0x95, 0xa8, 0x4c, 0x77, 0x95, 0x57, 0x5d, 0x3c, 0xea, 0x99, 0xe9, 0x57, 0x01, 0x67, 0x8e, 0x4c, 0xc7, 0xcb, 0x32, 0xa6, 0x39, 0x14, 0x57, 0xa5, 0x2a, 0x28, 0x93, 0x92, 0x0f, 0x8a, 0xd5, 0x26, 0xd2, 0xd7, 0x98, 0xd9, 0xf9, 0xe0, 0xad, 0xb9, 0x53, 0x23, 0x39, 0xc5, 0xcf, 0x6b, 0xc8, 0x2d, 0x5f, 0xe1, 0xe6, 0x10, 0x0d, 0xb7, 0x3e, 0x2e, 0x81, 0x45, 0x58, 0x43, 0x11, 0xb1, 0x5f, 0x24, 0x5e, 0xb8, 0xc3, 0xc9, 0x94, 0xee, 0x2d, 0xad, 0xdc, 0x3f, 0x5e, 0x77, 0x42, 0xd9, 0xeb, 0x82, 0x6c, 0xa5, 0x43, 0x6f, 0xae, 0x33, 0xdf, 0x95, 0xa1, 0x2d, 0xc8, 0x26, 0x8e, 0x8a, 0xf9, 0xb1, 0x9b, 0x7c, 0x9e, 0xba, 0xee, 0x34, 0xd2, 0xa3, 0x50, 0x94, 0x44, 0xec, 0x4c, 0xdf, 0x5b, 0x4a, 0x6c, 0xe6, 0xce, 0x0b, 0x63, 0xfb, 0xa0, 0xfd, 0x73, 0xb1, 0xfe, 0x67, 0x91, 0x7e, 0x42, 0x20, 0x2c, 0xaa, 0x57, 0x9d, 0x24, 0x57, 0x69, 0x3a, 0xb0, 0xa6, 0x6a, 0x4e, 0x31, 0x52, 0x46, 0x9f, 0x94, 0x5a, 0xa5, 0xd0, 0xab, 0x26, 0x5c, 0xf3, 0x1a, 0xc2, 0x12, 0x58, 0x6f, 0x82, 0x49, 0xba, 0xe3, 0x75, 0x3f, 0x93, 0x7f, 0xef, 0xa4, 0x12, 0xb7, 0x79, 0x31, 0xbf, 0xee, 0xba, 0xc0, 0x85, 0x09, 0x6d, 0xe9, 0xdb, 0x39, 0x25, 0x96, 0x6c, 0x3e, 0xd7, 0x8c, 0xc8, 0x69, 0x20, 0xb3, 0xe1, 0x66, 0x58, 0x09, 0xf1, 0xd8, 0x50, 0x0d, 0x7d, 0x35, 0xde, 0xf6, 0x41, 0x92, 0x9a, 0xca, 0xa6, 0x8b, 0x7c, 0x79, 0x22, 0x63, 0xaf, 0x13, 0xed, 0x66, 0x17, 0xe4, 0x8c, 0x6c, 0xda, 0xf0, 0xae, 0xba, 0xc3, 0x5a, 0xb9, 0x61, 0x4c, 0x01, 0x82, 0x90, 0x4d, 0x8b, 0x4d, 0x13, 0xfc, 0x83, 0x22, 0x64, 0xf9, 0xa3, 0x5a, 0xcf, 0x6e, 0xa4, 0xc0, 0x12, 0x6b, 0x3d, 0xd9, 0xd3, 0x9d, 0xca, 0xc1, 0x2b, 0x09, 0x3e, 0x15, 0xbd, 0x2f, 0xa0, 0x2f, 0xd7, 0x48, 0x91, 0x08, 0x70, 0x25, 0x58, 0xa4, 0xf1, 0xb7, 0x2a, 0x37, 0x9c, 0x1c, 0xb8, 0xf8, 0xd8, 0x17, 0xe8, 0x02, 0x7b, 0xd8, 0xca, 0x21, 0x55, 0xfc, 0x72, 0x6b, 0xa1, 0x75, 0xd9, 0x8f, 0x31, 0x3f, 0x77, 0x87, 0x66, 0x7d, 0xd8, 0xfa, 0x6d, 0xb9, 0xb2, 0x9d, 0xbf, 0x1f, 0xbd, 0x9e, 0x75, 0xdf, 0x8b, 0x96, 0xbe, 0xd1, 0x6f, 0x4e, 0xcf, 0xf7, 0x85, 0x49, 0x20, 0xc6, 0x5d, 0xa4, 0x55, 0xea, 0x57, 0x59, ]; const EXPECTED_MAC_4256: [u8; 16] = [ 0x80, 0xea, 0x8c, 0x7c, 0xa9, 0xa5, 0xea, 0x0e, 0x86, 0x49, 0x84, 0x1b, 0xfe, 0x16, 0x67, 0x67, ]; fn test_cmac() { let mut aes = unsafe { Aes::new(AesReg::new(), AesClpReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // Init CFI let mut entropy_gen = || trng.generate4(); CfiCounter::reset(&mut entropy_gen); let key = KEY_EMPTY.into(); let mac = aes.cmac(AesKey::Array(&key), &[]).unwrap(); assert_eq!(mac, EXPECTED_MAC_EMPTY.into(), "AES CMAC mismatch"); let key = KEY_4256.into(); let mac = aes.cmac(AesKey::Array(&key), &M_4256).unwrap(); assert_eq!(mac, EXPECTED_MAC_4256.into(), "AES CMAC mismatch"); } fn test_cmac_kv() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // Load a key into the key vault. let seed = [0u8; 48]; let key_out_1 = KeyWriteArgs { id: KeyId::KeyId0, usage: KeyUsage::default() .set_ecc_key_gen_seed_en() .set_ecc_private_key_en() .set_aes_key_en(), }; let result = ecc.key_pair( Ecc384Seed::from(&Ecc384Scalar::from(seed)), &Array4x12::default(), &mut trng, Ecc384PrivKeyOut::from(key_out_1), ); assert!(result.is_ok()); let mut aes = unsafe { Aes::new(AesReg::new(), AesClpReg::new()) }; // this is the expected derived key from the above seed. let key: [u8; 48] = [ 0xfe, 0xee, 0xf5, 0x54, 0x4a, 0x76, 0x56, 0x49, 0x90, 0x12, 0x8a, 0xd1, 0x89, 0xe8, 0x73, 0xf2, 0x1f, 0xd, 0xfd, 0x5a, 0xd7, 0xe2, 0xfa, 0x86, 0x11, 0x27, 0xee, 0x6e, 0x39, 0x4c, 0xa7, 0x84, 0x87, 0x1c, 0x1a, 0xec, 0x3, 0x2c, 0x7a, 0x8b, 0x10, 0xb9, 0x3e, 0xe, 0xab, 0x89, 0x46, 0xd6, ]; let key: [u8; 32] = key[0..32].try_into().unwrap(); let key = transmute!(key); let mac1 = aes.cmac(AesKey::Array(&key), &[]).unwrap(); let mac2 = aes .cmac(AesKey::KV(KeyReadArgs::new(KeyId::KeyId0)), &[]) .unwrap(); assert_eq!(mac1, mac2, "AES CMAC mismatch"); } test_suite! { test_cmac, test_cmac_kv, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/error_reporter_tests.rs
drivers/test-fw/src/bin/error_reporter_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: error_reporter_tests.rs Abstract: File contains test cases for HMAC-384 API --*/ #![no_std] #![no_main] use caliptra_drivers::{ clear_fw_error_non_fatal, get_fw_error_non_fatal, report_fw_error_fatal, report_fw_error_non_fatal, PersistentDataAccessor, }; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_test_harness::test_suite; fn test_report_fw_error() { let v: u32 = 0xdead0; report_fw_error_non_fatal(v); assert_eq!(v, get_fw_error_non_fatal()); } fn test_clear_fw_error_non_fatal() { let err1: u32 = 0xdead1; let err2: u32 = 0xdead2; let mut persistent_data_accessor = unsafe { PersistentDataAccessor::new() }; let persistent_data = persistent_data_accessor.get_mut(); report_fw_error_non_fatal(err1); assert_eq!(err1, get_fw_error_non_fatal()); // Ensure clear function zeros the fw_non_fatal_error and stores it in persistent data correctly clear_fw_error_non_fatal(persistent_data); assert_eq!(0, get_fw_error_non_fatal()); assert_eq!(err1, persistent_data.rom.cleared_non_fatal_fw_error); // Write a new error report_fw_error_non_fatal(err2); assert_eq!(err2, get_fw_error_non_fatal()); clear_fw_error_non_fatal(persistent_data); assert_eq!(0, get_fw_error_non_fatal()); assert_eq!(err2, persistent_data.rom.cleared_non_fatal_fw_error); // Repeatedly clearing should not overwrite the stored previous error when no error is present clear_fw_error_non_fatal(persistent_data); clear_fw_error_non_fatal(persistent_data); assert_eq!(0, get_fw_error_non_fatal()); assert_eq!(err2, persistent_data.rom.cleared_non_fatal_fw_error); } fn test_report_fw_error_fatal() { let v: u32 = 0xdead1; report_fw_error_fatal(v); assert_eq!(v, retrieve_fw_error_fatal()); } fn retrieve_fw_error_fatal() -> u32 { let soc_ifc = unsafe { SocIfcReg::new() }; soc_ifc.regs().cptra_fw_error_fatal().read() } test_suite! { test_report_fw_error, test_clear_fw_error_non_fatal, test_report_fw_error_fatal, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/csrng_pass_health_tests.rs
drivers/test-fw/src/bin/csrng_pass_health_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: csrng_pass_health_tests.rs Abstract: https://opentitan.org/book/hw/ip/entropy_src/index.html#description The test cases in this file should pass entropy health tests. --*/ #![no_std] #![no_main] use caliptra_drivers::Csrng; use caliptra_registers::{csrng::CsrngReg, entropy_src::EntropySrcReg, soc_ifc::SocIfcReg}; use caliptra_test_harness::test_suite; fn test_boot_and_generate_pass() { let csrng_reg = unsafe { CsrngReg::new() }; let entropy_src_reg = unsafe { EntropySrcReg::new() }; let soc_ifc_reg = unsafe { SocIfcReg::new() }; let mut csrng = Csrng::new(csrng_reg, entropy_src_reg, &soc_ifc_reg) .expect("CSRNG should pass boot-time health test"); let _ = csrng .generate12() .expect("CSRNG should pass continuous health tests (first generate)"); let _ = csrng .generate12() .expect("CSRNG should pass continuous health tests (second generate)"); } test_suite! { test_boot_and_generate_pass, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/ecc384_tests.rs
drivers/test-fw/src/bin/ecc384_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: ecc384_tests.rs Abstract: File contains test cases for ECC-384 API tests --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{ Array4x12, Ecc384, Ecc384PrivKeyIn, Ecc384PrivKeyOut, Ecc384PubKey, Ecc384Result, Ecc384Scalar, Ecc384Seed, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, Trng, }; use caliptra_error::CaliptraError; use caliptra_kat::{Ecc384Kat, EcdhKat}; use caliptra_registers::csrng::CsrngReg; use caliptra_registers::ecc::EccReg; use caliptra_registers::entropy_src::EntropySrcReg; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_registers::soc_ifc_trng::SocIfcTrngReg; use caliptra_test_harness::test_suite; const PRIV_KEY: [u8; 48] = [ 0xfe, 0xee, 0xf5, 0x54, 0x4a, 0x76, 0x56, 0x49, 0x90, 0x12, 0x8a, 0xd1, 0x89, 0xe8, 0x73, 0xf2, 0x1f, 0xd, 0xfd, 0x5a, 0xd7, 0xe2, 0xfa, 0x86, 0x11, 0x27, 0xee, 0x6e, 0x39, 0x4c, 0xa7, 0x84, 0x87, 0x1c, 0x1a, 0xec, 0x3, 0x2c, 0x7a, 0x8b, 0x10, 0xb9, 0x3e, 0xe, 0xab, 0x89, 0x46, 0xd6, ]; const PUB_KEY_X: [u8; 48] = [ 0xd7, 0xdd, 0x94, 0xe0, 0xbf, 0xfc, 0x4c, 0xad, 0xe9, 0x90, 0x2b, 0x7f, 0xdb, 0x15, 0x42, 0x60, 0xd5, 0xec, 0x5d, 0xfd, 0x57, 0x95, 0xe, 0x83, 0x59, 0x1, 0x5a, 0x30, 0x2c, 0x8b, 0xf7, 0xbb, 0xa7, 0xe5, 0xf6, 0xdf, 0xfc, 0x16, 0x85, 0x16, 0x2b, 0xdd, 0x35, 0xf9, 0xf5, 0xc1, 0xb0, 0xff, ]; const PUB_KEY_Y: [u8; 48] = [ 0xbb, 0x9c, 0x3a, 0x2f, 0x6, 0x1e, 0x8d, 0x70, 0x14, 0x27, 0x8d, 0xd5, 0x1e, 0x66, 0xa9, 0x18, 0xa6, 0xb6, 0xf9, 0xf1, 0xc1, 0x93, 0x73, 0x12, 0xd4, 0xe7, 0xa9, 0x21, 0xb1, 0x8e, 0xf0, 0xf4, 0x1f, 0xdd, 0x40, 0x1d, 0x9e, 0x77, 0x18, 0x50, 0x9f, 0x87, 0x31, 0xe9, 0xee, 0xc9, 0xc3, 0x1d, ]; const SIGNATURE_R: [u8; 48] = [ 0x93, 0x79, 0x9d, 0x55, 0x12, 0x26, 0x36, 0x28, 0x34, 0xf6, 0xf, 0x7b, 0x94, 0x52, 0x90, 0xb7, 0xcc, 0xe6, 0xe9, 0x96, 0x1, 0xfb, 0x7e, 0xbd, 0x2, 0x6c, 0x2e, 0x3c, 0x44, 0x5d, 0x3c, 0xd9, 0xb6, 0x50, 0x68, 0xda, 0xc0, 0xa8, 0x48, 0xbe, 0x9f, 0x5, 0x60, 0xaa, 0x75, 0x8f, 0xda, 0x27, ]; const SIGNATURE_S: [u8; 48] = [ 0xe5, 0x48, 0xe5, 0x35, 0xa1, 0xcc, 0x60, 0xe, 0x13, 0x3b, 0x55, 0x91, 0xae, 0xba, 0xad, 0x78, 0x5, 0x40, 0x6, 0xd7, 0x52, 0xd0, 0xe1, 0xdf, 0x94, 0xfb, 0xfa, 0x95, 0xd7, 0x8f, 0xb, 0x3f, 0x8e, 0x81, 0xb9, 0x11, 0x9c, 0x2b, 0xe0, 0x8, 0xbf, 0x6d, 0x6f, 0x4e, 0x41, 0x85, 0xf8, 0x7d, ]; fn test_gen_key_pair() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let seed = [0u8; 48]; let mut priv_key = Array4x12::default(); let result = ecc.key_pair( Ecc384Seed::from(&Ecc384Scalar::from(seed)), &Array4x12::default(), &mut trng, Ecc384PrivKeyOut::from(&mut priv_key), ); assert!(result.is_ok()); let pub_key = result.unwrap(); assert_eq!(priv_key, Ecc384Scalar::from(PRIV_KEY)); assert_eq!(pub_key.x, Ecc384Scalar::from(PUB_KEY_X)); assert_eq!(pub_key.y, Ecc384Scalar::from(PUB_KEY_Y)); let mut der = [0u8; 97]; der[0] = 0x04; der[01..49].copy_from_slice(&PUB_KEY_X); der[49..97].copy_from_slice(&PUB_KEY_Y); assert_eq!(pub_key.to_der(), der); } fn test_gen_key_pair_with_iv() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let seed = [ 0x8F, 0xA8, 0x54, 0x1C, 0x82, 0xA3, 0x92, 0xCA, 0x74, 0xF2, 0x3E, 0xD1, 0xDB, 0xFD, 0x73, 0x54, 0x1C, 0x59, 0x66, 0x39, 0x1B, 0x97, 0xEA, 0x73, 0xD7, 0x44, 0xB0, 0xE3, 0x4B, 0x9D, 0xF5, 0x9E, 0xD0, 0x15, 0x80, 0x63, 0xE3, 0x9C, 0x09, 0xA5, 0xA0, 0x55, 0x37, 0x1E, 0xDF, 0x7A, 0x54, 0x41, ]; let nonce = [ 0x1B, 0x7E, 0xC5, 0xE5, 0x48, 0xE8, 0xAA, 0xA9, 0x2E, 0xC7, 0x70, 0x97, 0xCA, 0x95, 0x51, 0xC9, 0x78, 0x3C, 0xE6, 0x82, 0xCA, 0x18, 0xFB, 0x1E, 0xDB, 0xD9, 0xF1, 0xE5, 0x0B, 0xC3, 0x82, 0xDB, 0x8A, 0xB3, 0x94, 0x96, 0xC8, 0xEE, 0x42, 0x3F, 0x8C, 0xA1, 0x05, 0xCB, 0xBA, 0x7B, 0x65, 0x88, ]; let priv_key_exp = [ 0xF2, 0x74, 0xF6, 0x9D, 0x16, 0x3B, 0x0C, 0x9F, 0x1F, 0xC3, 0xEB, 0xF4, 0x29, 0x2A, 0xD1, 0xC4, 0xEB, 0x3C, 0xEC, 0x1C, 0x5A, 0x7D, 0xDE, 0x6F, 0x80, 0xC1, 0x42, 0x92, 0x93, 0x4C, 0x20, 0x55, 0xE0, 0x87, 0x74, 0x8D, 0x0A, 0x16, 0x9C, 0x77, 0x24, 0x83, 0xAD, 0xEE, 0x5E, 0xE7, 0x0E, 0x17, ]; let pub_key_x_exp = [ 0xD7, 0x9C, 0x6D, 0x97, 0x2B, 0x34, 0xA1, 0xDF, 0xC9, 0x16, 0xA7, 0xB6, 0xE0, 0xA9, 0x9B, 0x6B, 0x53, 0x87, 0xB3, 0x4D, 0xA2, 0x18, 0x76, 0x07, 0xC1, 0xAD, 0x0A, 0x4D, 0x1A, 0x8C, 0x2E, 0x41, 0x72, 0xAB, 0x5F, 0xA5, 0xD9, 0xAB, 0x58, 0xFE, 0x45, 0xE4, 0x3F, 0x56, 0xBB, 0xB6, 0x6B, 0xA4, ]; let pub_key_y_exp = [ 0x5A, 0x73, 0x63, 0x93, 0x2B, 0x06, 0xB4, 0xF2, 0x23, 0xBE, 0xF0, 0xB6, 0x0A, 0x63, 0x90, 0x26, 0x51, 0x12, 0xDB, 0xBD, 0x0A, 0xAE, 0x67, 0xFE, 0xF2, 0x6B, 0x46, 0x5B, 0xE9, 0x35, 0xB4, 0x8E, 0x45, 0x1E, 0x68, 0xD1, 0x6F, 0x11, 0x18, 0xF2, 0xB3, 0x2B, 0x4C, 0x28, 0x60, 0x87, 0x49, 0xED, ]; let mut priv_key = Array4x12::default(); let result = ecc.key_pair( Ecc384Seed::from(&Ecc384Scalar::from(seed)), &Array4x12::from(nonce), &mut trng, Ecc384PrivKeyOut::from(&mut priv_key), ); assert!(result.is_ok()); let pub_key = result.unwrap(); assert_eq!(priv_key, Ecc384Scalar::from(priv_key_exp)); assert_eq!(pub_key.x, Ecc384Scalar::from(pub_key_x_exp)); assert_eq!(pub_key.y, Ecc384Scalar::from(pub_key_y_exp)); } fn test_sign() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let digest = Array4x12::new([0u32; 12]); let result = ecc.sign( Ecc384PrivKeyIn::from(&Array4x12::from(PRIV_KEY)), &Ecc384PubKey { x: Ecc384Scalar::from(PUB_KEY_X), y: Ecc384Scalar::from(PUB_KEY_Y), }, &digest, &mut trng, ); assert!(result.is_ok()); let signature = result.unwrap(); assert_eq!(signature.r, Ecc384Scalar::from(SIGNATURE_R)); assert_eq!(signature.s, Ecc384Scalar::from(SIGNATURE_S)); } fn test_verify() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let digest = Array4x12::new([0u32; 12]); let result = ecc.sign( Ecc384PrivKeyIn::from(&Array4x12::from(PRIV_KEY)), &Ecc384PubKey { x: Ecc384Scalar::from(PUB_KEY_X), y: Ecc384Scalar::from(PUB_KEY_Y), }, &digest, &mut trng, ); assert!(result.is_ok()); let signature = result.unwrap(); let pub_key = Ecc384PubKey { x: Ecc384Scalar::from(PUB_KEY_X), y: Ecc384Scalar::from(PUB_KEY_Y), }; let result = ecc.verify(&pub_key, &Ecc384Scalar::from(digest), &signature); assert!(result.is_ok()); assert_eq!(result.unwrap(), Ecc384Result::Success); } fn test_verify_r() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let digest = Array4x12::new([0u32; 12]); let result = ecc.sign( Ecc384PrivKeyIn::from(&Array4x12::from(PRIV_KEY)), &Ecc384PubKey { x: Ecc384Scalar::from(PUB_KEY_X), y: Ecc384Scalar::from(PUB_KEY_Y), }, &digest, &mut trng, ); assert!(result.is_ok()); let signature = result.unwrap(); let pub_key = Ecc384PubKey { x: Ecc384Scalar::from(PUB_KEY_X), y: Ecc384Scalar::from(PUB_KEY_Y), }; let result = ecc.verify_r(&pub_key, &Ecc384Scalar::from(digest), &signature); assert!(result.is_ok()); assert_eq!(result.unwrap(), signature.r); } fn test_verify_failure() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let digest = Array4x12::new([0u32; 12]); let result = ecc.sign( Ecc384PrivKeyIn::from(&Array4x12::from(PRIV_KEY)), &Ecc384PubKey { x: Ecc384Scalar::from(PUB_KEY_X), y: Ecc384Scalar::from(PUB_KEY_Y), }, &digest, &mut trng, ); assert!(result.is_ok()); let signature = result.unwrap(); let pub_key = Ecc384PubKey { x: Ecc384Scalar::from(PUB_KEY_X), y: Ecc384Scalar::from(PUB_KEY_Y), }; let hash = [0xFFu8; 48]; let result = ecc.verify(&pub_key, &Ecc384Scalar::from(hash), &signature); assert!(result.is_ok()); assert_eq!(result.unwrap(), Ecc384Result::SigVerifyFailed); } fn test_kv_seed_from_input_msg_from_input() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // // Step 1: Generate a key pair and store private key in kv slot 2. // let seed = [0u8; 48]; let key_out_1 = KeyWriteArgs { id: KeyId::KeyId2, usage: KeyUsage::default().set_ecc_private_key_en(), }; let result = ecc.key_pair( Ecc384Seed::from(&Ecc384Scalar::from(seed)), &Array4x12::default(), &mut trng, Ecc384PrivKeyOut::from(key_out_1), ); assert!(result.is_ok()); let pub_key = result.unwrap(); assert_eq!(pub_key.x, Ecc384Scalar::from(PUB_KEY_X)); assert_eq!(pub_key.y, Ecc384Scalar::from(PUB_KEY_Y)); // // Step 2: Sign message with private key generated in step 1. // let digest = Array4x12::new([0u32; 12]); let key_in_1 = KeyReadArgs::new(KeyId::KeyId2); let result = ecc.sign(key_in_1.into(), &pub_key, &digest, &mut trng); assert!(result.is_ok()); let signature = result.unwrap(); assert_eq!(signature.r, Ecc384Scalar::from(SIGNATURE_R)); assert_eq!(signature.s, Ecc384Scalar::from(SIGNATURE_S)); // // Step 3: Verify the signature generated in step 2. // let pub_key = Ecc384PubKey { x: pub_key.x, y: pub_key.y, }; let result = ecc.verify(&pub_key, &Ecc384Scalar::from(digest), &signature); assert!(result.is_ok()); assert_eq!(result.unwrap(), Ecc384Result::Success); } fn test_kv_seed_from_kv_msg_from_input() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // // Step 1: Generate a key-pair. Store private key in kv slot 0. // Mark the key as ecc_key_gen_seed as it will be used as a seed for key generation. // // Seed generated should be: // [0xfe, 0xee, 0xf5, 0x54, 0x4a, 0x76, 0x56, 0x49, 0x90, 0x12, 0x8a, 0xd1, 0x89, 0xe8, 0x73, // 0xf2, 0x1f, 0xd, 0xfd, 0x5a, 0xd7, 0xe2, 0xfa, 0x86, 0x11, 0x27, 0xee, 0x6e, 0x39, 0x4c, // 0xa7, 0x84, 0x87, 0x1c, 0x1a, 0xec, 0x3, 0x2c, 0x7a, 0x8b, 0x10, 0xb9, 0x3e, 0xe, 0xab, // 0x89, 0x46, 0xd6,] // let seed = [0u8; 48]; let key_out_1 = KeyWriteArgs { id: KeyId::KeyId0, usage: KeyUsage::default() .set_ecc_key_gen_seed_en() .set_ecc_private_key_en(), }; let result = ecc.key_pair( Ecc384Seed::from(&Ecc384Scalar::from(seed)), &Array4x12::default(), &mut trng, Ecc384PrivKeyOut::from(key_out_1), ); assert!(result.is_ok()); let pub_key = result.unwrap(); assert_eq!(pub_key.x, Ecc384Scalar::from(PUB_KEY_X)); assert_eq!(pub_key.y, Ecc384Scalar::from(PUB_KEY_Y)); // // Step 2: Generate a key pair and store private key in kv slot 1. // Use seed generated in step 1. // // Private key generated should be: // [0xc3, 0xb, 0x13, 0xa9, 0x33, 0x39, 0xbb, 0x5a, 0x2f, 0x4c, 0xed, 0xf8, 0x83, 0x57, 0x43, // 0x45, 0xbd, 0xa1, 0xd7, 0x7f, 0x36, 0x59, 0x75, 0x81, 0x2d, 0xa2, 0xc1, 0x4, 0xac, 0x76, // 0x28, 0xba, 0x9a, 0x8e, 0xf4, 0x37, 0xd0, 0x50, 0x6, 0x96, 0xc9, 0x40, 0xc, 0x20, 0x59, 0x42, 0xa5, 0x2c, ] // let pub_key_x: [u8; 48] = [ 0x93, 0x79, 0x9d, 0x55, 0x12, 0x26, 0x36, 0x28, 0x34, 0xf6, 0xf, 0x7b, 0x94, 0x52, 0x90, 0xb7, 0xcc, 0xe6, 0xe9, 0x96, 0x1, 0xfb, 0x7e, 0xbd, 0x2, 0x6c, 0x2e, 0x3c, 0x44, 0x5d, 0x3c, 0xd9, 0xb6, 0x50, 0x68, 0xda, 0xc0, 0xa8, 0x48, 0xbe, 0x9f, 0x5, 0x60, 0xaa, 0x75, 0x8f, 0xda, 0x27, ]; let pub_key_y: [u8; 48] = [ 0xe5, 0x87, 0xb2, 0xcd, 0x38, 0xe9, 0x4f, 0x7a, 0x2f, 0xd4, 0x31, 0xf5, 0xb1, 0xb2, 0xa8, 0xa0, 0x33, 0x7b, 0x97, 0x63, 0x75, 0x19, 0xf4, 0xb1, 0x51, 0x3e, 0xc9, 0x0, 0x9f, 0x96, 0x26, 0xfe, 0xb2, 0x5, 0x74, 0xfb, 0xff, 0x22, 0x5, 0xad, 0x84, 0x69, 0x87, 0xfd, 0xb6, 0x67, 0x1d, 0x8f, ]; let key_in_seed = KeyReadArgs::new(KeyId::KeyId0); let key_out_priv_key = KeyWriteArgs { id: KeyId::KeyId1, usage: KeyUsage::default().set_ecc_private_key_en(), }; let result = ecc.key_pair( Ecc384Seed::from(key_in_seed), &Array4x12::default(), &mut trng, Ecc384PrivKeyOut::from(key_out_priv_key), ); assert!(result.is_ok()); let pub_key = result.unwrap(); assert_eq!(pub_key.x, Ecc384Scalar::from(pub_key_x)); assert_eq!(pub_key.y, Ecc384Scalar::from(pub_key_y)); // // Step 3: Sign message with private key generated in step 2. // // Private key is: // [0xc3, 0xb, 0x13, 0xa9, 0x33, 0x39, 0xbb, 0x5a, 0x2f, 0x4c, 0xed, 0xf8, 0x83, 0x57, 0x43, // 0x45, 0xbd, 0xa1, 0xd7, 0x7f, 0x36, 0x59, 0x75, 0x81, 0x2d, 0xa2, 0xc1, 0x4, 0xac, 0x76, // 0x28, 0xba, 0x9a, 0x8e, 0xf4, 0x37, 0xd0, 0x50, 0x6, 0x96, 0xc9, 0x40, 0xc, 0x20, 0x59, 0x42, 0xa5, 0x2c, ] let msg: [u8; 48] = [ 0xfe, 0xee, 0xf5, 0x54, 0x4a, 0x76, 0x56, 0x49, 0x90, 0x12, 0x8a, 0xd1, 0x89, 0xe8, 0x73, 0xf2, 0x1f, 0xd, 0xfd, 0x5a, 0xd7, 0xe2, 0xfa, 0x86, 0x11, 0x27, 0xee, 0x6e, 0x39, 0x4c, 0xa7, 0x84, 0x87, 0x1c, 0x1a, 0xec, 0x3, 0x2c, 0x7a, 0x8b, 0x10, 0xb9, 0x3e, 0xe, 0xab, 0x89, 0x46, 0xd6, ]; let sig_r: [u8; 48] = [ 0xda, 0x48, 0xb4, 0xc1, 0x6a, 0xed, 0x87, 0x69, 0xc0, 0x64, 0x48, 0x3d, 0x4b, 0xc8, 0xba, 0xb3, 0xe, 0x4a, 0x51, 0x3d, 0x45, 0x80, 0x5d, 0x18, 0x73, 0x89, 0x42, 0x46, 0xe4, 0xd5, 0xd6, 0x1, 0x83, 0xd8, 0x41, 0xaf, 0xbf, 0xaa, 0xc2, 0x57, 0xff, 0xc, 0xff, 0x20, 0xbf, 0x65, 0x8c, 0xa4, ]; let sig_s: [u8; 48] = [ 0xdd, 0xb4, 0xbd, 0x4c, 0xbf, 0x7c, 0xa5, 0x2e, 0xd0, 0xea, 0xdc, 0xbe, 0x7c, 0x42, 0xbe, 0x99, 0x9d, 0x97, 0x14, 0xbe, 0x15, 0xa8, 0x8b, 0x45, 0x67, 0x18, 0x15, 0x46, 0x85, 0x7d, 0xa0, 0xb3, 0x49, 0xe8, 0x90, 0x28, 0x45, 0x74, 0xb7, 0x2e, 0x42, 0xd3, 0xa1, 0x38, 0xdc, 0xe8, 0x8c, 0x10, ]; let key_in_priv_key = KeyReadArgs::new(KeyId::KeyId1); let result = ecc.sign( key_in_priv_key.into(), &pub_key, &Array4x12::from(msg), &mut trng, ); assert!(result.is_ok()); let signature = result.unwrap(); assert_eq!(signature.r, Ecc384Scalar::from(sig_r)); assert_eq!(signature.s, Ecc384Scalar::from(sig_s)); // // Step 4: Verify the signature generated in step 2. // let pub_key = Ecc384PubKey { x: pub_key_x.into(), y: pub_key_y.into(), }; let result = ecc.verify(&pub_key, &Ecc384Scalar::from(msg), &signature); assert_eq!(result.unwrap(), Ecc384Result::Success); } fn test_no_private_key_usage() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let seed = [0u8; 48]; let key_out_1 = KeyWriteArgs { id: KeyId::KeyId0, // The caller needs to use set_ecc_private_key_en() here to prevent the error usage: KeyUsage::default().set_ecc_key_gen_seed_en(), }; let result = ecc.key_pair( Ecc384Seed::from(&Ecc384Scalar::from(seed)), &Array4x12::default(), &mut trng, Ecc384PrivKeyOut::from(key_out_1), ); assert_eq!(result, Err(CaliptraError::DRIVER_ECC384_KEYGEN_BAD_USAGE)) } fn test_kat() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // Init CFI let mut entropy_gen = || trng.generate4(); CfiCounter::reset(&mut entropy_gen); assert_eq!( Ecc384Kat::default().execute(&mut ecc, &mut trng).is_ok(), true ); assert_eq!( EcdhKat::default().execute(&mut ecc, &mut trng).is_ok(), true ); } const ECDH_SHARED_SECRET: [u8; 48] = [ 0x72, 0xb5, 0x45, 0xcf, 0xc5, 0x59, 0x40, 0x47, 0xd1, 0xc1, 0x3d, 0x0a, 0xab, 0x72, 0xcf, 0x0b, 0x16, 0x06, 0x9e, 0xc8, 0x2e, 0xc4, 0x50, 0x60, 0x71, 0x1f, 0x63, 0x6f, 0xf8, 0x17, 0xaf, 0xb7, 0x81, 0x31, 0x45, 0x66, 0x1c, 0xf4, 0x3e, 0x1a, 0x3c, 0x97, 0xb1, 0x93, 0xb6, 0x50, 0x6c, 0x24, ]; fn test_ecdh() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // Alice's private key let alice_priv_key = Ecc384Scalar::from(PRIV_KEY); // Bob's public key let bob_pub_key = Ecc384PubKey { x: Ecc384Scalar::from(PUB_KEY_X), y: Ecc384Scalar::from(PUB_KEY_Y), }; // Expected shared secret let expected_shared_secret = Ecc384Scalar::from(ECDH_SHARED_SECRET); // Compute shared secret let mut shared_secret = Array4x12::default(); let result = ecc.ecdh( Ecc384PrivKeyIn::from(&alice_priv_key), &bob_pub_key, &mut trng, Ecc384PrivKeyOut::from(&mut shared_secret), ); assert!(result.is_ok()); assert_eq!(shared_secret, expected_shared_secret); } fn test_ecdh_with_key_vault() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // Step 1: Generate a key pair and store private key in key vault slot 3 let seed = [0u8; 48]; let key_out = KeyWriteArgs { id: KeyId::KeyId3, usage: KeyUsage::default().set_ecc_private_key_en(), }; let result = ecc.key_pair( Ecc384Seed::from(&Ecc384Scalar::from(seed)), &Array4x12::default(), &mut trng, Ecc384PrivKeyOut::from(key_out), ); assert!(result.is_ok()); // Bob's public key let bob_pub_key = Ecc384PubKey { x: Ecc384Scalar::from(PUB_KEY_X), y: Ecc384Scalar::from(PUB_KEY_Y), }; // Step 2: Compute shared secret using private key from key vault and store in key vault slot 4 let key_in = KeyReadArgs::new(KeyId::KeyId3); let key_out_shared = KeyWriteArgs { id: KeyId::KeyId4, usage: KeyUsage::default().set_ecc_private_key_en(), }; let _result = ecc .ecdh( Ecc384PrivKeyIn::from(key_in), &bob_pub_key, &mut trng, Ecc384PrivKeyOut::from(key_out_shared), ) .unwrap(); // Is there a way to test we have a valid key inside keyvault } test_suite! { test_kat, test_gen_key_pair, test_gen_key_pair_with_iv, test_sign, test_verify, test_verify_r, test_verify_failure, test_kv_seed_from_input_msg_from_input, test_kv_seed_from_kv_msg_from_input, test_no_private_key_usage, test_ecdh, test_ecdh_with_key_vault, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/status_reporter_tests.rs
drivers/test-fw/src/bin/status_reporter_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: error_reporter_tests.rs Abstract: File contains test cases for HMAC-384 API --*/ #![no_std] #![no_main] use caliptra_drivers::{report_boot_status, SocIfc}; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_test_harness::test_suite; fn retrieve_boot_status() -> u32 { let soc_ifc = unsafe { SocIfcReg::new() }; soc_ifc.regs().cptra_boot_status().read() } fn test_report_boot_status() { let val: u32 = 0xbeef2; report_boot_status(val); assert_eq!(val, retrieve_boot_status()); } fn test_report_idevid_csr_ready() { let soc_ifc = unsafe { SocIfcReg::new() }; SocIfc::new(soc_ifc).flow_status_set_idevid_csr_ready(); let soc_ifc = unsafe { SocIfcReg::new() }; assert!(soc_ifc.regs().cptra_flow_status().read().idevid_csr_ready()); } fn test_report_ready_for_firmware() { let soc_ifc = unsafe { SocIfcReg::new() }; SocIfc::new(soc_ifc).flow_status_set_ready_for_mb_processing(); let soc_ifc = unsafe { SocIfcReg::new() }; assert!(soc_ifc .regs() .cptra_flow_status() .read() .ready_for_mb_processing()); } test_suite! { test_report_boot_status, test_report_idevid_csr_ready, test_report_ready_for_firmware, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/sha1_tests.rs
drivers/test-fw/src/bin/sha1_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha1_tests.rs Abstract: File contains test cases for SHA1 API --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{Array4x5, Array4xN, Sha1}; use caliptra_kat::Sha1Kat; use caliptra_test_harness::test_suite; fn test_sha1(data: &str, expected: Array4x5) { let digest = Sha1::default().digest(data.as_bytes()).unwrap(); assert_eq!(digest, expected); } fn test_digest0() { let expected = Array4xN([0xda39a3ee, 0x5e6b4b0d, 0x3255bfef, 0x95601890, 0xafd80709]); let data = ""; test_sha1(data, expected); } fn test_digest1() { let expected = Array4xN([0xa9993e36, 0x4706816a, 0xba3e2571, 0x7850c26c, 0x9cd0d89d]); let data = "abc"; test_sha1(data, expected); } fn test_digest2() { let expected = Array4xN([0x84983e44, 0x1c3bd26e, 0xbaae4aa1, 0xf95129e5, 0xe54670f1]); let data = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; test_sha1(data, expected); } fn test_digest3() { let expected = Array4xN([0xa49b2446, 0xa02c645b, 0xf419f995, 0xb6709125, 0x3a04a259]); let data = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"; test_sha1(data, expected); } fn test_op1() { let expected = Array4xN([0x521d84ef, 0xcae113d0, 0x00a14796, 0x8b508e06, 0x7cb60184]); const DATA: [u8; 1000] = [0x61; 1000]; let mut digest = Array4x5::default(); let mut sha = Sha1::default(); let mut digest_op = sha.digest_init().unwrap(); for _ in 0..300 { assert!(digest_op.update(&DATA).is_ok()); } let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, expected); } fn test_kat() { // Init CFI CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); assert_eq!( Sha1Kat::default().execute(&mut Sha1::default()).is_ok(), true ); } test_suite! { test_kat, test_digest0, test_digest1, test_digest2, test_digest3, test_op1, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/mldsa87_tests.rs
drivers/test-fw/src/bin/mldsa87_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: ml_dsa87_tests.rs Abstract: File contains test cases for ML_DSA87 API tests --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{ Array4x12, Array4x16, Hmac, HmacData, HmacKey, HmacMode, HmacTag, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, LEArray4x16, LEArray4x8, Mldsa87, Mldsa87Msg, Mldsa87PrivKey, Mldsa87PubKey, Mldsa87Result, Mldsa87Seed, Mldsa87SignRnd, Mldsa87Signature, Trng, }; use caliptra_registers::abr::AbrReg; use caliptra_registers::csrng::CsrngReg; use caliptra_registers::entropy_src::EntropySrcReg; use caliptra_registers::hmac::HmacReg; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_registers::soc_ifc_trng::SocIfcTrngReg; use caliptra_test_harness::test_suite; use zerocopy::IntoBytes; const PUBKEY: [u32; 648] = [ 0x91204ff5, 0xe7902480, 0xa0e5c933, 0x72a637ac, 0xfabb499d, 0x6ffb2abb, 0x8511668e, 0xdb8a3253, 0x553de529, 0x413f8be9, 0x5ea473d7, 0x8081ee24, 0x246090d8, 0xdd247908, 0x2e8b653c, 0x31837dac, 0x56949029, 0x1dc84a04, 0x226364dc, 0xfa988abc, 0x1dad3da7, 0x7b197f29, 0xe76edff5, 0xa0cd7edf, 0xee60a43d, 0x4e0726ab, 0xc93efb79, 0x785ed57e, 0x6916ed6a, 0xf0ecb754, 0xb3bd3a04, 0xa673e1f9, 0x6c8c3768, 0xae53583b, 0xd399c240, 0x2d9db819, 0x207837e4, 0x22395f74, 0x758d0a9b, 0xbcdfa238, 0xc89282c1, 0x5dea2e10, 0x85f11cb2, 0xb4de12b0, 0x3941613e, 0x832c5c17, 0x66910e1d, 0x477d8408, 0x10b7b10c, 0xb6328113, 0x6255886d, 0xc8d6d365, 0xba1ed855, 0xfd5193f8, 0xf2ad6e44, 0x5ae0ef0d, 0xb5c15b8a, 0x3c967bdb, 0xdd83f8dc, 0x50940d5, 0x65c4c504, 0x79695991, 0x1ba1ea6b, 0x4993009c, 0x6ea15eee, 0x77d00da9, 0xdcc2f892, 0x2f4d703b, 0xe0fe2cd, 0xd1a3a2d9, 0xaa44fced, 0xaabf04a0, 0x8527ced7, 0x30888a8d, 0xa7d1725b, 0xc9da3aad, 0x676bb5f0, 0x4dcc9c64, 0xd470daee, 0x305d0685, 0x85963a0b, 0xf1667f68, 0x942c8d2c, 0x97323f07, 0x4b3bca70, 0x97af0f45, 0x9abe22bc, 0x4a13a199, 0xb1a845c5, 0x31978400, 0xc172e50e, 0xdaf20300, 0xe65d2093, 0xf70288c, 0x4737a756, 0x6e150c4d, 0x10355d0c, 0xc770353, 0xbdce0f6c, 0x17cbc234, 0x6c3ce9b5, 0xc3ceaef5, 0xc53af15b, 0x98b5a5ac, 0x3c94d5a5, 0xd2949d43, 0x62f60eaf, 0x6f3e60a2, 0xa50258bd, 0x36772e58, 0x63da3fa0, 0x312e1dd9, 0x7ca5cdef, 0x8c1e7643, 0x5bc4c355, 0xfc5f0f4e, 0x4d25bf81, 0x56ac0a0, 0x4b29cf44, 0x8a94db67, 0xe417df7b, 0x7e30f74f, 0x9e50a464, 0x3e3c5e7d, 0x8d08dbb, 0x4d2b59d7, 0xaf6c323d, 0x16f66be8, 0x921b024e, 0xd60d8874, 0x313bd32a, 0x6c6e1b21, 0xdada6f62, 0x538e0a1d, 0x71a99a24, 0x937f4d7b, 0x36856f6a, 0x3dbcbce4, 0x21464448, 0xc1e03cee, 0x4f98835, 0x9f0127e5, 0x959fbd38, 0x449def54, 0x413a442b, 0x1abf0f08, 0xd0823c2f, 0x3f4185fe, 0xf6a3dfcc, 0x4c8a10af, 0xfacdfe24, 0x552264f1, 0x65db50f3, 0x40d9c16e, 0x5c908401, 0x8091928c, 0x23726d39, 0xca7859b4, 0xc449d691, 0xb9b4b668, 0xd12f03e8, 0x5067e9ec, 0xd587cea2, 0x14ab2f9, 0x8a1bdd33, 0xdd08055d, 0x97e17102, 0x7dde5b71, 0x515ee4af, 0xa0b0d828, 0x9b9356ba, 0xa1e5ddd8, 0xd834dd06, 0xf8da3866, 0xa1216134, 0x68e6d0f4, 0x8a419138, 0x5096f6ad, 0x709b1f8c, 0x37e965ae, 0xec867865, 0x7c98dff9, 0xf548e937, 0xd9c6bf1d, 0xb247d6c5, 0xe5d6efe8, 0x95a1ba79, 0xd96f500f, 0x8e772047, 0x2706a4ec, 0xfc1d6a7c, 0x8236fcd0, 0x1bdab621, 0x81282fb5, 0xec6137a4, 0xc5a1ec8e, 0x31bff8c8, 0x7696359d, 0xa56b8ab9, 0x5b4bb8ca, 0xd4bd172b, 0x3d6c2126, 0x9f9f0f59, 0xe9888723, 0x989dcc64, 0xf2bc44d9, 0xfb365f9a, 0xff2333da, 0x509ba7b1, 0x5b1ca925, 0xe4a77e0c, 0xd678fadc, 0x6fbc2d61, 0x7460a11c, 0xa691ee09, 0x5e5ae09c, 0x35e41711, 0xe53d72d3, 0xbb9e2bfe, 0x93ac8c2f, 0xb9a0730c, 0x3a2c34ed, 0xe3651de3, 0xfa2c0f3, 0x823c13c8, 0x4f817adf, 0xe66df587, 0x9a97164e, 0x6df2c47, 0x528e42e3, 0xfb944369, 0x8871187e, 0xa5249608, 0x17e8104e, 0xf68398a8, 0xbcbfc235, 0x7bca1967, 0x5a6ca651, 0x6cf4318e, 0x80209146, 0x5a994ec4, 0x337fec80, 0xd41a6339, 0xc3d82e5d, 0x2212c4c5, 0xe42d72f8, 0x82c37332, 0xbf5efaec, 0x9792596c, 0x94f60c67, 0xa3cf5d0c, 0x3e315bdc, 0xbd277f70, 0x10821be0, 0x982cfebb, 0x89ca1d76, 0x50b7b935, 0x6f5dc1d8, 0x8f7fb5de, 0x7690e437, 0x69064ea2, 0x5c11f7, 0x1aa0a865, 0x699c2516, 0xda4c3be0, 0x2a353f68, 0x7ae96f4a, 0x2930c7db, 0x9a8ec783, 0xbbc41db4, 0x66fc2915, 0xfff14cd9, 0x1c059f92, 0xa17573ee, 0xa623d4f, 0x423a8807, 0x2b5a29c0, 0xc601dffd, 0x1c2eb264, 0xe9cb3dbf, 0x2308a3cc, 0xadc2bf04, 0xdc256025, 0xf896d08f, 0x85d08a68, 0x77d8374a, 0x544c0b6f, 0xbbf45b14, 0xee6d8329, 0x94ff0009, 0x68789dcf, 0x83a95bf4, 0xbe537d96, 0x714f1972, 0x54b6c3c3, 0x4f35ecd, 0x63eed870, 0x885ed3e1, 0x389a3405, 0xe3619ad9, 0xa08e3e0e, 0x11c7c8dc, 0xc28a113e, 0x2911a91c, 0xe955c5d8, 0x8f8669f3, 0x23718ef0, 0xb69cd7ed, 0x6f1ab26a, 0x98169422, 0x624ed233, 0xffb41b52, 0x7ab70f56, 0xba7bdd64, 0xb14a6786, 0x3cd782b0, 0x27bcdf7a, 0xe33f8728, 0xc1680de9, 0xcfae9a1d, 0x6e1be398, 0x85f883a7, 0xf1a49e06, 0xff6f7d9a, 0x196c2129, 0x160f2c7d, 0x272f232a, 0x1d4b55f8, 0x707c5a06, 0xfecf1a1, 0xaa58daf1, 0xd6017e66, 0x5ef398b8, 0xac281e5c, 0x15e8966b, 0xfdb3c866, 0xe7d306, 0x13d5c3dd, 0x5be04abd, 0xfabd2784, 0x98602332, 0x4dfa2012, 0xd8429aef, 0x661ee397, 0xc7a42da3, 0xdd8df42d, 0xeb462807, 0xb432b716, 0xf5438d85, 0x7d1661ed, 0x21d80975, 0x9d5e692a, 0x1dfdbc15, 0x6e21268e, 0x9bfd5443, 0xa4a45aa4, 0x80809cf6, 0x42ca703, 0xdd305b12, 0x8eff2c3b, 0x3fbacdfc, 0x653e093c, 0x7018037a, 0x6bf4e840, 0xe634d1b0, 0x6af4b7d8, 0x1a85b7ac, 0x8384c463, 0x65409b7, 0xe89a0cb4, 0x14bcc37c, 0xa2311e14, 0x7ae8ef42, 0x514572b3, 0x5a9bf361, 0x6c4c302, 0x6d42a768, 0xa2db3696, 0x52affa66, 0x3add0b01, 0xccaadc7a, 0x1b0b2eb4, 0x1bc4d759, 0x679bd137, 0x870c0b2d, 0x76b5b3a4, 0xfbe6b187, 0xad95bbf9, 0xfa7a49d5, 0x2e3b0acb, 0x328a88f8, 0x93d25c65, 0x1bed809c, 0xe663782a, 0x75cb1fc2, 0x31439e6e, 0xfd11cef9, 0x71490c64, 0x5c14d49c, 0x4d263890, 0xaf7ea1da, 0x3fbf5291, 0x2cacf92c, 0x454d42e0, 0x5990702a, 0xb92e8e11, 0xf1cac39d, 0x65dd8ee8, 0xa231381b, 0xd2cdaf01, 0xc02ea9e9, 0xf06b98a9, 0x3b5eff7e, 0x660baea, 0x7f9738ae, 0xf9f80cab, 0x9a4ddcc7, 0x9bcd4279, 0xa1ac0f83, 0xcfe722ff, 0xf6e092ef, 0xb8d70486, 0xec11455, 0x32edb71b, 0xb82472fd, 0xb68ae7d, 0x28566a0e, 0x506ea559, 0xf604ae74, 0xec25812a, 0x5182e270, 0x3405cce4, 0xa4483c2d, 0x49b6927b, 0x14b42fc1, 0x63c638f1, 0x16d13910, 0x3c8255bd, 0xa2b2cb13, 0xbb96b69d, 0x826411af, 0x3d07c98a, 0x15b8b079, 0xbb2a380, 0xefcf88e6, 0x1d6e3dab, 0x50b7941c, 0x1f748737, 0xcdf2d1ec, 0xa6fb071e, 0x246c691c, 0xbff9e81e, 0x4dec0bd9, 0x9dc84672, 0x11c147a3, 0xb41511d0, 0x895dd5fc, 0x946707ae, 0x7ca580a0, 0x2f0c609b, 0xc38bdb7, 0xcc6541ec, 0x62e3a57c, 0xb954d451, 0xcd644a17, 0x479863b, 0xf7a414bb, 0x8b61267c, 0x91151ed9, 0xf372d94, 0xdf63f1bb, 0x33c8bd0e, 0x295dcce3, 0x946570c0, 0xe5841f9d, 0x2f4719e0, 0x4a7c088d, 0x1529e45a, 0x9f55526d, 0xa434f32b, 0x2a539a9e, 0x5c00ce84, 0xc468d0a, 0xd6034b6f, 0xae9eec76, 0xfa1aff97, 0x62dd2260, 0xd98b0e59, 0x284f5bed, 0x158ebef6, 0x67f33854, 0x8f15efc9, 0xbc70562, 0xa832ab49, 0x8b5e7457, 0xb42ba65a, 0xdaa6a14b, 0x220ba047, 0xb268492e, 0xb565a65e, 0x3debf628, 0xd2b76207, 0xbdeb518b, 0xef3a62da, 0xe8e8cea4, 0xd7eda59c, 0x53e134a, 0xa301d344, 0xdaa0f46f, 0xfe7934c0, 0x9856a8f4, 0xd4eb8c2e, 0x59438efc, 0xd6219fea, 0x6d69c853, 0x57f4ecf, 0xab081623, 0x54e6d668, 0x126b6f3d, 0x364711c8, 0xef99750a, 0x861cf05b, 0xccdeae52, 0x10a11efb, 0x1884feac, 0x199999e6, 0xab829f64, 0xc97bff83, 0xab02b53f, 0x8b5aeb3d, 0x31d811f9, 0xdcf5eb, 0x5a40f5e1, 0xe8c4b3cd, 0x521d9b33, 0x6efb7236, 0xedb3c7f2, 0xd9b0b0ab, 0x389d4741, 0x3227a03, 0xd97d056c, 0xe6fe86f0, 0xc98af75e, 0x4a78c220, 0x88d1884a, 0x2a33b2ca, 0x59d6f2a6, 0xc092d9c5, 0x5956fce2, 0x389ebcc1, 0xbed2868, 0xf7b6b878, 0x8d077ef6, 0x20f73fc2, 0x1385376a, 0xdb5858a8, 0x166f9069, 0x14a9031c, 0xfaaf3c23, 0x3cdd8cf1, 0x466796ab, 0xaaee6ca2, 0xd2e42d4f, 0xc4e3fa75, 0xe8635ae8, 0x3242a5fd, 0x8cb38269, 0x344bdb20, 0x13877d75, 0x79063baa, 0xd2283587, 0x48068bd0, 0x6468b392, 0xb811b3b0, 0x1e2475dd, 0x87bc98ec, 0x28218f32, 0xdd37074, 0x5fd3ace9, 0xf90407c5, 0x33d1b624, 0xc1ce37fc, 0x35bdc8a2, 0xf324937d, 0x7b0d0a43, 0xd6a7bcf7, 0x5191ce6c, 0x7746b74, 0xbc0a8d42, 0x768d08e, 0x8a110abe, 0xf8cef2cb, 0x6a86965a, 0xf7cceb92, 0xa3cad697, 0x9584e027, 0xcbb12205, 0x52226c90, 0x25d2a99e, 0xbfdfec00, 0x73ffe7de, 0x648ee7fa, 0xf38676f7, 0xd2dc7145, 0xce2bba03, 0xaec3018f, 0x7043489f, 0x38596615, 0xed0ab30e, 0x9dbc040b, 0xbd6e114c, 0xbb6fbd22, 0x8ccd3b57, 0x707d4bc5, 0x778c98a7, 0x580d88b7, 0xf93af125, 0xf1c21a47, 0x24100b84, 0x4a31472f, 0xe9cff5d4, 0xa7a9b7e2, 0xb2081b62, 0x8c265b36, 0xebdec4be, 0xca84112c, 0x9260fbf, 0x13d42a1f, 0x456d3647, 0x3a7df989, 0x9462c9de, 0xc527ee5c, 0x8a58d1dd, 0x60cca17c, 0xfac94cf6, 0x61217530, 0xd3a021fe, 0x7fb4d936, 0x70e424c2, 0x51186248, 0xbba5b033, 0x7f784581, 0xedd3be4a, 0xca1fb49, 0xdc28cf42, 0x32e5b6e9, 0xdbf10a48, 0xe49d2c4c, ]; const SIGNATURE: [u32; 1157] = [ 0x356024b8, 0xb33219dc, 0xb27f7d39, 0x0e97135e, 0x879c1760, 0x02ddd61e, 0xec11d1e3, 0xeb0b47a8, 0xfdf36cad, 0x397a6f82, 0x6ddbc61a, 0x0fd7d31c, 0x4bb69fa8, 0xff7b0734, 0xce2cd513, 0x57f66f5f, 0x04112957, 0x4fd89fe6, 0x8534a2eb, 0x6e8d1b8f, 0x8a4cbc70, 0xe29ce3e2, 0x96f63a9b, 0xca86b852, 0x24888427, 0x891298f3, 0xa4695e1c, 0x384f4a82, 0xa2a12c9e, 0x9a322d2d, 0xf5966368, 0x7b17efec, 0x9a1e42f8, 0x8480413b, 0x1f9d00a7, 0xbc6a7ce5, 0xfe110cae, 0xdd46e2c8, 0xdc60a985, 0xacf22ddb, 0x6ffe1880, 0x271a3b64, 0x6df8470a, 0xc5405676, 0x95018e07, 0xe58e9106, 0xa94c92dc, 0xa86f40d2, 0xf542e634, 0x86f97aab, 0x8da5e234, 0x175fa493, 0x9a993e05, 0x83fe4cad, 0x7c563812, 0x659a28c9, 0xeb1375e1, 0x01249144, 0x05449b42, 0xd31bf7ad, 0xd2ea8e1a, 0x7fe8c7c1, 0xcea9f9e8, 0x9905d76b, 0x14c9f335, 0x476efd28, 0xa67e371e, 0x31809618, 0x46968528, 0x5e3e76af, 0x1ca1a272, 0x01242f56, 0xdcbcb607, 0x5ad3cd12, 0x104d951c, 0x81e6301d, 0xb0657f56, 0xfc7090fd, 0x5fed5038, 0xaa03302e, 0x2d715dba, 0xba7d2136, 0xabb1d6f4, 0x06e8731d, 0x667fc142, 0x76696fa6, 0x1e6ecfaa, 0xf96d6e66, 0x5e971c04, 0x50d81d9c, 0xd72ed756, 0x5886097a, 0xae8d4162, 0x6f1ddb30, 0xf4d80ae6, 0xa28331cb, 0x5e9887a3, 0x94e08c5b, 0xcd10588a, 0x56eece0a, 0xf9f8592b, 0x10831ed1, 0x4a587352, 0x6ea794c7, 0x3f2e3769, 0xf32e930d, 0xc253bd78, 0xedefa912, 0xd9474906, 0x7ed4bf1d, 0x081e95f4, 0x1ab7e300, 0x28c4e753, 0xf3ef9f70, 0x7aa32f04, 0x9ab2171f, 0x2e8f62e6, 0xba31bc2d, 0x2f57e9bc, 0xf758b58c, 0x76af312d, 0x1a6c2adf, 0x2de71435, 0x307f2c53, 0xdf6e68ec, 0x09eea813, 0x93bd889c, 0xc2ce486b, 0x09534967, 0x4e0177a5, 0x69b7545f, 0x0def83f6, 0xf492e6dd, 0x8b50430b, 0x6b8129e3, 0x161c7adc, 0x12e47dba, 0x1a492146, 0xb622f55d, 0x36f69348, 0xd6c1f722, 0x213d6d6e, 0xf019abc3, 0xf90be80f, 0xa1490316, 0x5b3e8353, 0x20d9d176, 0x3ac3dedb, 0xb642f1e4, 0xbb09c9a6, 0x8a92501c, 0xc4ff1bd8, 0x88f6ad52, 0x038a2af1, 0x8f1358bc, 0x31d1f4b8, 0x70f455f4, 0x7d8611a1, 0x7219befa, 0x1c3bc35d, 0x2a3ce56e, 0x3a0bf5f1, 0x98983b1d, 0x744eea18, 0x888f09be, 0x7bcf7144, 0x5ebbd8cc, 0x22b27bad, 0x2040cfbe, 0x75aceb9c, 0x0609bb20, 0x9c3666fc, 0x46beec1c, 0x5b37cf21, 0x5e95414f, 0xa736ce9d, 0x78ad33a9, 0xbd2c03ac, 0x0c36c407, 0x710f9644, 0x2035db48, 0x42577b2e, 0x26571708, 0x7eb395a9, 0xba497ab8, 0xbf3629c4, 0xec6ef1b9, 0x7833edf8, 0xe4bc2330, 0x0fe55bff, 0xffe50d69, 0xb0c75483, 0xdea883f0, 0x2bf41877, 0x5ae7a9e5, 0x0a756940, 0x2bf13e39, 0xfd0e7316, 0x21dd1d33, 0x1179ecbb, 0xea24dbe5, 0xf3d1f74c, 0x7a12de45, 0x793ecfa4, 0xaaf26acd, 0x55846e35, 0xf2a15eb1, 0x2aafe5a1, 0xf0a8e520, 0x9c4826ba, 0x915c5010, 0x23f674bb, 0xa401d516, 0xbb7ec3a4, 0xa40d99db, 0x51112054, 0xb1ded64f, 0xd995d526, 0x7f1aaad9, 0x124a730e, 0x6727b091, 0xee942f46, 0x60ec2c68, 0x42adc6e9, 0x833d05d2, 0x798252d1, 0xc01ee239, 0x570f682d, 0x1f3421f9, 0xfb340f4a, 0xc80a7f77, 0x7a45bd9b, 0x1b2e268f, 0xb75e0476, 0x9b222ae6, 0x8c20bb6f, 0xeb3f9e9f, 0xd3573fca, 0x89fe7b21, 0xca50d47b, 0x8b7edd30, 0x3a3ee57c, 0xf768efdc, 0xb58b9be1, 0xec3e69a7, 0xfa76913b, 0x52fb3896, 0x7fd68717, 0x0f1299f7, 0xa5b48711, 0xa73f1811, 0x63219acc, 0xb9ebb207, 0x0b9ce9c5, 0xc21dc876, 0x06756151, 0x38305310, 0xbfa47cce, 0x8217e274, 0x66892785, 0x9a7de31f, 0x31bb99f6, 0x1bae8fe0, 0x87578cd9, 0x32813614, 0x00d20569, 0xbc9957b0, 0xdf3712d1, 0x0c374a35, 0xb52a47fc, 0x98cb42f6, 0x1726be59, 0xed5e8e70, 0x8405f75b, 0xd4083819, 0x3dd8b3f5, 0xe6b758df, 0x33b6d86a, 0xa2108c77, 0x581fbf72, 0x6085dbd4, 0x34d7dfa4, 0x76e42637, 0x6cd8f909, 0x45768dcc, 0xb82934a8, 0x30b0ead4, 0x920fca7a, 0x6073fcde, 0x6b4dd2db, 0xf87746ef, 0xeff55a6a, 0x835aad8f, 0x03f4cb0e, 0xc4d87535, 0x7939420d, 0xc630df61, 0x2e9b3ada, 0xe685363d, 0x07256aa9, 0x2887fadc, 0x58a53cfa, 0xe68ac0b1, 0xb73f20c5, 0x31774a01, 0x7a5433c1, 0x7e5ac0bd, 0xed7cc499, 0xeee090dd, 0x4488d3b2, 0xa2edf15c, 0xea9b8239, 0x48a94714, 0xb06ad042, 0xe7999f7e, 0xe0a488e3, 0x4e06f3ae, 0x77c8867a, 0xddab6512, 0xd4e197f4, 0xada26fd3, 0x28507dd4, 0xd703f846, 0x6e5d9ea4, 0x2f2e4d27, 0x8cf779cb, 0x35fd3f62, 0x24700c2d, 0x1599b774, 0xe7f93f20, 0x0c5729c5, 0x37315c42, 0x472da66c, 0x386baa02, 0xae30c44d, 0x87ba7aec, 0x0092272f, 0xc1a27fa5, 0x84cf5de3, 0xdf32fdd3, 0x0aa682cb, 0x531ddfd2, 0x54792b77, 0x7ec1669c, 0xd9c0fbc3, 0x886561e0, 0x3339c6f7, 0xcbc95454, 0xabb9d5fd, 0xa77a16e4, 0x70185ac8, 0x586a66d4, 0x0fc1d3d7, 0xa3e35831, 0x107784ab, 0x757548c8, 0x1785fbb1, 0xb5ebbf66, 0xf46d7e09, 0x9dea39e9, 0x8940c3f9, 0xe26081ff, 0x545aaab1, 0x4531e5d1, 0x50dddb08, 0x85e0d8da, 0xe8cd7fe3, 0xc6c28572, 0xdfcce491, 0x60cbaf5e, 0x8902b48b, 0x4edae3bb, 0xb0f873ba, 0xecc3b50c, 0x9789cf7d, 0x9bffc4d0, 0xfc66b411, 0x51c6b8fd, 0x2c483054, 0x6dc1ee10, 0x7f7cb935, 0xb6605ec5, 0xeaf0e765, 0x55ee7678, 0x8979a98c, 0x810a9a2c, 0x2dbef2eb, 0x242107c2, 0x01ba777a, 0x71ed3c0f, 0x215e5f6a, 0xbe17a028, 0xde53c690, 0xcf33ad71, 0x8fc3f3ab, 0x38ef75b5, 0x105ebda1, 0x579f93d1, 0x8f9d61e6, 0xdf75b8aa, 0x5c024c11, 0xcfa771db, 0x0eb63853, 0x7ea898a0, 0xcb5719d3, 0xd0d1ed14, 0x456f31e1, 0x4b1c9c0c, 0x36f403aa, 0x866793d3, 0x2553d685, 0xfa51bc77, 0x5bfe6f2f, 0x6daa9be9, 0xd99d6589, 0xbf89a36c, 0x2ba795c9, 0x0903be7a, 0xfc02bc40, 0xf18f7bbe, 0xd8dc60df, 0x57373014, 0x0da4e50c, 0xc9d51d61, 0x095f2986, 0xbe0275ed, 0x4e31d2b1, 0x0c8519c3, 0xda3df3ea, 0x43eb8463, 0xf866259f, 0xd6e4900b, 0xdffbdc2b, 0xc9740428, 0xc48d95fe, 0x4e221360, 0x3c4b53a5, 0x90b09de4, 0x8e1dd154, 0x38c8c3e8, 0xd135e306, 0x7cecc54a, 0x30cfbf02, 0x594cbf20, 0x0b6a5d93, 0xc02c672e, 0xd8f1dae5, 0x946223c2, 0x001897fb, 0x5018db03, 0xe89b3d87, 0xf6f88b06, 0xb59877d7, 0xa4208e44, 0xb5dbeab9, 0x195a963c, 0x0c42d278, 0x85500bc1, 0xd9fdf128, 0x99208ec3, 0x465ed5a4, 0x32eb4254, 0x290f5a4d, 0x155c12e0, 0x95eadc35, 0x62ff1fae, 0x6a8b6fad, 0x956ca3fd, 0x2514ffbd, 0xe8464d7d, 0xa59e9688, 0x3e72b8e4, 0x0dc9c48c, 0xe6c41a29, 0xba68aa12, 0x836db58a, 0x26bf3c6f, 0x37a96adc, 0x96cb8d2e, 0xbc3b6ee7, 0xa639e173, 0x20aee1db, 0xff65e3be, 0xf3795c85, 0x0ac09dab, 0x515fbfd3, 0xdb841e73, 0x49cd1f89, 0x795e87d8, 0xbd404310, 0xe9e08c07, 0x502f44c5, 0x8c224114, 0x8697dd96, 0xac375f20, 0xc91c1b68, 0x1df3733a, 0x5b8f462a, 0xc7885db4, 0x70868185, 0x9f820229, 0xdac9b54f, 0x135e543c, 0x455294d0, 0x440ab5bf, 0xb7cbf7d1, 0x1b235879, 0x385176a8, 0x3553dcea, 0xa2198f23, 0x8833b6d4, 0x7a163011, 0x3b49ec90, 0xca650646, 0x206a3abc, 0x021f21d8, 0x9e190af6, 0x6336b071, 0x0fc6f64a, 0x7955c625, 0x7e3d6684, 0x2e12d935, 0xdf27cb12, 0x5e0c61b3, 0x0228f895, 0x2956654a, 0x5b3f716d, 0x7ec66d16, 0xa34f130d, 0xcdad7cd1, 0x3e6606ef, 0xf4588945, 0x0e49a919, 0x53af4b2e, 0xd3599e7d, 0xe24f3b4c, 0x07960770, 0x2bb7f080, 0x4b6f9e84, 0xd41d2353, 0x013cb62e, 0xab65d568, 0x629dc478, 0xb5985fb0, 0x452e2808, 0x6e70b0ee, 0x92ab93cc, 0xfecced78, 0xc7859b99, 0xb941b236, 0xbfaf336d, 0xcd31f913, 0x0a41205a, 0x6e17b479, 0x7219d0c6, 0x9d68c76b, 0x7e6e0935, 0xc885c141, 0xa46ebfec, 0xf10ea9b0, 0x01355c6d, 0x7340d18f, 0xe66f37d2, 0x0b9cc442, 0x9a65c3be, 0xb6cc4daa, 0x7cb0560f, 0x669d2910, 0x9011a729, 0x3f0e2cd6, 0x3ae81f71, 0x25d94de9, 0x36b24342, 0xf6f9a23a, 0x1d395a26, 0x00226906, 0xd6ca67fd, 0x9fa0aa78, 0x614a0e6a, 0xc7a25372, 0x683d7568, 0xe8d05b93, 0xe846501d, 0xb702df47, 0x6a43c903, 0x5b645276, 0xebec2913, 0x324e14e7, 0xa8b63ebb, 0x79b6ac5b, 0xd35a5b39, 0xdfca5ace, 0xb6fde98b, 0x505cfd8f, 0x46b77760, 0x55cc9b7f, 0x1c850846, 0x666bc568, 0xf01b2474, 0x8ac40754, 0x03d225f6, 0xd24a93c5, 0x0b4934c5, 0x11045d04, 0x2a583dfd, 0x70e18d97, 0xb0eac860, 0x767c4933, 0x16ab6b85, 0xb11bd267, 0x5852d568, 0x3ce0680d, 0xb05199ec, 0x17d76615, 0x183f39e3, 0x7ccd3d9d, 0x51381345, 0xcc876345, 0x37cee418, 0xf42c5987, 0x06311c10, 0x201dc8c2, 0x0b86e63a, 0x35eb1d93, 0x895070da, 0xcee789b0, 0x8f25ecc3, 0x7cecf8ec, 0x521e5455, 0x5f31ca1b, 0xf1655faf, 0x78b26eb5, 0x2e155dee, 0x86542f57, 0x662790b8, 0x901d1631, 0xd7cbeba1, 0xd3550020, 0x1c6423ac, 0x45750064, 0x1751e4fa, 0xc0cdaa81, 0xd857f2d2, 0x280f7066, 0x46b49e79, 0xe7956f20, 0xfa8ceb82, 0x1de91eb0, 0xe3ee608f, 0x97727f81, 0x3445649f, 0x93c935e7, 0xce030beb, 0x1631c55c, 0x76654109, 0xe2902bec, 0x49601525, 0x73b38a65, 0x801b0ecc, 0x68f22e1c, 0xd8ade49d, 0x6e90ea68, 0xea5e0809, 0xf3892a59, 0x4f4c5d1a, 0xd6e06d28, 0xf949f1cc, 0x41f81d11, 0xed49769b, 0x8c9baac1, 0x8bf6c99f, 0x5430a5f2, 0xeb09b1fd, 0x0a7783e1, 0x18121bf8, 0x8fa3b722, 0x813f71f8, 0xca40a186, 0x31e56247, 0xbe8e0346, 0xaf27fa62, 0xba025398, 0xd2ccec86, 0x8fd639f2, 0x0d506a67, 0x5c7fbff3, 0xe8dad62f, 0x80a65042, 0xc175a7c5, 0xe6884859, 0xc677db2a, 0xd3307f77, 0x610773b9, 0x7e05a643, 0x807ba057, 0x3ee4eead, 0xcc5eff9c, 0x95bab349, 0x4b4fdbc1, 0xa2fd0d33, 0x956afc7b, 0x2eb1e9cc, 0x806342a1, 0xce44793a, 0xea6f19c4, 0xbc62bb6b, 0x7e196651, 0x48bb2a0b, 0xeba1d5e5, 0x0527921d, 0x02862484, 0x87ffb480, 0x0df06531, 0x5b79b17b, 0x7d83981a, 0x644a991a, 0x41e7ea91, 0x7fc7b34e, 0xce1b44da, 0x8fe28e6c, 0xec46c06f, 0xa7219321, 0x550751fa, 0xa9c85dce, 0x4078102c, 0xf838d4ae, 0xe3e44db8, 0x082b5f04, 0x2a161f1d, 0x93f73de0, 0xc2ae7325, 0xbf4a5fbe, 0xe36fe98e, 0x79a50ec0, 0x52504fdc, 0x7c0e694c, 0x3db56a4c, 0x8adc26d2, 0x833b8e17, 0x39d99ef1, 0x32fd4ad5, 0x197aa0e3, 0x9f8339e2, 0xa5be0ebb, 0xd3a9abdd, 0x030c60f0, 0xd39656b5, 0x1828c55a, 0xfdbdee12, 0x63c4e7c3, 0x7585848f, 0x103c5c91, 0xc080567f, 0x7be80f86, 0x4dd284ac, 0x546d4c6f, 0xa11659cd, 0xe122519e, 0x0d0eda4c, 0xe0e5d18e, 0x3a3cb60d, 0x8f7dc7b5, 0x2740d13d, 0x2411cbe3, 0xc55502f4, 0xd6d1c076, 0x7d07ed81, 0x82a67573, 0xa15d7d58, 0x27aded61, 0xf87e46b0, 0x0e64e24a, 0x18ab4380, 0x233065d0, 0x0493e4ab, 0x1a5307ca, 0xe0c4de35, 0x20314b07, 0xd65c4f48, 0x35efe5ac, 0x97124c31, 0x154160c1, 0xd4bf2b73, 0xa3b8a493, 0xbe2cf942, 0x7a8131c1, 0x37952080, 0x602d6624, 0x9b8baefc, 0x4eab182e, 0x49a3a8d4, 0x2f30705b, 0xcada3622, 0xe39793d4, 0x979818b1, 0xe37b1080, 0x34e284a5, 0xa53d17a0, 0x2bbef228, 0x8582cd80, 0xb5d5e5f1, 0x5c09db08, 0xba465091, 0x64045f7c, 0xc7c2bf38, 0xa990b83a, 0xcde967fd, 0xbcf06f16, 0x35052c9e, 0x580d3a8d, 0x761852ad, 0xd32abb68, 0xd3f6fa3b, 0x943877fa, 0xfa7d450e, 0xbc1b7a35, 0x2b3a268c, 0xc940ac5c, 0x867d3f85, 0x755eaf00, 0xa1353106, 0x4f243e84, 0x19e2ea4a, 0x524a9c9a, 0x9d1f087c, 0x69e238bc, 0x5344bd29, 0xb96bda10, 0xa1808dfd, 0x625f9be8, 0x965db46d, 0x65014e1a, 0x6279b478, 0x0990ddcc, 0xb358dafc, 0x7ac1c1b9, 0xc4803b84, 0x40d4351f, 0x7a1a0dc1, 0x78de4b36, 0xb6468ace, 0x51ef3177, 0x2fc9f94f, 0x6303e55a, 0x5d54a1ec, 0x5094973c, 0x9d600f27, 0xc4447501, 0x1f592e14, 0x40c84e1e, 0xbe8af689, 0x3c6c7829, 0x8cd049bd, 0xc505f9f3, 0x69ca63dd, 0xe3dd08e4, 0x3f3bc424, 0x5eb4683c, 0x43a3639e, 0xd687777e, 0xfb94e6ee, 0x0a0ac753, 0xd96eadb2, 0x4da43e60, 0x23264af6, 0xfb5a7d96, 0xd8bda93f, 0xe0305786, 0x42e0516d, 0x61505e74, 0xd3599380, 0x0f74af98, 0xd6ef9d34, 0x2b2f70ab, 0xf5aa4989, 0xc25706a6, 0xc7099c0a, 0x103fb695, 0x93c04d84, 0x3808de1e, 0x353a42c9, 0x9664430e, 0x63cc8e48, 0x97091542, 0x03d78519, 0x5b4eb47a, 0xbe69fd03, 0xa7cd112d, 0x8ae74006, 0x476adb16, 0x94e0c79f, 0xb42310ab, 0xc866a24e, 0x04352fed, 0xa3016937, 0x5dc1ea48, 0xfd2a1532, 0x12f11fa3, 0xae9a7bc1, 0xc1dd6911, 0x3db0e7fb, 0x0f228255, 0x5754c504, 0xa53dd8cf, 0xda8a516d, 0xc8916f0e, 0x52ac5774, 0xb5f50d21, 0x6a59e708, 0x2c956154, 0xdbb434ff, 0xa6b989c9, 0xae21a1c4, 0xc3ca8c67, 0xb8989d5e, 0xdd8c16c7, 0xa0f44995, 0xac67d236, 0x5aa7d61d, 0xd0820dd6, 0x65ffb561, 0xeea84b89, 0xbc394ffb, 0x606d8019, 0x9bc2d51b, 0x56f1e290, 0xfc70bf04, 0xb841f8c5, 0x1ffef030, 0xde942862, 0x2299fb83, 0xc2aad484, 0xabdf93eb, 0x4ac5fd0a, 0xaaf0ca41, 0x6248feea, 0x81cdc217, 0x95112a78, 0x316fbcfb, 0x5f34cdde, 0xfcc1a506, 0x3a12876b, 0x02a025e1, 0xc9400dc9, 0xdfe1a77c, 0x0415e648, 0x46d14c25, 0xf899b2f6, 0xb42b100f, 0x4d67ad23, 0xb569f638, 0x80f987ce, 0xfe9dfed9, 0x43ec9a54, 0x4dae3b9c, 0x6381f9b5, 0xd80f2e7b, 0x30c84ef7, 0x01004ecc, 0x4de702e7, 0x39005f46, 0x5babe6e8, 0x4d57dd8b, 0xe9e6fc64, 0xf97fe8c8, 0x5397ec14, 0x717f7a7f, 0x6f6552af, 0xe833b836, 0x69880e7c, 0xdbd5f7ec, 0x42f352e3, 0x5ab8e676, 0x14a64bd3, 0x42bf7aa1, 0xa2d7bcc5, 0x3df7f2f1, 0x6cbc536a, 0x35dd7546, 0x7b09f7d3, 0x628a0365, 0x87da2285, 0xc4082406, 0x0c1dcebc, 0xffb6556a, 0x0ae02345, 0xb8de98ad, 0x8f6d95e6, 0xa064fa56, 0xe985bdee, 0xf9aaa64d, 0x577c1ed5, 0x10ebfa2c, 0xfc649327, 0xeb9e29c2, 0xa54368d3, 0xd01f34e1, 0xa6fcae0a, 0xb5e582a0, 0x197053b6, 0xc3c19f06, 0x6ba7af20, 0x622dd684, 0xdc8660e2, 0x058a9b8a, 0xac8b8ba2, 0xbe53eab6, 0xbb40d5d8, 0x9f1801ea, 0xb9b0c90b, 0xccf07edc, 0x5c07b518, 0x806093c1, 0x7ce038cb, 0x8e74fb55, 0xd2368ffe, 0x4a60c7de, 0x7e4b7afc, 0x52dc37db, 0xa46ad286, 0x1404b9e3, 0x49c8175d, 0x1c546deb, 0x22ecf6a8, 0xb07442ff, 0x4d07719b, 0x20163c7f, 0x8fc94a55, 0x273181fb, 0x1520a6a1, 0xa7e7544f, 0x02f531d5, 0x2376b588, 0x2e15e627, 0x67be1768, 0x959b9847, 0x310f3ea2, 0x6063c2ee, 0x381df387, 0x0968dced, 0xf9efd0b0, 0xa7e1da32, 0x3043294b, 0x35ccd55f, 0xbba0e732, 0xf461f6e9, 0xd3423c1b, 0x84536152, 0xfc8b72fd, 0x40ef3a91, 0xb20f1e93, 0x84056753, 0x6cd2e250, 0xb0bc485c, 0x37b19bc1, 0x9e7c54b2, 0xe1124fbf, 0x77c45263, 0x9f3503fd, 0x5ab7d7a4, 0xedad228a, 0x64dd072a, 0x1dd61f11, 0x39659df2, 0x6e06b675, 0x8ef3d8e3, 0x4d480161, 0x13c186b9, 0xed582da9, 0x3afbfafa, 0x4476a896, 0x4ac48ff8, 0xaa304d9f, 0x5219694c, 0x21aa3df2, 0x7af29e91, 0xb0ff5c05, 0x18691b06, 0xa9b16a99, 0xe075b164, 0xe6165adf, 0x799654bc, 0x170d0ad4, 0x9c9397b9, 0xd5bc102d, 0x75eb30cf, 0xa10a69b1, 0x8f02d61d, 0xffda6a4c, 0x40df904b, 0x8df9ebc2, 0xc7923dc7, 0xb5913008, 0x133acbda, 0xae9e0e83, 0xc3fc1845, 0x0b088036, 0xb9b7dec5, 0x78f54f80, 0xbc3c5836, 0xbdfa5a5d, 0x899457e1, 0x59c14cf9, 0xc94cf442, 0xe06f9006, 0x23d80b3f, 0x207c3865, 0x654a3502, 0xd8caedeb, 0x1037e94b, 0xa587d5fd, 0x8f9b2531, 0x6d0c8d97, 0xba0ffa10, 0xae2ff785, 0xdf14e75d, 0x7fbe4bc1, 0x5d13fb4e, 0x66fb84d7, 0xb59ac4d5, 0xa79c897d, 0xa660311e, 0xcd004de4, 0x912a2567, 0x027700b4, 0x213e02bc, 0x4469b30b, 0xfcdb0d2b, 0xd35bb3a8, 0x9933b719, 0x4d493526, 0x5edf4698, 0x2d802b5c, 0x37aa6759, 0xae0da18c, 0x87ca98b0, 0x84722f2c, 0xcabebc8b, 0xcd615be3, 0xfba17c51, 0x6c50100c, 0xb2959489, 0x0ec7bdb5, 0x302d1715, 0x654d3a32, 0x9d998078, 0xe9e4b9ad, 0x0f796cef, 0xc0bfb970, 0x733716c7, 0x0000e982, 0x00000000, 0x00000000, 0x00000000, 0x09000000, 0x2d1b100c, 0x003a352f, ]; const MESSAGE: [u8; 64] = [ 29, 204, 154, 221, 65, 56, 204, 167, 12, 130, 160, 47, 200, 7, 250, 159, 194, 82, 16, 98, 102, 89, 177, 73, 39, 15, 105, 116, 233, 169, 31, 160, 5, 186, 46, 229, 44, 126, 198, 98, 20, 39, 194, 203, 249, 170, 183, 196, 80, 111, 6, 194, 23, 17, 183, 73, 119, 95, 8, 123, 190, 17, 14, 186, ]; const MLDSA_MSG: [u32; 16] = [ 0xe703fb78, 0xc41fed22, 0x44e2a5f2, 0x16e60096, 0x5087290d, 0xd90d9a17, 0x6d303b5, 0xd4c62abc, 0xee115f73, 0x48c5f623, 0xdb988435, 0x800af504, 0x3c9e16fb, 0x6ed56c1c, 0xf3aa1bd4, 0xc8f518d4, ]; const MLDSA_PRIVKEY: [u32; 1224] = [ 0xc9f4a875, 0xdad7c056, 0x8fe77f6c, 0x2e723eb0, 0x2a4ffcd1, 0x6049245e, 0x616f610e, 0x884a5a99, 0xc28ec76c, 0x5cb81c95, 0x54d58aea, 0x5f8ebdf2, 0x46127141, 0xb85d2291, 0x71a3cb3a, 0x587a8d8a, 0x280f35b3, 0x44901d76, 0x7df1838d, 0xb85dd20d, 0xc07cc9e6, 0x1eed7b7f, 0xaffc9db5, 0xc2c37f2d, 0xc8812fbb, 0x42af94df, 0x80292427, 0xf5717be2, 0x1f3e3e37, 0x9154b551, 0x39287f47, 0xca2d7927, 0xcc8c2654, 0x96994632, 0x8400ca50, 0xc9512600, 0xb10b1118, 0x86490391, 0x44082259, 0xdc5020, 0x4b52151, 0xc653090, 0xa4d36840, 0xe060111, 0x5231a862, 0x81c05c8, 0x2c28d088, 0x130dc849, 0x24ca40a9, 0x20a28246, 0x9870a723, 0x24d22086, 0x72388a41, 0x6229a209, 0xa0994128, 0x9321b11, 0x1a51869a, 0x25014089, 0xda69391, 0x14d24e3, 0x16996e30, 0x65c40466, 0x168c0a4, 0x926211c0, 0x11a52245, 0x6185a, 0x65a8e21, 0x11a65c25, 0xe28da463, 0xc4832536, 0x4a152141, 0x189a29c, 0x12588823, 0x24a08b91, 0xcc4e1842, 0xb2647044, 0x486c225, 0x5a094322, 0x4e24900, 0x50a2994c, 0x6348b450, 0xc6818a14, 0x114442d, 0x1b8da4e2, 0xb0218425, 0x5068411, 0x8c519653, 0xa60c6018, 0x12251444, 0x9308465b, 0x36cb8628, 0x1905c80, 0x9829b2e2, 0xc7040648, 0x24951345, 0xa24c284b, 0xb2848614, 0x8d80a231, 0xb01b259, 0x91104502, 0x986c250, 0x10483298, 0xa40c2997, 0x65a69225, 0xd34d8609, 0x368c2434, 0x634db21, 0x8a40964b, 0xc4506614, 0x4e092200, 0x814996dc, 0x42d921a2, 0x65a80b45, 0xd28d0862, 0x160b0624, 0x6116e38d, 0xa309890, 0x26cb9102, 0x8128996a, 0xe288b64a, 0xa8e251c8, 0x42345485, 0x5b70a640, 0x182108b8, 0x2d840184, 0xa14d0814, 0x84920a0, 0x5222c809, 0x8c089662, 0x89224892, 0x9144e24d, 0x1c2a3212, 0x926080, 0x2a32dc89, 0x984116d1, 0x24db8006, 0x9161305, 0x898cb8d4, 0x80241198, 0x30485465, 0xd04e2410, 0x3235112, 0x66469a52, 0x51514404, 0x470b85b0, 0xd94d826, 0xda023854, 0x464b0008, 0x85872032, 0xdc51b863, 0x32640930, 0x5925451, 0x1c104292, 0x40c92812, 0x8d86986e, 0x618c971b, 0x40404a06, 0xe12994e, 0x81610659, 0xc2428dc6, 0x11940904, 0x588d8610, 0xc64a71a4, 0x51008161, 0xd891a713, 0x111c2604, 0xc90e450, 0x91098893, 0x30612536, 0x6046592c, 0x2044600, 0x871c44a7, 0xdc60060, 0x908e26d8, 0xa5012834, 0x51a80b60, 0xe1690489, 0x38193100, 0x4d90a050, 0x2031b480, 0x10c37182, 0xc01b62, 0xe33010d9, 0xa0616836, 0x46282400, 0x19013452, 0xa6018032, 0x31c6c280, 0x4c2990db, 0x48204988, 0x69906305, 0x11323010, 0xa8ca2a06, 0x29948260, 0xa192371a, 0x485b6904, 0x6a490250, 0xd40dc20a, 0x6015208, 0x2db2a10e, 0x51422802, 0x12883000, 0x48028886, 0x6320a649, 0xb85a4d82, 0x70a00424, 0x24212864, 0x24518c21, 0x6d301a46, 0x43204312, 0x6888c28, 0x40c62080, 0xd80616c3, 0x245051b4, 0xc10d052, 0x1b4cb702, 0x18935030, 0x6040491, 0x928cc0c9, 0x49116580, 0x8135122e, 0x8480a844, 0x86c83024, 0x4502da41, 0xc091b044, 0x2993190, 0x50311260, 0xd388c253, 0xb86200b6, 0x9945c70, 0x160a61b, 0x410b0509, 0x42445190, 0x5c414024, 0xd10590, 0x41b4044a, 0x9091b2dc, 0xb2c93240, 0x90c61b70, 0x4845c2e2, 0xc89048c4, 0x6e292029, 0x816c4221, 0x39210d80, 0x85b91340, 0x9951b4d4, 0x86dc9184, 0xa231001, 0x90288082, 0x40cb1192, 0x9c01141, 0x616d4860, 0x908c0c46, 0x48004901, 0x114800d9, 0x24986108, 0x41005024, 0x831b803, 0x2834886, 0x60c12405, 0x410dc664, 0x20912502, 0x9197206d, 0x419144d2, 0x38cc4044, 0x4a424890, 0x211321c, 0x825a2645, 0x70028450, 0x1168b688, 0x71b6210, 0x46492322, 0x230c9681, 0xc2493138, 0x65b8da89, 0xd964984a, 0x6124008, 0x113106a, 0xdc42305a, 0x84c481b0, 0x2486cb40, 0x58064914, 0x80136d88, 0x64a00811, 0xc8096d9, 0xa6615016, 0x8a304245, 0x1a6c9311, 0x26448214, 0x4198420d, 0x8a6a2, 0x32434887, 0x6e06234a, 0xc261301c, 0x7026228, 0x80870b60, 0x198e3253, 0x84e08cc8, 0x8a471121, 0x9b444452, 0x80586c16, 0x8d04c821, 0x9240620, 0x944b10c8, 0x3000a168, 0x90c9214, 0x82412e12, 0x4da25c80, 0x440e34d2, 0x44488c90, 0x402191, 0x968c901, 0x28d36c03, 0x6084b09, 0x8c0906d8, 0x10108020, 0x5128e148, 0xd4008643, 0x148b01b0, 0x71b6200c, 0xc11b712, 0xd32040, 0x8a086208, 0x3652662, 0x22594228, 0x30824811, 0x1c6cc421, 0x211a8225, 0x2da8030d, 0xa011a0da, 0x3207022, 0x70904148, 0xe00d16d0, 0x18844d48, 0x44189a4a, 0x2049c28c, 0xa5194c39, 0x44c70241, 0xdb52281a, 0x34247186, 0x10309404, 0x81610221, 0xc8230c94, 0x40968181, 0x51121523, 0x40a40834, 0x51b88c8e, 0xda8222a0, 0xc8204642, 0x188cc69, 0x1a88a620, 0x924b6dc9, 0x4cb85388, 0x94a1290, 0x6504d09, 0x80c2a08a, 0x40694662, 0x48dc8048, 0x230d466, 0x206a360a, 0x28cb31c6, 0x30392252, 0xb08a288, 0x14401032, 0x6828a429, 0xd48d0223, 0xc3028e10, 0x2a268424, 0xb45b404, 0x20804d49, 0x62110045, 0xb84400c, 0x34044939, 0x6388a50, 0xc845260a, 0x94e04416, 0x1421130, 0x6468b701, 0x384a1082, 0x45b80a12, 0xe060c2d4, 0x30cc6202, 0x29368b89, 0x2128c8a1, 0x34642109, 0x2d966142, 0x810004d1, 0x38524510, 0x2e230044, 0x188e1814, 0x368109b4, 0x7146604e, 0xe76666a4, 0x33efedc3, 0xd222bbd3, 0x1a55af66, 0x6c858d9e, 0x26689e8b, 0xbd047ba7, 0x3c37e65e, 0xbbf683a7, 0x4a2793cc, 0x3b30de40, 0x74ff227, 0xff55a17e, 0x6df92c53, 0xf38f66, 0xcba879ed, 0xd5e69d19, 0x4fac09e8, 0xbc8791d5, 0xd2c8e04, 0x9fa05879, 0x7828cf8, 0xdf00d32a, 0x7b0d31eb, 0x45765743, 0x2de7e899, 0xb9486fbf, 0x2817864f, 0xf84e243e, 0x9ab92d31, 0x841e8936, 0xb231e68f, 0x4b5e097f, 0x5807144a, 0x19cb19a3, 0x8876a83b, 0xf549a831, 0xfb140d6c, 0x90cc09de, 0xfb6efd4f, 0x22db8186, 0xc6a2f48a, 0x1a57af1c, 0x533eca39, 0xea3a61f9, 0xc8ba7d0f, 0xf0520375, 0xd40608da, 0xc8d40286, 0x7163f389, 0x83a6a096, 0x3a60a5d3, 0x36bc58b4, 0xc4898969, 0x5b3cba5b, 0xcf803db2, 0x20238ec5, 0xa9492f49, 0x59ff78fe, 0x1cc8b2a1, 0xe0f5d8c5, 0xd4ec55ef, 0x565fef5e, 0xaf237033, 0xa5ee97a7, 0xe7fb6421, 0x22d9c806, 0x41e6a0bf, 0xe9b831ed, 0xd6ca6d7f, 0x416d7ae3, 0x985d4bf1, 0x829c4ff9, 0x3c5edcbd, 0x972e94a0, 0x4ece10ef, 0x9ebf0b53, 0x7a6bfe3e, 0xe49ab80b, 0xd0ed1e4f, 0xf95c172, 0xfd276311, 0x3fe50700, 0x989df46b, 0x8e59f55e, 0xebdeb443, 0xb1dd951, 0x417b82f4, 0x27ec8de0, 0x358a143e, 0x4ae57ee9, 0xfccfa4ea, 0x51ae75e5, 0xd538cc79, 0x334a496a, 0x19c32f10, 0x8bc8c0bb, 0xffc94657, 0x7a3c53da, 0xf4b795fd, 0x76321e2c, 0x3cc6d78d, 0x32791e9b, 0x3cea0590, 0x7665c106, 0x3ff1a68e, 0x9040139, 0xa01f50d1, 0xa059af88, 0x540d34be, 0xbd769f26, 0x70371479, 0xf6695749, 0xe4bb0585, 0x7fddebdf, 0x2c0340cb, 0xe0308566, 0x7b6f4412, 0x79a6691, 0xc9c1410b, 0x1ec00de8, 0x8b4a3e1b, 0xca384c6a, 0x26b2acbc, 0xcb9d31e0, 0xe7254517, 0x436ee950, 0xb09169e7, 0x49157143, 0xbc427966, 0x3933bc1, 0x186da822, 0x22084c21, 0x851daed, 0x87629156, 0x39a759ec, 0xd12e12d2, 0x54040dcd, 0xcc2ba1a7, 0x1a266e1f, 0x387027a8, 0x8da7964c, 0x6bef2821, 0xbc3672da, 0xce66d2f6, 0xc5643bc4, 0xcd667f5f, 0x4662e385, 0x2622d5c8, 0x83412cf, 0x6b33f67c, 0xd53806fc, 0x42e7c93e, 0x45596e01, 0xeb30c746, 0x5b4e384e, 0x4757ec65, 0x1da5e67b, 0x9153b508, 0xfdb5bf32, 0x755dcbab, 0xd7044d8, 0x4657355, 0x6a5bf10c, 0x55f1443e, 0x919c39e0, 0x29aaebe9, 0x33cc838f, 0x961d210e, 0xd8a485a3, 0x1c8bb5c2, 0xeb2a067d, 0xbc64ee8f, 0x2afa1db7, 0x6437c695, 0x2d71b860, 0x24118a19, 0xccfb7494, 0x83bb2e84, 0xf8c20233, 0x86aa057c, 0x4f4da295, 0x2e2261bb, 0xe2c659a, 0x4a12836f, 0x8ea71897, 0xe9b7a53c, 0x5bfda095, 0x2da57957, 0x422ad6bc, 0xb98242a7, 0x2e01e250, 0xb642b434, 0x98c6cdc3, 0x24c7bf98, 0xd9baf251, 0x88163f20, 0xe4f5ac70, 0x3ac7c7de, 0x764842aa, 0x73797932, 0xc07625c0, 0xbc699055, 0xb7ded1e9, 0x3cec83de, 0x23ea92a3, 0x4c1ba061, 0xb8199849, 0xd2b45579, 0x86e4dcca, 0xbc5a4312, 0xc8455056, 0xe44a1707, 0xf6fcde0, 0x2a2b4a1b, 0x6cdee068, 0x433a3dc4, 0xa9b06608, 0xa4251d66, 0x30391fc6, 0x3ca7e09d, 0x3fff07ac, 0x37fff98e, 0x3656db5a, 0x4ab2e768, 0x96539757, 0x8a397687, 0x40559803, 0x2e889d43, 0xfb90a75d, 0x2168cc4, 0x6ab2bbac, 0x7effa819, 0xd52d1440, 0x588a4fc0, 0xecd30a03, 0xc83cd973, 0xeb33fb36, 0x37b87a36, 0x3b85b2dc, 0xab20a9c8, 0xd345da88, 0xc7fac94e, 0x1d644c6e, 0xf624b0c9, 0xd0494c8c, 0x19fb50f8, 0x4488c08a, 0x2696482a, 0xf48c635e, 0x299749df, 0xa3b5eab8, 0x6c0618d1, 0x791d04a4, 0x34857033, 0xdffc7280, 0xe4522fed, 0xa98e8ae6, 0xec17b5f7, 0xf29ffbd1, 0x47cccef4, 0xb0f6d39d, 0x6706ad27, 0xbe82a4ec, 0x6663b6c3, 0x79160070, 0xe02d8ec9, 0x4cfa3003, 0x7b8cb852, 0x2bd64732, 0x34d7af39, 0xc9213f5a, 0xc0d27ab6, 0x7ce71d40, 0x571ef697, 0x36118782, 0x13ddb51a, 0x9de3f40e, 0xad6f2df6, 0x562433c9, 0xff9de84b, 0x89455154, 0x2069d8e5, 0xa55c479f, 0x439670aa, 0xdc6341e3, 0x3d54f2f2, 0x90d0ef7f, 0x9c875bfe, 0xeeacbb45, 0x22dcf450, 0xe5d034e5, 0x383ae3ac, 0xd69927e5, 0x47d6284a, 0x9b3b1ad0, 0xd4d80922, 0xe6d704b4, 0xd3775e68, 0xd9e53abd, 0xe02cb9f8, 0x38262475, 0x3c2543a4, 0x233bbdb8, 0x562f72f5, 0x4c3f419f, 0xdcfd0141, 0x6928cb2c, 0x86eafb5f, 0x40b6c6b0, 0x900c8726, 0x516e9f9c,
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/csrng_tests.rs
drivers/test-fw/src/bin/csrng_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: csrng_tests.rs Abstract: File contains test cases for CSRNG API --*/ #![no_std] #![no_main] use caliptra_drivers::{Csrng, CsrngSeed}; use caliptra_registers::{csrng::CsrngReg, entropy_src::EntropySrcReg, soc_ifc::SocIfcReg}; use caliptra_test_harness::test_suite; // From: // https://github.com/lowRISC/opentitan/blob/ff70cfe194f5a2bb08c1a87a949b5c45746a5d99/sw/device/tests/csrng_smoketest.c#L27 fn test_ctr_drbg_ctr0_smoke() { let csrng_reg = unsafe { CsrngReg::new() }; let entropy_src_reg = unsafe { EntropySrcReg::new() }; let soc_ifc_reg = unsafe { SocIfcReg::new() }; const SEED: CsrngSeed = CsrngSeed::Constant(&[ 0x73bec010, 0x9262474c, 0x16a30f76, 0x531b51de, 0x2ee494e5, 0xdfec9db3, 0xcb7a879d, 0x5600419c, 0xca79b0b0, 0xdda33b5c, 0xa468649e, 0xdf5d73fa, ]); const EXPECTED_OUTPUT: [u32; 12] = [ 0x725eda90, 0xc79b4a14, 0xe43b74ac, 0x9d9a938b, 0xc395a610, 0x4c5a1483, 0xa45f15e8, 0x2708cbef, 0x89eb63a9, 0x70cdc6bc, 0x710daba1, 0xed39808c, ]; let mut csrng = Csrng::with_seed(csrng_reg, entropy_src_reg, &soc_ifc_reg, SEED).expect("construct CSRNG"); // The original OpenTitan test tosses the first call to generate. let _ = csrng .generate12() .expect("first call to generate should work"); assert_eq!( csrng .generate12() .expect("second call to generate should work"), EXPECTED_OUTPUT ); } // Note: this test is sensitive to the TRNG bits that are fed into the emulation model. fn test_entropy_src_seed() { let csrng_reg = unsafe { CsrngReg::new() }; let entropy_src_reg = unsafe { EntropySrcReg::new() }; let soc_ifc_reg = unsafe { SocIfcReg::new() }; const EXPECTED_OUTPUT: [u32; 4] = [0xca3d3c2f, 0x552adb53, 0xa9749c5d, 0xdabbe4c3]; let mut csrng = Csrng::new(csrng_reg, entropy_src_reg, &soc_ifc_reg).expect("construct CSRSNG"); assert_eq!( csrng .generate12() .expect("first call to generate should work")[..EXPECTED_OUTPUT.len()], EXPECTED_OUTPUT ); } fn test_zero_health_fails() { let csrng_reg = unsafe { CsrngReg::new() }; let entropy_src_reg = unsafe { EntropySrcReg::new() }; let soc_ifc_reg = unsafe { SocIfcReg::new() }; let csrng = Csrng::new(csrng_reg, entropy_src_reg, &soc_ifc_reg).expect("construct CSRNG"); let counts = csrng.health_fail_counts(); assert_eq!(counts.total, 0, "Expected zero total health check fails"); assert_eq!( u32::from(counts.specific), 0, "Expected zero specific health check fails" ); } test_suite! { test_ctr_drbg_ctr0_smoke, test_entropy_src_seed, test_zero_health_fails, // TODO(rkr35): Induce failing health checks and assert we can observe them. // TODO(rkr35): Test Reseed and Update commands. }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/sha384_tests.rs
drivers/test-fw/src/bin/sha384_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha384_tests.rs Abstract: File contains test cases for SHA-384 API --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::sha2_512_384::Sha2DigestOpTrait; use caliptra_drivers::{Array4x12, PcrBank, PcrId, Sha2_512_384}; use caliptra_kat::Sha384Kat; use caliptra_registers::{pv::PvReg, sha512::Sha512Reg}; use caliptra_test_harness::test_suite; fn test_digest0() { let mut sha2 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0x38, 0xB0, 0x60, 0xA7, 0x51, 0xAC, 0x96, 0x38, 0x4C, 0xD9, 0x32, 0x7E, 0xB1, 0xB1, 0xE3, 0x6A, 0x21, 0xFD, 0xB7, 0x11, 0x14, 0xBE, 0x07, 0x43, 0x4C, 0x0C, 0xC7, 0xBF, 0x63, 0xF6, 0xE1, 0xDA, 0x27, 0x4E, 0xDE, 0xBF, 0xE7, 0x6F, 0x65, 0xFB, 0xD5, 0x1A, 0xD2, 0xF1, 0x48, 0x98, 0xB9, 0x5B, ]; let data = &[]; let digest = sha2.sha384_digest(data).unwrap(); assert_eq!(digest, Array4x12::from(expected)); } fn test_digest1() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0xCB, 0x00, 0x75, 0x3F, 0x45, 0xA3, 0x5E, 0x8B, 0xB5, 0xA0, 0x3D, 0x69, 0x9A, 0xC6, 0x50, 0x07, 0x27, 0x2C, 0x32, 0xAB, 0x0E, 0xDE, 0xD1, 0x63, 0x1A, 0x8B, 0x60, 0x5A, 0x43, 0xFF, 0x5B, 0xED, 0x80, 0x86, 0x07, 0x2B, 0xA1, 0xE7, 0xCC, 0x23, 0x58, 0xBA, 0xEC, 0xA1, 0x34, 0xC8, 0x25, 0xA7, ]; let data = "abc".as_bytes(); let digest = sha384.sha384_digest(data.into()).unwrap(); assert_eq!(digest, Array4x12::from(expected)); } fn test_digest2() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0x33, 0x91, 0xFD, 0xDD, 0xFC, 0x8D, 0xC7, 0x39, 0x37, 0x07, 0xA6, 0x5B, 0x1B, 0x47, 0x09, 0x39, 0x7C, 0xF8, 0xB1, 0xD1, 0x62, 0xAF, 0x05, 0xAB, 0xFE, 0x8F, 0x45, 0x0D, 0xE5, 0xF3, 0x6B, 0xC6, 0xB0, 0x45, 0x5A, 0x85, 0x20, 0xBC, 0x4E, 0x6F, 0x5F, 0xE9, 0x5B, 0x1F, 0xE3, 0xC8, 0x45, 0x2B, ]; let data = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".as_bytes(); let digest = sha384.sha384_digest(data.into()).unwrap(); assert_eq!(digest, Array4x12::from(expected)); } fn test_digest3() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0x09, 0x33, 0x0C, 0x33, 0xF7, 0x11, 0x47, 0xE8, 0x3D, 0x19, 0x2F, 0xC7, 0x82, 0xCD, 0x1B, 0x47, 0x53, 0x11, 0x1B, 0x17, 0x3B, 0x3B, 0x05, 0xD2, 0x2F, 0xA0, 0x80, 0x86, 0xE3, 0xB0, 0xF7, 0x12, 0xFC, 0xC7, 0xC7, 0x1A, 0x55, 0x7E, 0x2D, 0xB9, 0x66, 0xC3, 0xE9, 0xFA, 0x91, 0x74, 0x60, 0x39, ]; let data = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".as_bytes(); let digest = sha384.sha384_digest(data.into()).unwrap(); assert_eq!(digest, Array4x12::from(expected)); } fn test_op0() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0x38, 0xB0, 0x60, 0xA7, 0x51, 0xAC, 0x96, 0x38, 0x4C, 0xD9, 0x32, 0x7E, 0xB1, 0xB1, 0xE3, 0x6A, 0x21, 0xFD, 0xB7, 0x11, 0x14, 0xBE, 0x07, 0x43, 0x4C, 0x0C, 0xC7, 0xBF, 0x63, 0xF6, 0xE1, 0xDA, 0x27, 0x4E, 0xDE, 0xBF, 0xE7, 0x6F, 0x65, 0xFB, 0xD5, 0x1A, 0xD2, 0xF1, 0x48, 0x98, 0xB9, 0x5B, ]; let mut digest = Array4x12::default(); let digest_op = sha384.sha384_digest_init().unwrap(); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x12::from(expected)); } fn test_op1() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0x38, 0xB0, 0x60, 0xA7, 0x51, 0xAC, 0x96, 0x38, 0x4C, 0xD9, 0x32, 0x7E, 0xB1, 0xB1, 0xE3, 0x6A, 0x21, 0xFD, 0xB7, 0x11, 0x14, 0xBE, 0x07, 0x43, 0x4C, 0x0C, 0xC7, 0xBF, 0x63, 0xF6, 0xE1, 0xDA, 0x27, 0x4E, 0xDE, 0xBF, 0xE7, 0x6F, 0x65, 0xFB, 0xD5, 0x1A, 0xD2, 0xF1, 0x48, 0x98, 0xB9, 0x5B, ]; let mut digest = Array4x12::default(); let digest_op = sha384.sha384_digest_init().unwrap(); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x12::from(expected)); } fn test_op2() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0xCB, 0x00, 0x75, 0x3F, 0x45, 0xA3, 0x5E, 0x8B, 0xB5, 0xA0, 0x3D, 0x69, 0x9A, 0xC6, 0x50, 0x07, 0x27, 0x2C, 0x32, 0xAB, 0x0E, 0xDE, 0xD1, 0x63, 0x1A, 0x8B, 0x60, 0x5A, 0x43, 0xFF, 0x5B, 0xED, 0x80, 0x86, 0x07, 0x2B, 0xA1, 0xE7, 0xCC, 0x23, 0x58, 0xBA, 0xEC, 0xA1, 0x34, 0xC8, 0x25, 0xA7, ]; let data = "abc".as_bytes(); let mut digest = Array4x12::default(); let mut digest_op = sha384.sha384_digest_init().unwrap(); assert!(digest_op.update(data).is_ok()); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x12::from(expected)); } fn test_op3() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0x33, 0x91, 0xFD, 0xDD, 0xFC, 0x8D, 0xC7, 0x39, 0x37, 0x07, 0xA6, 0x5B, 0x1B, 0x47, 0x09, 0x39, 0x7C, 0xF8, 0xB1, 0xD1, 0x62, 0xAF, 0x05, 0xAB, 0xFE, 0x8F, 0x45, 0x0D, 0xE5, 0xF3, 0x6B, 0xC6, 0xB0, 0x45, 0x5A, 0x85, 0x20, 0xBC, 0x4E, 0x6F, 0x5F, 0xE9, 0x5B, 0x1F, 0xE3, 0xC8, 0x45, 0x2B, ]; let data = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".as_bytes(); let mut digest = Array4x12::default(); let mut digest_op = sha384.sha384_digest_init().unwrap(); assert!(digest_op.update(data).is_ok()); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x12::from(expected)); } fn test_op4() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0x09, 0x33, 0x0C, 0x33, 0xF7, 0x11, 0x47, 0xE8, 0x3D, 0x19, 0x2F, 0xC7, 0x82, 0xCD, 0x1B, 0x47, 0x53, 0x11, 0x1B, 0x17, 0x3B, 0x3B, 0x05, 0xD2, 0x2F, 0xA0, 0x80, 0x86, 0xE3, 0xB0, 0xF7, 0x12, 0xFC, 0xC7, 0xC7, 0x1A, 0x55, 0x7E, 0x2D, 0xB9, 0x66, 0xC3, 0xE9, 0xFA, 0x91, 0x74, 0x60, 0x39, ]; let data = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".as_bytes(); let mut digest = Array4x12::default(); let mut digest_op = sha384.sha384_digest_init().unwrap(); assert!(digest_op.update(data).is_ok()); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x12::from(expected)); } fn test_op5() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0x9D, 0x0E, 0x18, 0x09, 0x71, 0x64, 0x74, 0xCB, 0x08, 0x6E, 0x83, 0x4E, 0x31, 0x0A, 0x4A, 0x1C, 0xED, 0x14, 0x9E, 0x9C, 0x00, 0xF2, 0x48, 0x52, 0x79, 0x72, 0xCE, 0xC5, 0x70, 0x4C, 0x2A, 0x5B, 0x07, 0xB8, 0xB3, 0xDC, 0x38, 0xEC, 0xC4, 0xEB, 0xAE, 0x97, 0xDD, 0xD8, 0x7F, 0x3D, 0x89, 0x85, ]; const DATA: [u8; 1000] = [0x61; 1000]; let mut digest = Array4x12::default(); let mut digest_op = sha384.sha384_digest_init().unwrap(); for _ in 0..1_000 { assert!(digest_op.update(&DATA).is_ok()); } let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x12::from(expected)); } fn test_op6() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0x9c, 0x2f, 0x48, 0x76, 0x0d, 0x13, 0xac, 0x42, 0xea, 0xd1, 0x96, 0xe5, 0x4d, 0xcb, 0xaa, 0x5e, 0x58, 0x72, 0x06, 0x62, 0xa9, 0x6b, 0x91, 0x94, 0xe9, 0x81, 0x33, 0x29, 0xbd, 0xb6, 0x27, 0xc7, 0xc1, 0xca, 0x77, 0x15, 0x31, 0x16, 0x32, 0xc1, 0x39, 0xe7, 0xa3, 0x59, 0x14, 0xfc, 0x1e, 0xcd, ]; let data = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz".as_bytes(); let mut digest = Array4x12::default(); let mut digest_op = sha384.sha384_digest_init().unwrap(); for idx in 0..data.len() { assert!(digest_op.update(&data[idx..idx + 1]).is_ok()); } let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x12::from(expected)); } fn test_op7() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0x67, 0x4b, 0x2e, 0x80, 0xff, 0x8d, 0x94, 0x00, 0x8d, 0xe7, 0x40, 0x9c, 0x7b, 0x1f, 0x87, 0x8f, 0x9f, 0xae, 0x3a, 0x0a, 0x6d, 0xae, 0x2f, 0x98, 0x2c, 0xca, 0x7e, 0x3a, 0xae, 0xf9, 0x1b, 0xf3, 0x25, 0xd3, 0xeb, 0x56, 0x82, 0x63, 0xa2, 0xe1, 0xe6, 0x85, 0x6a, 0xc7, 0x50, 0x70, 0x06, 0x2a, ]; let data = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx".as_bytes(); let mut digest = Array4x12::default(); let mut digest_op = sha384.sha384_digest_init().unwrap(); for idx in 0..data.len() { assert!(digest_op.update(&data[idx..idx + 1]).is_ok()); } let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x12::from(expected)); } fn test_op8() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected: [u8; 48] = [ 0x55, 0x23, 0xcf, 0xb7, 0x7f, 0x9c, 0x55, 0xe0, 0xcc, 0xaf, 0xec, 0x5b, 0x87, 0xd7, 0x9c, 0xde, 0x64, 0x30, 0x12, 0x28, 0x3b, 0x71, 0x18, 0x8e, 0x40, 0x8c, 0x5a, 0xea, 0xe9, 0x19, 0xa3, 0xf2, 0x93, 0x37, 0x57, 0x4d, 0x5c, 0x72, 0x9b, 0x33, 0x9d, 0x95, 0x53, 0x98, 0x4a, 0xb0, 0x01, 0x4e, ]; let data = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefgh".as_bytes(); let mut digest = Array4x12::default(); let mut digest_op = sha384.sha384_digest_init().unwrap(); for idx in 0..data.len() { assert!(digest_op.update(&data[idx..idx + 1]).is_ok()); } let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x12::from(expected)); } fn test_pcr_hash_extend_single_block() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let mut pcr_bank = unsafe { PcrBank::new(PvReg::new()) }; // fn change_endianess(arr: mut &[u8]) { // for idx in (0..self.len()).step_by(4) { // self.swap(idx, idx + 3); // self.swap(idx + 1, idx + 2); // } // } let expected_round_1: [u8; 48] = [ 0x4d, 0xca, 0xf1, 0x2f, 0xab, 0xaa, 0x55, 0x47, 0xf4, 0x6c, 0x32, 0x64, 0xb1, 0xe4, 0x5b, 0xc4, 0x5, 0x5c, 0x0, 0xe, 0x66, 0x2c, 0x6c, 0x8a, 0x2c, 0xca, 0x71, 0x2b, 0x44, 0x2d, 0x82, 0x6a, 0xf0, 0xbc, 0x35, 0x96, 0x2b, 0x59, 0x45, 0x17, 0xb3, 0x2f, 0xe1, 0x66, 0x73, 0xd1, 0x20, 0x30, ]; let expected_round_2: [u8; 48] = [ 0xe0, 0x4, 0x44, 0x8, 0xb7, 0x28, 0xe8, 0xcc, 0x18, 0x76, 0x1e, 0x30, 0xde, 0x50, 0xb0, 0xa5, 0x30, 0xd7, 0xfa, 0x58, 0x78, 0x62, 0x8, 0xc2, 0xb1, 0x75, 0xa9, 0x7c, 0x6c, 0x25, 0x50, 0x50, 0x4, 0x4c, 0x6c, 0x2f, 0xcf, 0xc6, 0x40, 0x46, 0xcc, 0xea, 0x1c, 0x3a, 0xe1, 0x2e, 0xe6, 0x72, ]; let data: [u8; 48] = [ 0x9c, 0x2f, 0x48, 0x76, 0x0d, 0x13, 0xac, 0x42, 0xea, 0xd1, 0x96, 0xe5, 0x4d, 0xcb, 0xaa, 0x5e, 0x58, 0x72, 0x06, 0x62, 0xa9, 0x6b, 0x91, 0x94, 0xe9, 0x81, 0x33, 0x29, 0xbd, 0xb6, 0x27, 0xc7, 0xc1, 0xca, 0x77, 0x15, 0x31, 0x16, 0x32, 0xc1, 0x39, 0xe7, 0xa3, 0x59, 0x14, 0xfc, 0x1e, 0xcd, ]; pcr_bank.erase_all_pcrs(); // Call gen_pcr_hash first to ensure that software workaround for // https://github.com/chipsalliance/caliptra-rtl/issues/375 in SHA // driver works as expected. let _ = sha384.gen_pcr_hash([0; 32].into()); // Round 1: PCR is all zeros. let result = sha384.pcr_extend(PcrId::PcrId0, &data); assert!(result.is_ok()); assert_eq!( pcr_bank.read_pcr(PcrId::PcrId0), Array4x12::from(expected_round_1) ); // Round 2: PCR is expected_round_1 let result = sha384.pcr_extend(PcrId::PcrId0, &data); assert!(result.is_ok()); assert_eq!( pcr_bank.read_pcr(PcrId::PcrId0), Array4x12::from(expected_round_2) ); } fn test_pcr_hash_extend_single_block_2() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let mut pcr_bank = unsafe { PcrBank::new(PvReg::new()) }; let expected_round_1: [u8; 48] = [ 0x4d, 0xca, 0xf1, 0x2f, 0xab, 0xaa, 0x55, 0x47, 0xf4, 0x6c, 0x32, 0x64, 0xb1, 0xe4, 0x5b, 0xc4, 0x5, 0x5c, 0x0, 0xe, 0x66, 0x2c, 0x6c, 0x8a, 0x2c, 0xca, 0x71, 0x2b, 0x44, 0x2d, 0x82, 0x6a, 0xf0, 0xbc, 0x35, 0x96, 0x2b, 0x59, 0x45, 0x17, 0xb3, 0x2f, 0xe1, 0x66, 0x73, 0xd1, 0x20, 0x30, ]; let expected_round_2: [u8; 48] = [ 0x13, 0xc4, 0x1e, 0x3a, 0xd2, 0x7f, 0x9d, 0xaa, 0xdb, 0x92, 0x8f, 0x25, 0x9d, 0x35, 0xf9, 0xd1, 0x3d, 0xeb, 0x13, 0x39, 0x73, 0x2, 0x19, 0x21, 0x98, 0x7b, 0x32, 0x2b, 0xb6, 0xd4, 0xfa, 0xb0, 0xcc, 0x4f, 0xae, 0xfa, 0x43, 0xf1, 0xf7, 0x12, 0x1e, 0x66, 0x99, 0x7a, 0xb5, 0xdf, 0xa0, 0x3d, ]; let data: [u8; 48] = [ 0x9c, 0x2f, 0x48, 0x76, 0x0d, 0x13, 0xac, 0x42, 0xea, 0xd1, 0x96, 0xe5, 0x4d, 0xcb, 0xaa, 0x5e, 0x58, 0x72, 0x06, 0x62, 0xa9, 0x6b, 0x91, 0x94, 0xe9, 0x81, 0x33, 0x29, 0xbd, 0xb6, 0x27, 0xc7, 0xc1, 0xca, 0x77, 0x15, 0x31, 0x16, 0x32, 0xc1, 0x39, 0xe7, 0xa3, 0x59, 0x14, 0xfc, 0x1e, 0xcd, ]; pcr_bank.erase_all_pcrs(); // Round 1: PCR is all zeros. let result = sha384.pcr_extend(PcrId::PcrId0, &data); assert!(result.is_ok()); assert_eq!( pcr_bank.read_pcr(PcrId::PcrId0), Array4x12::from(expected_round_1) ); // Round 2: PCR is expected_round_1 let result = sha384.pcr_extend(PcrId::PcrId0, &[]); assert!(result.is_ok()); assert_eq!( pcr_bank.read_pcr(PcrId::PcrId0), Array4x12::from(expected_round_2) ); } fn test_pcr_hash_extend_single_block_3() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let mut pcr_bank = unsafe { PcrBank::new(PvReg::new()) }; let expected_round_1: [u8; 48] = [ 0x4d, 0xca, 0xf1, 0x2f, 0xab, 0xaa, 0x55, 0x47, 0xf4, 0x6c, 0x32, 0x64, 0xb1, 0xe4, 0x5b, 0xc4, 0x5, 0x5c, 0x0, 0xe, 0x66, 0x2c, 0x6c, 0x8a, 0x2c, 0xca, 0x71, 0x2b, 0x44, 0x2d, 0x82, 0x6a, 0xf0, 0xbc, 0x35, 0x96, 0x2b, 0x59, 0x45, 0x17, 0xb3, 0x2f, 0xe1, 0x66, 0x73, 0xd1, 0x20, 0x30, ]; let expected_round_2: [u8; 48] = [ 0xa1, 0xaa, 0x37, 0xde, 0x2b, 0x9f, 0x9e, 0x93, 0xac, 0xd4, 0x38, 0xbb, 0x2b, 0x80, 0xf4, 0xf4, 0x88, 0x5f, 0x6b, 0x96, 0xef, 0x2f, 0xe8, 0x74, 0xd8, 0x2f, 0x46, 0x77, 0x65, 0x35, 0x7, 0x66, 0x34, 0x1a, 0x62, 0x43, 0xf4, 0xaa, 0x72, 0x26, 0x4f, 0x10, 0xe0, 0xa5, 0x1b, 0x77, 0xae, 0xc3, ]; let data: [u8; 48] = [ 0x9c, 0x2f, 0x48, 0x76, 0x0d, 0x13, 0xac, 0x42, 0xea, 0xd1, 0x96, 0xe5, 0x4d, 0xcb, 0xaa, 0x5e, 0x58, 0x72, 0x06, 0x62, 0xa9, 0x6b, 0x91, 0x94, 0xe9, 0x81, 0x33, 0x29, 0xbd, 0xb6, 0x27, 0xc7, 0xc1, 0xca, 0x77, 0x15, 0x31, 0x16, 0x32, 0xc1, 0x39, 0xe7, 0xa3, 0x59, 0x14, 0xfc, 0x1e, 0xcd, ]; let extended_data: [u8; 1] = [0xa]; pcr_bank.erase_all_pcrs(); // Round 1: PCR is all zeros. let result = sha384.pcr_extend(PcrId::PcrId0, &data); assert!(result.is_ok()); assert_eq!( pcr_bank.read_pcr(PcrId::PcrId0), Array4x12::from(expected_round_1) ); // Round 2: PCR is expected_round_1 let result = sha384.pcr_extend(PcrId::PcrId0, &extended_data); assert!(result.is_ok()); assert_eq!( pcr_bank.read_pcr(PcrId::PcrId0), Array4x12::from(expected_round_2) ); } fn test_pcr_hash_extend_limit() { let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let data_allowed: [u8; 79] = [0u8; 79]; let data_not_allowed: [u8; 80] = [0u8; 80]; let result = sha384.pcr_extend(PcrId::PcrId0, &data_allowed); assert!(result.is_ok()); let result = sha384.pcr_extend(PcrId::PcrId0, &data_not_allowed); assert!(result.is_err()); } fn test_kat() { // Init CFI CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut sha384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; assert_eq!(Sha384Kat::default().execute(&mut sha384).is_ok(), true); } test_suite! { test_kat, test_digest0, test_digest1, test_digest2, test_digest3, test_op0, test_op1, test_op2, test_op3, test_op4, test_op5, test_op6, test_op7, test_op8, test_pcr_hash_extend_single_block, test_pcr_hash_extend_single_block_2, test_pcr_hash_extend_single_block_3, test_pcr_hash_extend_limit, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/dma_sha384_tests.rs
drivers/test-fw/src/bin/dma_sha384_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: dma_sha384_tests.rs Abstract: File contains test cases for DMA SHA384 operations --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{ AesDmaMode, Array4x16, AxiAddr, Dma, DmaRecovery, Sha2_512_384, Sha2_512_384Acc, ShaAccLockState, SocIfc, StreamEndianness, }; use caliptra_registers::sha512::Sha512Reg; use caliptra_registers::sha512_acc::Sha512AccCsr; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_test_harness::test_suite; const TEST_DATA_SIZE: usize = 1024; // 1KB of test data const MCU_SRAM_OFFSET: u64 = 0xc0_0000; fn test_dma_sha384_mcu_sram() { // Init CFI CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let dma = Dma::default(); { // the SHA accelerator is locked by default by the uC, so unlock it let mut digest = Array4x16::default(); let mut sha_acc = unsafe { Sha2_512_384Acc::new(Sha512AccCsr::new()) }; let mut op = sha_acc .try_start_operation(ShaAccLockState::AssumedLocked) .unwrap() .unwrap(); op.digest_512(0, 0, StreamEndianness::Reorder, &mut digest) .unwrap(); } let mut sha_acc = unsafe { Sha2_512_384Acc::new(Sha512AccCsr::new()) }; let mut sha2_512_384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let soc_ifc = SocIfc::new(unsafe { SocIfcReg::new() }); // test only runs in subsystem mode if !soc_ifc.subsystem_mode() { return; } // Generate test data - using a simple pattern for reproducibility let mut test_data = [0u32; TEST_DATA_SIZE / 4]; for (i, word) in test_data.iter_mut().enumerate() { *word = (i as u32).wrapping_mul(0x12345678).wrapping_add(0xdeadbeef); } // Get MCI base address from SocIfc and use DMA to write test data to MCU SRAM let mci_base = soc_ifc.mci_base_addr(); let mcu_sram_addr = AxiAddr::from(mci_base + MCU_SRAM_OFFSET); for (i, &word) in test_data.iter().enumerate() { let offset = (i * 4) as u64; dma.write_dword(mcu_sram_addr + offset, word); } // Create DMA recovery instance for accessing sha384_mcu_sram let caliptra_base = AxiAddr::from(soc_ifc.caliptra_base_axi_addr()); let recovery_base = AxiAddr::from(soc_ifc.recovery_interface_base_addr()); let dma_recovery = DmaRecovery::new(recovery_base, caliptra_base, AxiAddr::from(mci_base), &dma); // Compute SHA384 using DMA's sha384_mcu_sram function let dma_digest = dma_recovery .sha384_mcu_sram(&mut sha_acc, 0, TEST_DATA_SIZE as u32, AesDmaMode::None) .expect("DMA SHA384 failed"); let test_data_bytes = unsafe { core::slice::from_raw_parts(test_data.as_ptr() as *const u8, TEST_DATA_SIZE) }; let regular_digest = sha2_512_384 .sha384_digest(test_data_bytes) .expect("Regular SHA384 failed"); // Compare the results assert_eq!( dma_digest, regular_digest, "DMA SHA384 result should match regular SHA384 result" ); } fn test_dma_sha384_empty_data() { let dma = Dma::default(); let mut sha_acc = unsafe { Sha2_512_384Acc::new(Sha512AccCsr::new()) }; let mut sha2_512_384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let soc_ifc = SocIfc::new(unsafe { SocIfcReg::new() }); // test only runs in subsystem mode if !soc_ifc.subsystem_mode() { return; } // Test with empty data (0 length) let caliptra_base = AxiAddr::from(soc_ifc.caliptra_base_axi_addr()); let recovery_base = AxiAddr::from(soc_ifc.recovery_interface_base_addr()); let mci_base = soc_ifc.mci_base_addr(); let dma_recovery = DmaRecovery::new(recovery_base, caliptra_base, AxiAddr::from(mci_base), &dma); // Compute SHA384 using DMA's sha384_mcu_sram function with 0 length let dma_digest = dma_recovery .sha384_mcu_sram(&mut sha_acc, 0, 0, AesDmaMode::None) .expect("DMA SHA384 with empty data failed"); // Compute SHA384 using regular SHA384 driver on empty data let empty_data: &[u8] = &[]; let regular_digest = sha2_512_384 .sha384_digest(empty_data) .expect("Regular SHA384 with empty data failed"); // Compare the results assert_eq!( dma_digest, regular_digest, "DMA SHA384 result for empty data should match regular SHA384 result" ); } fn test_dma_sha384_small_data() { let dma = Dma::default(); let mut sha_acc = unsafe { Sha2_512_384Acc::new(Sha512AccCsr::new()) }; let mut sha2_512_384 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let soc_ifc = SocIfc::new(unsafe { SocIfcReg::new() }); // test only runs in subsystem mode if !soc_ifc.subsystem_mode() { return; } // Test with small amount of data (32 bytes) const SMALL_DATA_SIZE: usize = 32; let mut test_data = [0u32; SMALL_DATA_SIZE / 4]; for (i, word) in test_data.iter_mut().enumerate() { *word = (i as u32 + 1) * 0x11111111; } // Get MCI base address from SocIfc and use DMA to write test data to MCU SRAM let mci_base = soc_ifc.mci_base_addr(); let mcu_sram_addr = AxiAddr::from(mci_base + MCU_SRAM_OFFSET); for (i, &word) in test_data.iter().enumerate() { let offset = (i * 4) as u64; dma.write_dword(mcu_sram_addr + offset, word); } let caliptra_base = AxiAddr::from(soc_ifc.caliptra_base_axi_addr()); let recovery_base = AxiAddr::from(soc_ifc.recovery_interface_base_addr()); let dma_recovery = DmaRecovery::new(recovery_base, caliptra_base, AxiAddr::from(mci_base), &dma); // Compute SHA384 using DMA's sha384_mcu_sram function let dma_digest = dma_recovery .sha384_mcu_sram(&mut sha_acc, 0, SMALL_DATA_SIZE as u32, AesDmaMode::None) .expect("DMA SHA384 failed"); // Compute SHA384 using regular SHA384 driver on the same data let test_data_bytes = unsafe { core::slice::from_raw_parts(test_data.as_ptr() as *const u8, SMALL_DATA_SIZE) }; let regular_digest = sha2_512_384 .sha384_digest(test_data_bytes) .expect("Regular SHA384 failed"); // Compare the results assert_eq!( dma_digest, regular_digest, "DMA SHA384 result should match regular SHA384 result for small data" ); } test_suite! { test_dma_sha384_mcu_sram, test_dma_sha384_empty_data, test_dma_sha384_small_data, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/csrng_fail_adaptp_tests.rs
drivers/test-fw/src/bin/csrng_fail_adaptp_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: csrng_fail_adaptp_tests.rs Abstract: https://opentitan.org/book/hw/ip/entropy_src/doc/theory_of_operation.html#adaptive-proportion-test File contains test cases for CSRNG API when the physical entropy source has a strong bias to produce too many or too little 1's (and vice-versa for 0's). We expect the Adaptive Proportion health check to fail for these tests. --*/ #![no_std] #![no_main] use caliptra_drivers::Csrng; use caliptra_error::CaliptraError; use caliptra_registers::{csrng::CsrngReg, entropy_src::EntropySrcReg, soc_ifc::SocIfcReg}; use caliptra_test_harness::test_suite; fn test_boot_fail_adaptp_check() { let csrng_reg = unsafe { CsrngReg::new() }; let entropy_src_reg = unsafe { EntropySrcReg::new() }; let soc_ifc_reg = unsafe { SocIfcReg::new() }; let csrng = Csrng::new(csrng_reg, entropy_src_reg, &soc_ifc_reg); if let Err(e) = csrng { assert_eq!( e, CaliptraError::DRIVER_CSRNG_ADAPTP_HEALTH_CHECK_FAILED, "error code should indicate the adaptive proportion test failed" ) } else { panic!("failing adaptive proportion test should prevent CSRNG from being constructed"); } } test_suite! { test_boot_fail_adaptp_check, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/mailbox_driver_responder.rs
drivers/test-fw/src/bin/mailbox_driver_responder.rs
// Licensed under the Apache-2.0 license //! A very simple program that uses the driver to respond to the mailbox. #![no_main] #![no_std] // Needed to bring in startup code #[allow(unused)] use caliptra_test_harness::{self, println}; use caliptra_drivers::{self, Mailbox}; use caliptra_registers::mbox::MboxCsr; use zerocopy::IntoBytes; #[panic_handler] pub fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } #[no_mangle] extern "C" fn main() { let mut mbox = unsafe { Mailbox::new(MboxCsr::new()) }; loop { let Some(mut txn) = mbox.try_start_recv_txn() else { continue; }; println!("cmd: 0x{:x}", txn.cmd()); match txn.cmd() { // Test recv_request function 0x5000_0000 => { let mut buf = [0u32; 4]; let dlen = txn.dlen(); println!("dlen: {dlen}"); txn.recv_request(buf.as_mut_bytes()).unwrap(); println!("buf: {:08x?}", buf); } // Test recv_request with non-multiple-of-4 result buffer 0x5000_0001 => { let mut buf = [0u8; 5]; let dlen = txn.dlen(); println!("dlen: {dlen}"); txn.recv_request(&mut buf).unwrap(); println!("buf: {:02x?}", buf); } // Test copy_request function 0x6000_0000 => { let mut buf = [0u32; 2]; let dlen = txn.dlen() as usize; let dlen_words = (dlen + 3) / 4; println!("dlen: {dlen}"); for _ in 0..((dlen_words + (buf.len() - 1)) / buf.len()) { txn.copy_request(buf.as_mut_bytes()).unwrap(); println!("buf: {:08x?}", buf); } txn.complete(true).unwrap(); } // Test success completion without pulling data out of the fifo 0x7000_0000 => { txn.complete(true).unwrap(); } // Test failure completion without pulling data out of the fifo 0x8000_0000 => { txn.complete(false).unwrap(); } // Test dropping first half of words and then printing the remaining words 0x9000_0000 => { let dlen = txn.dlen() as usize; let dlen_words = (dlen + 3) / 4; println!("dlen: {dlen}"); txn.drop_words(dlen_words / 2).unwrap(); let rem_words = dlen_words / 2; let mut buf = [0u32; 1]; for _ in 0..rem_words { txn.copy_request(buf.as_mut_bytes()).unwrap(); println!("buf: {:08x?}", buf); } txn.complete(true).unwrap(); } // Test responding with 4 bytes copy_response and no request data 0xA000_0000 => { txn.send_response(&[0x12, 0x34, 0x56, 0x78]).unwrap(); } // Test responding with request data 0xB000_0000 => { let mut buf = [0u32; 2]; let dlen = txn.dlen() as usize; let dlen_words = (dlen + 3) / 4; println!("dlen: {dlen}"); for _ in 0..((dlen_words + (buf.len() - 1)) / buf.len()) { txn.copy_request(buf.as_mut_bytes()).unwrap(); println!("buf: {:08x?}", buf); } txn.send_response(&[0x98, 0x76]).unwrap(); } // Test responding with 9 byte copy_response 0xC000_0000 => { txn.send_response(&[0x0A, 0x0B, 0x0C, 0x0D, 0x05, 0x04, 0x03, 0x02, 0x01]) .unwrap(); } // Test responding with 0 byte copy_response 0xD000_0000 => { txn.send_response(&[]).unwrap(); } // Test transaction dropped immediately _ => {} } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/sha3_tests.rs
drivers/test-fw/src/bin/sha3_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha3_tests.rs Abstract: File contains test cases for SHA-3 API --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{Array4x16, Array4x8, Sha3}; use caliptra_kat::Shake256Kat; use caliptra_registers::kmac::Kmac as KmacReg; use caliptra_test_harness::test_suite; // All test vectors from NIST CAVP sample test vectors // https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/secure-hashing fn test_shake256_digest0() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0x46, 0xb9, 0xdd, 0x2b, 0x0b, 0xa8, 0x8d, 0x13, 0x23, 0x3b, 0x3f, 0xeb, 0x74, 0x3e, 0xeb, 0x24, 0x3f, 0xcd, 0x52, 0xea, 0x62, 0xb8, 0x1b, 0x82, 0xb5, 0x0c, 0x27, 0x64, 0x6e, 0xd5, 0x76, 0x2f, ]; let data = &[]; let digest: Array4x8 = sha3.shake256_digest(data).unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_shake256_digest1() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0xaa, 0xbb, 0x07, 0x48, 0x8f, 0xf9, 0xed, 0xd0, 0x5d, 0x6a, 0x60, 0x3b, 0x77, 0x91, 0xb6, 0x0a, 0x16, 0xd4, 0x50, 0x93, 0x60, 0x8f, 0x1b, 0xad, 0xc0, 0xc9, 0xcc, 0x9a, 0x91, 0x54, 0xf2, 0x15, ]; let data = &[0x0f]; let digest = sha3.shake256_digest(data).unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_shake256_digest2() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0x8e, 0x2d, 0xf9, 0xd3, 0x79, 0xbb, 0x03, 0x4a, 0xee, 0x06, 0x4e, 0x96, 0x5f, 0x96, 0x0e, 0xbb, 0x41, 0x8a, 0x9b, 0xb5, 0x35, 0x02, 0x5f, 0xb9, 0x64, 0x27, 0xf6, 0x78, 0xcf, 0x20, 0x78, 0x77, ]; let data = &[0x0d, 0xc1]; let digest = sha3.shake256_digest(data).unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_shake256_digest3() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0x7b, 0x7e, 0x12, 0xd2, 0xa5, 0x20, 0xe2, 0x32, 0xfd, 0xe6, 0xc4, 0x1d, 0xbb, 0xb2, 0xb8, 0xb7, 0x4c, 0x29, 0x12, 0xfb, 0x3f, 0x15, 0x40, 0x4f, 0x73, 0x04, 0xfe, 0x46, 0x69, 0x14, 0x30, 0xc9, ]; let data = &[0x4a, 0x71, 0x96, 0x4b]; let digest = sha3.shake256_digest(data).unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_shake256_digest4() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0xf4, 0xbf, 0x0c, 0x76, 0xbe, 0xee, 0x2a, 0xbd, 0x61, 0x56, 0xb4, 0x1a, 0xfe, 0xf4, 0x14, 0x2c, 0x3d, 0xba, 0xbf, 0xed, 0xe5, 0xb9, 0xce, 0x2e, 0xcd, 0x28, 0x2f, 0xb2, 0x94, 0x66, 0x97, 0x31, ]; let data = &[0xe8, 0x2f, 0x41, 0x88, 0xab]; let digest = sha3.shake256_digest(data).unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_shake256_digest5() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0x33, 0x3d, 0x09, 0x64, 0x75, 0xb6, 0xa6, 0xd4, 0x5c, 0x87, 0xb5, 0xaf, 0xc7, 0xe8, 0xcb, 0x22, 0x84, 0x45, 0x6b, 0x84, 0xbd, 0x3e, 0x30, 0xa9, 0xb2, 0x64, 0x49, 0x25, 0x39, 0xed, 0x31, 0x59, ]; let data = &[ 0xaa, 0xf1, 0xf6, 0x4f, 0x3d, 0xf3, 0xfd, 0x4d, 0x42, 0x2a, 0xcb, 0xcb, 0x54, 0x91, 0xff, 0x38, 0x35, 0xb5, 0x7e, 0x32, ]; let digest = sha3.shake256_digest(data).unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_shake256_digest6() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0x8e, 0x9a, 0x89, 0x15, 0x92, 0x44, 0x7c, 0x34, 0x61, 0xea, 0x0a, 0x23, 0x73, 0xca, 0xee, 0xaa, 0xc8, 0xb9, 0xe5, 0xa9, 0x81, 0xd7, 0x74, 0x2f, 0x69, 0x27, 0x79, 0x37, 0x99, 0x64, 0xeb, 0x1e, ]; let data = &[ 0xa1, 0x08, 0x1e, 0x69, 0x94, 0xe1, 0xba, 0x5f, 0x96, 0x6f, 0x95, 0x81, 0x58, 0xee, 0x0a, 0x8c, 0x36, 0x9b, 0x73, 0x46, 0x69, 0x18, 0xf7, 0x07, 0x7e, 0x11, 0xa3, 0x79, 0x06, 0x20, 0xbc, 0x9c, 0x90, 0xee, 0x54, 0x0d, 0xd4, 0x9c, 0x1c, 0x87, 0x31, 0x61, 0x79, 0xaa, 0x5a, 0x74, 0xda, 0xfb, 0x4c, 0x2c, 0x48, 0x2d, 0x83, 0x65, 0x3f, 0x9f, 0x6d, 0x27, 0xbc, 0x25, 0x1f, 0x82, 0x97, 0x0b, 0x47, 0xbc, 0x13, 0x57, 0x61, 0xaf, 0xb4, 0x4f, 0x2e, 0x6c, 0x50, 0x3b, 0x62, 0x24, 0x69, 0x6c, 0x9d, 0x49, 0xba, 0x7d, 0x9d, 0xf0, 0x10, 0xd9, 0xb2, 0x7a, 0x5b, 0x7d, 0x72, 0x73, 0x05, 0x00, 0xad, 0xba, 0x82, 0xd0, 0xa4, 0xe2, 0x29, 0xbe, 0x75, 0xd9, 0x42, 0xbd, 0xda, 0xc7, 0x60, 0xe6, 0x13, 0x39, 0xf1, 0xc0, 0x21, 0x7f, 0x13, 0xbf, 0x35, 0x52, 0xa9, 0x0a, 0x68, 0xbb, 0xae, 0x81, ]; let digest = sha3.shake256_digest(data).unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_shake256_digest7() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0x00, 0x64, 0x8a, 0xfb, 0xc5, 0xe6, 0x51, 0x64, 0x9d, 0xb1, 0xfd, 0x82, 0x93, 0x6b, 0x00, 0xdb, 0xbc, 0x12, 0x2f, 0xb4, 0xc8, 0x77, 0x86, 0x0d, 0x38, 0x5c, 0x49, 0x50, 0xd5, 0x6d, 0xe7, 0xe0, 0x96, 0xd6, 0x13, 0xd7, 0xa3, 0xf2, 0x7e, 0xd8, 0xf2, 0x63, 0x34, 0xb0, 0xcc, 0xc1, 0x40, 0x7b, 0x41, 0xdc, 0xcb, 0x23, 0xdf, 0xaa, 0x52, 0x98, 0x18, 0xd1, 0x12, 0x5c, 0xd5, 0x34, 0x80, 0x92, ]; let data = &[ 0xdc, 0x88, 0x6d, 0xf3, 0xf6, 0x9c, 0x49, 0x51, 0x3d, 0xe3, 0x62, 0x7e, 0x94, 0x81, 0xdb, 0x58, 0x71, 0xe8, 0xee, 0x88, 0xeb, 0x9f, 0x99, 0x61, 0x15, 0x41, 0x93, 0x0a, 0x8b, 0xc8, 0x85, 0xe0, ]; let digest = sha3.shake256_digest(data).unwrap(); assert_eq!(digest, Array4x16::from(expected)); } fn test_shake256_op0() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0x46, 0xb9, 0xdd, 0x2b, 0x0b, 0xa8, 0x8d, 0x13, 0x23, 0x3b, 0x3f, 0xeb, 0x74, 0x3e, 0xeb, 0x24, 0x3f, 0xcd, 0x52, 0xea, 0x62, 0xb8, 0x1b, 0x82, 0xb5, 0x0c, 0x27, 0x64, 0x6e, 0xd5, 0x76, 0x2f, ]; let mut digest_op = sha3.shake256_digest_init().unwrap(); let digest = digest_op.finalize().unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_shake256_op1() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0x46, 0xb9, 0xdd, 0x2b, 0x0b, 0xa8, 0x8d, 0x13, 0x23, 0x3b, 0x3f, 0xeb, 0x74, 0x3e, 0xeb, 0x24, 0x3f, 0xcd, 0x52, 0xea, 0x62, 0xb8, 0x1b, 0x82, 0xb5, 0x0c, 0x27, 0x64, 0x6e, 0xd5, 0x76, 0x2f, ]; let data = []; let mut digest_op = sha3.shake256_digest_init().unwrap(); assert!(digest_op.update(&data).is_ok()); let digest = digest_op.finalize().unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_shake256_op2() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0x7b, 0x7e, 0x12, 0xd2, 0xa5, 0x20, 0xe2, 0x32, 0xfd, 0xe6, 0xc4, 0x1d, 0xbb, 0xb2, 0xb8, 0xb7, 0x4c, 0x29, 0x12, 0xfb, 0x3f, 0x15, 0x40, 0x4f, 0x73, 0x04, 0xfe, 0x46, 0x69, 0x14, 0x30, 0xc9, ]; let data = &[0x4a, 0x71, 0x96, 0x4b]; let mut digest_op = sha3.shake256_digest_init().unwrap(); assert!(digest_op.update(data).is_ok()); let digest = digest_op.finalize().unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_shake256_op3() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0xdd, 0xa6, 0xa9, 0x05, 0x23, 0x4e, 0x81, 0xb4, 0x77, 0x80, 0xbb, 0x08, 0x34, 0xa7, 0x60, 0xec, 0xd2, 0x97, 0x06, 0x8b, 0x28, 0xd4, 0xe0, 0x0f, 0xaf, 0x2c, 0x50, 0x94, 0xff, 0x86, 0x9e, 0x72, ]; let data0 = &[0x12, 0x73, 0x73]; let data1 = &[0x35, 0x1d, 0x8e, 0xb3, 0x08, 0x29]; let mut digest_op = sha3.shake256_digest_init().unwrap(); assert!(digest_op.update(data0).is_ok()); assert!(digest_op.update(data1).is_ok()); let digest = digest_op.finalize().unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_shake256_op4() { let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; let expected = [ 0x96, 0x20, 0xf7, 0xda, 0x5b, 0x74, 0x10, 0xfe, 0x8d, 0xb4, 0xe7, 0x77, 0x96, 0xf5, 0x57, 0x0d, 0x5a, 0xde, 0xf8, 0xa3, 0x44, 0x17, 0xbc, 0x70, 0xe6, 0x0c, 0xe6, 0x8c, 0x57, 0x1e, 0x8e, 0x1e, ]; let data0 = &[0x43, 0xfa]; let data1 = &[0x7c]; let data2 = &[0x73, 0xc6, 0x19, 0x6e]; let data3 = &[0xf2, 0x8d, 0x3a, 0xe7, 0x34, 0xfd, 0x80]; let data4 = &[ 0x8c, 0x1d, 0x01, 0x7e, 0xb9, 0x64, 0xfd, 0x54, 0x18, 0xdf, 0x04, 0x1b, 0x73, 0x01, 0x4a, 0x84, 0xc6, 0xa1, 0xdc, 0xbb, 0x99, 0xfc, 0x8e, 0x92, 0x8c, 0xfe, 0x35, 0xdb, ]; let data5 = &[0x34, 0xbd, 0x17, 0x15, 0x25]; let mut digest_op = sha3.shake256_digest_init().unwrap(); assert!(digest_op.update(data0).is_ok()); assert!(digest_op.update(data1).is_ok()); assert!(digest_op.update(data2).is_ok()); assert!(digest_op.update(data3).is_ok()); assert!(digest_op.update(data4).is_ok()); assert!(digest_op.update(data5).is_ok()); let digest = digest_op.finalize().unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_kat() { // Init CFI CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut sha3 = unsafe { Sha3::new(KmacReg::new()) }; assert_eq!(Shake256Kat::default().execute(&mut sha3).is_ok(), true); } test_suite! { test_kat, test_shake256_digest0, test_shake256_digest1, test_shake256_digest2, test_shake256_digest3, test_shake256_digest4, test_shake256_digest5, test_shake256_digest6, test_shake256_digest7, test_shake256_op0, test_shake256_op1, test_shake256_op2, test_shake256_op3, test_shake256_op4, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/mlkem_tests.rs
drivers/test-fw/src/bin/mlkem_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: mlkem_tests.rs Abstract: File contains test cases for ML-KEM-1024 API tests --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{ Array4x12, Hmac, HmacData, HmacKey, HmacMode, HmacTag, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, LEArray4x8, MlKem1024, MlKem1024Message, MlKem1024MessageSource, MlKem1024Seeds, MlKem1024SharedKey, MlKem1024SharedKeyOut, Trng, }; use caliptra_registers::abr::AbrReg; use caliptra_registers::csrng::CsrngReg; use caliptra_registers::entropy_src::EntropySrcReg; use caliptra_registers::hmac::HmacReg; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_registers::soc_ifc_trng::SocIfcTrngReg; use caliptra_test_harness::test_suite; use zerocopy::IntoBytes; // Test vectors for ML-KEM-1024 const SEED_D: [u32; 8] = [ 0x12345678, 0x9abcdef0, 0x11223344, 0x55667788, 0xaabbccdd, 0xeeff0011, 0x22334455, 0x66778899, ]; const SEED_Z: [u32; 8] = [ 0x87654321, 0x0fedcba9, 0x44332211, 0x88776655, 0xddccbbaa, 0x1100ffee, 0x55443322, 0x99887766, ]; const MESSAGE: [u32; 8] = [ 0xdeadbeef, 0xcafebabe, 0x12345678, 0x9abcdef0, 0x11223344, 0x55667788, 0xaabbccdd, 0xeeff0011, ]; const KEY_ID: KeyId = KeyId::KeyId2; fn test_mlkem_name() { let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let mut entropy_gen = || trng.generate4(); // This needs to happen in the first test CfiCounter::reset(&mut entropy_gen); let abr_reg = unsafe { AbrReg::new() }; let regs = abr_reg.regs(); let name = regs.mlkem_name().read(); // MLKEM_CORE_NAME from RTL: 64'h32343130_4D2D4B45 representing "KEM-1024" assert_eq!(name, [0x4D2D4B45, 0x32343130]); } fn test_key_pair_generation() { let mut mlkem = unsafe { MlKem1024::new(AbrReg::new()) }; // Test key pair generation with arrays let seed_d = LEArray4x8::from(SEED_D); let seed_z = LEArray4x8::from(SEED_Z); let seeds = MlKem1024Seeds::Arrays(&seed_d, &seed_z); let (encaps_key, decaps_key) = mlkem.key_pair(seeds).unwrap(); // Keys should be non-zero (basic sanity check) assert_ne!(encaps_key.0, [0u32; 392]); assert_ne!(decaps_key.0, [0u32; 792]); assert_eq!( encaps_key.0, [ 0x4814898e, 0xb15b7012, 0x40445527, 0x89bef849, 0x675b39a1, 0xa9521326, 0xe68578dc, 0x2ca846a9, 0x5ab3e598, 0x6a2205d6, 0xc82885a5, 0x4192cca4, 0x860f738f, 0xd1829988, 0x3eb59864, 0x1e7c6912, 0xb81432e5, 0x923ab46b, 0xb6fa547, 0x96b67123, 0x6a698bc1, 0xf28c41a8, 0x550720ca, 0x1bc9b953, 0x108c7b8e, 0x423cb260, 0x3ea0c055, 0xbd92c17f, 0x39415d06, 0x49b3002b, 0xec77164d, 0x869f9360, 0x5d2714c4, 0xe94dacb8, 0xbc9e9433, 0x9d891a50, 0x2435231a, 0xa8574f6c, 0xbeaac48c, 0x732b2305, 0x35d073c6, 0x6c15ec8a, 0x4c9dd55f, 0x3ae705b5, 0x751b9519, 0x4cab896, 0xc27e46d8, 0x722b3b22, 0x4643c9e0, 0x6b25a917, 0x4d419158, 0x903056be, 0x78a5b31, 0x295cd2bd, 0xb202f300, 0x3ca0cba1, 0x7e08b44c, 0x9c9c3159, 0x9cb5c7ea, 0x38f6e456, 0xcc6f9ade, 0xf42a6887, 0x9455fc0d, 0xcf451598, 0xd0c2e8, 0x8bb2df6d, 0xd4afc83c, 0x26507968, 0x3dc9b835, 0x7811bb31, 0x87447cd9, 0x14166497, 0xbecb9706, 0xf2ab64fc, 0x4270b818, 0xc81d51dc, 0x536a4e58, 0x8181f726, 0x3b7060d3, 0x613d2c2c, 0x56e963a2, 0x819f92f7, 0x94d7a406, 0xb9917e31, 0xacbb058c, 0x30f07490, 0x24080842, 0xf09a604c, 0xe8286d2c, 0xb0624e24, 0xd65e0584, 0x55397138, 0xc4510f75, 0xdfb15255, 0x2c7c06d6, 0x236785a6, 0xdd953c91, 0xec147b14, 0x4d2c221c, 0x8787aa4c, 0xf1b02101, 0x9f241c9a, 0x1d2b686b, 0x1a6ac75b, 0xe71f7a7, 0xbc2910c2, 0x256a0050, 0xfe7e421, 0x20852850, 0x29675bc3, 0x54e01eb9, 0x93529149, 0x44429b64, 0x997a29c2, 0xfc2fe436, 0x599a3f05, 0x5318632f, 0xdd7fc0b2, 0x399c3b85, 0x664b5e3f, 0x30273089, 0x18b75ed0, 0x33934615, 0x4d628b07, 0xf2880248, 0x14f79305, 0xe74ffb98, 0xe14d5c89, 0x72860532, 0xae6b73ca, 0x25cc719a, 0xa2481604, 0x6a138055, 0x185a0b36, 0x8156c22c, 0x2ac47024, 0xc494bbdc, 0x5050ae32, 0xb32c3aeb, 0x83b79a69, 0x35d8395c, 0x14cc25a6, 0x8c3bbeb, 0x6ed25b87, 0xd3366672, 0xe8b56a99, 0x744a52cb, 0x684af8e5, 0xf068adcc, 0xa5e3ec1d, 0x98cd9289, 0xc24309e6, 0xb3c6c070, 0x8d001ae2, 0xbac9b8ba, 0xdb7c2ac, 0xf0998b6d, 0x7bda9185, 0xa204149c, 0x58400a4b, 0x5469c053, 0x15779d79, 0xf6b09cb0, 0x17c07ed2, 0x5be86726, 0x5238a57d, 0x5a0d75b2, 0xa5f7be74, 0x23530294, 0x158616b6, 0x49751244, 0x68959817, 0x54380769, 0xb6c54845, 0x32461948, 0x95c008bb, 0xafbcde48, 0x92c2f5c3, 0x96f307d0, 0x1fd07219, 0x2740c41b, 0xa7f63226, 0x83576b2f, 0xd8984c0f, 0x990553f0, 0x9d734da1, 0x1043e78c, 0x3ba21d6, 0x15e3d43b, 0x78835bc8, 0x758e6331, 0x6b46a91b, 0xf25ba5eb, 0x4b969ec6, 0xcf4900ad, 0xaf423626, 0xa576ba52, 0x6f65fa63, 0x890375f5, 0x4b88b8f2, 0x2e511d36, 0xb3547249, 0x16abba50, 0x9681be17, 0x453c13d5, 0x586a5c23, 0x6d45dac3, 0x20108956, 0x23a510c4, 0x6cc43e80, 0xc95ab937, 0xe83f1d75, 0xac9640c3, 0x7b6b3c66, 0xe78661f2, 0xc5bb3554, 0xa5260add, 0x294fa807, 0xb4144e8b, 0x83591ba1, 0xe86db4b8, 0x23f14e3b, 0x8a41a00e, 0x9c8fa2fb, 0x1cd87f54, 0xb4633142, 0x9c8f8154, 0x1591d05e, 0x7270cbdf, 0x94525c2a, 0xe734b15, 0x53a01c76, 0x7dcb3a4, 0xafa0d081, 0xc1a8f711, 0x9267c753, 0xbff89aab, 0x5f4cfb0d, 0x8a6eb8b5, 0x55858850, 0xa36dd1ca, 0xcc93c10a, 0x79e1f83b, 0x2e443271, 0x33b43113, 0xabf9844a, 0x264399f9, 0x40faa747, 0x4d08bf4e, 0x630034fd, 0xda6921c5, 0x87a9b73b, 0xd741d35d, 0x830f69c4, 0x3e57a43d, 0x98838ab5, 0x75dc7840, 0x8d091002, 0xe1734bc6, 0xf065618b, 0x5f128159, 0x32dea1d, 0x43860de1, 0xbc52b08, 0x665926da, 0xab8c3df8, 0x937790a5, 0x30a5e58e, 0x59ef9891, 0xce23e24f, 0xb77e876c, 0x8a3f9f38, 0xbdd33a18, 0x7e4730b4, 0x9c4a42f6, 0x627971aa, 0xf6c5fb99, 0xc08e29a6, 0x6bb47ca2, 0xd01daae8, 0x59581309, 0x44732399, 0x5f5fa281, 0xd36c6e58, 0xb7194851, 0x98b2e3c0, 0xb5cb4372, 0x4ef0529b, 0xdb2b67e9, 0x279aa100, 0x90cbc290, 0xee1b7b93, 0x77116c81, 0x9cd1b382, 0xc09b93fc, 0x7bea81e1, 0x3cb53161, 0xb55377e4, 0xa26a01d9, 0xafc13b66, 0x87b6cccc, 0xb25c336a, 0xa3a80247, 0x2329e58d, 0x62dd38ca, 0xca9bbdb0, 0x2f2b396a, 0x464453f4, 0xca5afe76, 0x414cc4d6, 0xd53ba33a, 0x3e529a0d, 0xa63a034b, 0xb41d3c56, 0x2d65b443, 0x451af08b, 0xda1bb9aa, 0x6b9b9027, 0x13775176, 0x950b2d46, 0x4e67e399, 0x3d263cd4, 0xa20f00b4, 0xa982bd02, 0x47595ae4, 0x252715c3, 0x6c0a9ccb, 0xd2c93ba, 0xe94467d1, 0x1d18448, 0xbfaf87f7, 0x14715861, 0x1863263d, 0xf772d0d2, 0x24077ef9, 0x6dd1439a, 0xb521552d, 0x83c52dea, 0xaf137114, 0xa834884a, 0xea74b94b, 0x2be1e902, 0xe94d3087, 0x3639bba5, 0x8ba31360, 0x3a52a036, 0x140a7ecb, 0x1520a850, 0xd55e0bcc, 0x5b324252, 0x36fc921c, 0x14abf3fd, 0x33626f41, 0x8aba09a7, 0x2492a028, 0xd1809657, 0xc543c96c, 0x8db8349a, 0x6c9abd6a, 0xb0389d26, 0x9d7014f8, 0x1c98be57, 0x4b291a3a, 0xb2806a0c, 0x22dc8294, 0xa5e87928, 0xa08f35fd, 0x1cce97d5, 0x2bfc2b24, 0x28708a27, 0x29a34f5a, 0x8ed4ea9e, 0xf167462f, 0x8b3e0725, 0x2657286b, 0x13242825, 0x96564db5, 0xbe059f6a, 0x452b280, 0xa44e0d87, 0xb21aa2cd, 0xdf6aa565, 0x3bfa112, 0x56e9348f, 0xb884d50d, 0xd40cd04e, 0xd83ca4b2, 0xc4aa9a68, 0x5a02a685, 0x637b46b1, 0x17002fe1, 0xc65ab9f6 ] ); assert_eq!( decaps_key.0, [ 0xdac07e1, 0x16073c76, 0x71eba683, 0xfb57db5f, 0xd5d590f6, 0x7f536c03, 0x3c816829, 0xf8188c38, 0xbd1b4f8c, 0x5e4a6b3f, 0x41890576, 0x5e2b3441, 0x4b05270a, 0xb2f4306c, 0x8ae634ad, 0x338a029d, 0x705dceba, 0x2c9d1c6, 0xde4e4074, 0xf1079b98, 0xa6e5be2e, 0x2d5bd4fd, 0xb00861b3, 0x48c9578c, 0xc334282c, 0x29fbbbf4, 0xb4b75cbc, 0xbe23d5dd, 0xd6eb652a, 0x8c210916, 0xe6543b72, 0xf21f9832, 0xc3930933, 0xa2b08736, 0x88987ca0, 0xc3b3295e, 0x528d74bc, 0x97eebd47, 0x575ef4c, 0x3cab9927, 0xf5b43d79, 0x62c85446, 0x836e1a03, 0xc16f3c97, 0x99419cc2, 0x6e5c2363, 0x28d499da, 0x6eca2f6b, 0xcc04b476, 0xb7d3c31b, 0x8349a7c, 0x294a67d8, 0x2011c649, 0x65296c81, 0x444b6931, 0xa2c95882, 0x7af6a8a4, 0xee8e08f8, 0xb561ac62, 0x135453cd, 0xf587fbe9, 0x78e381eb, 0xd58e765, 0x44c511a6, 0x3b395754, 0xad9cd4aa, 0x47cc7a71, 0x6b5bb71c, 0x92b49f4c, 0x9a6854a3, 0xb7edce44, 0x40e6830a, 0x64c4a249, 0x931ec820, 0x4d47075b, 0x466b1551, 0x2487c5fa, 0xe00081c, 0x889241c1, 0xa3f4cfd5, 0xa9495a59, 0x170d76b0, 0x47b2310a, 0x30523ebf, 0xee16c9b5, 0x4bb41314, 0x510a27a5, 0x9b62f259, 0xd7bd6261, 0x2416d02f, 0xcd4fdb6b, 0xc32939e4, 0xae121a52, 0x8491c1ad, 0x7ac59a74, 0x836abf3d, 0xd49a54e8, 0x32746645, 0x2b6565ca, 0x979274e6, 0xb9f0cb31, 0x6e9242f, 0xe47aaadc, 0x51983377, 0x3a9a9c9f, 0x1c60eb98, 0x1b9bbd1c, 0x3673c66f, 0xc20115a6, 0x5bb11d88, 0xc1b94a8d, 0x385147ba, 0xf6599a34, 0x628a0e86, 0x7f112575, 0x906a2b15, 0x2426e636, 0x8968cb00, 0xea1e080b, 0xb4450b58, 0x5beb9c3, 0x2853088, 0x63606608, 0x743a6bca, 0x9985091b, 0x8a621191, 0xd4217410, 0x292a8734, 0x5d2c9a7d, 0x214482ad, 0x80b36035, 0x32c3d202, 0x2cc09290, 0x99594102, 0x69751699, 0xccc7b474, 0x89a48c51, 0x7b9bb629, 0xb8c390d2, 0x27306c40, 0x5ba9cf9c, 0xa27040fc, 0x33ca2002, 0x6b0a530, 0xcb53a47d, 0x96c36332, 0xa797ab7, 0x862c3ca8, 0xb1426093, 0x59779495, 0x5c25f2ab, 0x2b8b186c, 0x51bb1399, 0x126cd312, 0xe89ab39b, 0x9535af1a, 0xbc8f86c2, 0x3329b288, 0xabaf484, 0x228c7395, 0x87e812c5, 0x56fa240a, 0xc4a5804a, 0x7bb77231, 0x40c3b022, 0xc51b793a, 0x52ce6661, 0x9b301eba, 0xd922c874, 0xe57c5d55, 0xc9127700, 0xc403bd7, 0x62fe33f8, 0x7a00708b, 0x491a4b7b, 0x8819e94, 0x167aeb87, 0xc16068e6, 0xb1078b51, 0xb708e673, 0x6488432f, 0x85ba3d26, 0x64b5b43b, 0x74435c29, 0xf29131fc, 0x9996c93d, 0x4989463a, 0x41a87dd0, 0xb2c936b6, 0x686d7b5d, 0x866d1936, 0x3f4c4869, 0xdea21c83, 0x4433b53c, 0x33313892, 0x322621a3, 0xc2aa1d63, 0xa14128b8, 0xa5970389, 0x5faa44a, 0x2a4bb435, 0x347181d6, 0xa0ac94fc, 0xae809714, 0xcb8ffadd, 0x70249503, 0xa56cc210, 0xe6467540, 0x88678512, 0xc4a5ca83, 0xfc195ad3, 0x62940d0a, 0x6120f71c, 0xbfcfa4bc, 0x7bfa5f1c, 0x4101268d, 0xf87e6514, 0xb92b7685, 0x33186507, 0xa23db6a3, 0xa11e5f42, 0x25853d56, 0x20847c56, 0x59dc90e4, 0x32c01a9e, 0x1d2e087d, 0xe4693205, 0x420c4f08, 0x2c44b147, 0xdbada2b9, 0xacb16946, 0x29be243f, 0x92dbcbc3, 0x8fcce1c9, 0x11976cdf, 0xa1735fd6, 0x3863a766, 0xffcf6a08, 0x9744ae87, 0xc7e0acb6, 0xea69b692, 0x38e8c574, 0xb271fc28, 0x5986276d, 0xd90219ab, 0x9aead799, 0x263af3f6, 0xd296a264, 0x8a58ce17, 0x698bc69c, 0x49d1c941, 0xa4bb1d29, 0xf68f12e7, 0xb04a6fb0, 0xecc5a09, 0x146437e, 0xe2bc94b6, 0x59e3af29, 0x19bc1508, 0xaf35bfa, 0x7bcc8605, 0x4596b40a, 0x356c9af8, 0x2414debd, 0xbb3562ca, 0xa7627017, 0xb994b440, 0x1929d6fb, 0xfcb95226, 0xc5130112, 0x3233f659, 0x39958984, 0x1dfa9103, 0x252224f5, 0x83e501c7, 0xa9632907, 0x4051a64f, 0xd9289dac, 0x6a6a529c, 0xa20e1636, 0xc469890, 0x62d93041, 0x40aad658, 0x50893883, 0xbe0b3c9b, 0xbb1f3399, 0xa93c9e48, 0x4c828a33, 0x2ea10710, 0xd7cd86e3, 0x50203a62, 0xf957b1ab, 0x6a7ec2e7, 0x39109e6f, 0x6a76a7cf, 0x47435227, 0x4572f7d, 0xf123a02d, 0x7c692a04, 0x4f619063, 0x7c9df847, 0x73ccb270, 0x16b4d227, 0x956f17f, 0x482f9715, 0xaf98e683, 0x715796ba, 0xbc49ad0, 0x2c50d8bc, 0x6a6817f, 0x851c6260, 0x9c93980c, 0x999330a, 0xd66f8979, 0x3cac2cc5, 0x304c8435, 0x29d42810, 0x4cf83a89, 0xa405b8f7, 0x27f5c8d5, 0x2887dfcb, 0xf479f25e, 0xe0130d00, 0x121c472a, 0x53144c23, 0x77a2ba6a, 0x1661831e, 0xbb6c8167, 0xc7c09a4c, 0x8dd89938, 0x39c5f3f6, 0x8aea5599, 0xb51af26e, 0xcb4cf585, 0xf977ba08, 0x503b754a, 0xff1a699c, 0xa7d7847a, 0xbb58af4b, 0x3aa2e3ba, 0xc2e35ae7, 0xadf2dd4c, 0x9bb6b057, 0xab28810a, 0x6566e802, 0x4cc9208c, 0xa9252392, 0xbda1b428, 0x21cab702, 0x40cd7b92, 0x6b073f8f, 0x86557699, 0xa5cc330a, 0x37435528, 0xd17c91ab, 0xeac428f8, 0x31569be, 0x808920d7, 0x322040cb, 0x6ae6175a, 0x5d874233, 0x11e7b227, 0xa1430e79, 0xb3975993, 0xa38a4064, 0x88d1525a, 0xcaced83f, 0xa9c956f0, 0xc72c135e, 0xd6c6f45e, 0x931b96c8, 0xce19a0bc, 0x4db8d077, 0xf86f1d51, 0x36fa936c, 0xdc1ad739, 0xa9af1388, 0x24a04655, 0xb4ab042b, 0xb26d5ae0, 0xbe7bbdab, 0xf64f9920, 0xe6615c19, 0x327864bc, 0x4814898e, 0xb15b7012, 0x40445527, 0x89bef849, 0x675b39a1, 0xa9521326, 0xe68578dc, 0x2ca846a9, 0x5ab3e598, 0x6a2205d6, 0xc82885a5, 0x4192cca4, 0x860f738f, 0xd1829988, 0x3eb59864, 0x1e7c6912, 0xb81432e5, 0x923ab46b, 0xb6fa547, 0x96b67123, 0x6a698bc1, 0xf28c41a8, 0x550720ca, 0x1bc9b953, 0x108c7b8e, 0x423cb260, 0x3ea0c055, 0xbd92c17f, 0x39415d06, 0x49b3002b, 0xec77164d, 0x869f9360, 0x5d2714c4, 0xe94dacb8, 0xbc9e9433, 0x9d891a50, 0x2435231a, 0xa8574f6c, 0xbeaac48c, 0x732b2305, 0x35d073c6, 0x6c15ec8a, 0x4c9dd55f, 0x3ae705b5, 0x751b9519, 0x4cab896, 0xc27e46d8, 0x722b3b22, 0x4643c9e0, 0x6b25a917, 0x4d419158, 0x903056be, 0x78a5b31, 0x295cd2bd, 0xb202f300, 0x3ca0cba1, 0x7e08b44c, 0x9c9c3159, 0x9cb5c7ea, 0x38f6e456, 0xcc6f9ade, 0xf42a6887, 0x9455fc0d, 0xcf451598, 0xd0c2e8, 0x8bb2df6d, 0xd4afc83c, 0x26507968, 0x3dc9b835, 0x7811bb31, 0x87447cd9, 0x14166497, 0xbecb9706, 0xf2ab64fc, 0x4270b818, 0xc81d51dc, 0x536a4e58, 0x8181f726, 0x3b7060d3, 0x613d2c2c, 0x56e963a2, 0x819f92f7, 0x94d7a406, 0xb9917e31, 0xacbb058c, 0x30f07490, 0x24080842, 0xf09a604c, 0xe8286d2c, 0xb0624e24, 0xd65e0584, 0x55397138, 0xc4510f75, 0xdfb15255, 0x2c7c06d6, 0x236785a6, 0xdd953c91, 0xec147b14, 0x4d2c221c, 0x8787aa4c, 0xf1b02101, 0x9f241c9a, 0x1d2b686b, 0x1a6ac75b, 0xe71f7a7, 0xbc2910c2, 0x256a0050, 0xfe7e421, 0x20852850, 0x29675bc3, 0x54e01eb9, 0x93529149, 0x44429b64, 0x997a29c2, 0xfc2fe436, 0x599a3f05, 0x5318632f, 0xdd7fc0b2, 0x399c3b85, 0x664b5e3f, 0x30273089, 0x18b75ed0, 0x33934615, 0x4d628b07, 0xf2880248, 0x14f79305, 0xe74ffb98, 0xe14d5c89, 0x72860532, 0xae6b73ca, 0x25cc719a, 0xa2481604, 0x6a138055, 0x185a0b36, 0x8156c22c, 0x2ac47024, 0xc494bbdc, 0x5050ae32, 0xb32c3aeb, 0x83b79a69, 0x35d8395c, 0x14cc25a6, 0x8c3bbeb, 0x6ed25b87, 0xd3366672, 0xe8b56a99, 0x744a52cb, 0x684af8e5, 0xf068adcc, 0xa5e3ec1d, 0x98cd9289, 0xc24309e6, 0xb3c6c070, 0x8d001ae2, 0xbac9b8ba, 0xdb7c2ac, 0xf0998b6d, 0x7bda9185, 0xa204149c, 0x58400a4b, 0x5469c053, 0x15779d79, 0xf6b09cb0, 0x17c07ed2, 0x5be86726, 0x5238a57d, 0x5a0d75b2, 0xa5f7be74, 0x23530294, 0x158616b6, 0x49751244, 0x68959817, 0x54380769, 0xb6c54845, 0x32461948, 0x95c008bb, 0xafbcde48, 0x92c2f5c3, 0x96f307d0, 0x1fd07219, 0x2740c41b, 0xa7f63226, 0x83576b2f, 0xd8984c0f, 0x990553f0, 0x9d734da1, 0x1043e78c, 0x3ba21d6, 0x15e3d43b, 0x78835bc8, 0x758e6331, 0x6b46a91b, 0xf25ba5eb, 0x4b969ec6, 0xcf4900ad, 0xaf423626, 0xa576ba52, 0x6f65fa63, 0x890375f5, 0x4b88b8f2, 0x2e511d36, 0xb3547249, 0x16abba50, 0x9681be17, 0x453c13d5, 0x586a5c23, 0x6d45dac3, 0x20108956, 0x23a510c4, 0x6cc43e80, 0xc95ab937, 0xe83f1d75, 0xac9640c3, 0x7b6b3c66, 0xe78661f2, 0xc5bb3554, 0xa5260add, 0x294fa807, 0xb4144e8b, 0x83591ba1, 0xe86db4b8, 0x23f14e3b, 0x8a41a00e, 0x9c8fa2fb, 0x1cd87f54, 0xb4633142, 0x9c8f8154, 0x1591d05e, 0x7270cbdf, 0x94525c2a, 0xe734b15, 0x53a01c76, 0x7dcb3a4, 0xafa0d081, 0xc1a8f711, 0x9267c753, 0xbff89aab, 0x5f4cfb0d, 0x8a6eb8b5, 0x55858850, 0xa36dd1ca, 0xcc93c10a, 0x79e1f83b, 0x2e443271, 0x33b43113, 0xabf9844a, 0x264399f9, 0x40faa747, 0x4d08bf4e, 0x630034fd, 0xda6921c5, 0x87a9b73b, 0xd741d35d, 0x830f69c4, 0x3e57a43d, 0x98838ab5, 0x75dc7840, 0x8d091002, 0xe1734bc6, 0xf065618b, 0x5f128159, 0x32dea1d, 0x43860de1, 0xbc52b08, 0x665926da, 0xab8c3df8, 0x937790a5, 0x30a5e58e, 0x59ef9891, 0xce23e24f, 0xb77e876c, 0x8a3f9f38, 0xbdd33a18, 0x7e4730b4, 0x9c4a42f6, 0x627971aa, 0xf6c5fb99, 0xc08e29a6, 0x6bb47ca2, 0xd01daae8, 0x59581309, 0x44732399, 0x5f5fa281, 0xd36c6e58, 0xb7194851, 0x98b2e3c0, 0xb5cb4372, 0x4ef0529b, 0xdb2b67e9, 0x279aa100, 0x90cbc290, 0xee1b7b93, 0x77116c81, 0x9cd1b382, 0xc09b93fc, 0x7bea81e1, 0x3cb53161, 0xb55377e4, 0xa26a01d9, 0xafc13b66, 0x87b6cccc, 0xb25c336a, 0xa3a80247, 0x2329e58d, 0x62dd38ca, 0xca9bbdb0, 0x2f2b396a, 0x464453f4, 0xca5afe76, 0x414cc4d6, 0xd53ba33a, 0x3e529a0d, 0xa63a034b, 0xb41d3c56, 0x2d65b443, 0x451af08b, 0xda1bb9aa, 0x6b9b9027, 0x13775176, 0x950b2d46, 0x4e67e399, 0x3d263cd4, 0xa20f00b4, 0xa982bd02, 0x47595ae4, 0x252715c3, 0x6c0a9ccb, 0xd2c93ba, 0xe94467d1, 0x1d18448, 0xbfaf87f7, 0x14715861, 0x1863263d, 0xf772d0d2, 0x24077ef9, 0x6dd1439a, 0xb521552d, 0x83c52dea, 0xaf137114, 0xa834884a, 0xea74b94b, 0x2be1e902, 0xe94d3087, 0x3639bba5, 0x8ba31360, 0x3a52a036, 0x140a7ecb, 0x1520a850, 0xd55e0bcc, 0x5b324252, 0x36fc921c, 0x14abf3fd, 0x33626f41, 0x8aba09a7, 0x2492a028, 0xd1809657, 0xc543c96c, 0x8db8349a, 0x6c9abd6a, 0xb0389d26, 0x9d7014f8, 0x1c98be57, 0x4b291a3a, 0xb2806a0c, 0x22dc8294, 0xa5e87928, 0xa08f35fd, 0x1cce97d5, 0x2bfc2b24, 0x28708a27, 0x29a34f5a, 0x8ed4ea9e, 0xf167462f, 0x8b3e0725, 0x2657286b, 0x13242825, 0x96564db5, 0xbe059f6a, 0x452b280, 0xa44e0d87, 0xb21aa2cd, 0xdf6aa565, 0x3bfa112, 0x56e9348f, 0xb884d50d, 0xd40cd04e, 0xd83ca4b2, 0xc4aa9a68, 0x5a02a685, 0x637b46b1, 0x17002fe1, 0xc65ab9f6, 0xb6b26546, 0xae6a2074, 0x7621ee62, 0xe9b7863c, 0xf0fb834f, 0x52005fb0, 0x7a5b738b, 0x77cccbea, 0x87654321, 0xfedcba9, 0x44332211, 0x88776655, 0xddccbbaa, 0x1100ffee, 0x55443322, 0x99887766, ] ); } fn test_key_pair_generation_from_kv() { let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let mut mlkem = unsafe { MlKem1024::new(AbrReg::new()) }; let mut hmac = unsafe { Hmac::new(HmacReg::new()) }; // Store seeds in key vault let key_out = KeyWriteArgs { id: KEY_ID, usage: KeyUsage::default().set_mlkem_seed_en(), }; hmac.hmac( HmacKey::from(&Array4x12::default()), HmacData::from(&[]), &mut trng, HmacTag::Key(key_out), HmacMode::Hmac384, ) .unwrap(); // Test key pair generation from key vault let seeds = MlKem1024Seeds::Key(KeyReadArgs::new(KEY_ID)); let (encaps_key, decaps_key) = mlkem.key_pair(seeds).unwrap(); // Encapsulation key should be non-zero (basic sanity check) assert_ne!(encaps_key.0, [0u32; 392]); // Decapsulation key should be zero (because the seed is from the KV) assert_eq!(decaps_key.0, [0u32; 792]); assert_eq!( encaps_key.0, [ 0xffa6b869, 0x47761091, 0xb1188d91, 0x1a3a9ae9, 0xb07f01d0, 0x438c5376, 0xb4867992, 0xdac20d39, 0x9563d5a2, 0xbdb40537, 0xda071895, 0x35abd911, 0x245e0022, 0x18bfbf98, 0x9b576b51, 0xb64fdc37, 0xd9a31476, 0x3a03ef49, 0xd1477972, 0xa9010136, 0x6b29e7a5, 0xc854226b, 0xc8668871, 0xb75c4f8c, 0x967d0035, 0x7e518e1, 0xbb81fa26, 0xad38b738, 0xd6249b3b, 0x7c885d5b, 0x65a3261, 0x2b421c13, 0x4995f38f, 0x603f804a, 0xb9c9c785, 0x36f5b2c6, 0x8cc346a6, 0xd73b7d98, 0x874b209b, 0xa50b937d, 0x26085f48, 0x4d11b1bd, 0xf75854f1, 0x231e4e29, 0x51bc461d, 0xf471d10f, 0xf07c39d7, 0x2df8fb2e, 0xfe22bb71, 0xc240c483, 0x83b9fd99, 0xeec3c12c, 0x5af679b4, 0x56d57057, 0xfd3dc39b, 0x304f74dc, 0xb6b3490f, 0x5e79f86e, 0x2cce9dcb, 0x6fd6394f, 0x638ae81b, 0x2212c378, 0x39daeb15, 0x20beea7f, 0xc91008d3, 0x9b8a6c01, 0x61374456, 0x9601258c, 0xc4cc3304, 0xe07271b3, 0x75793b29, 0xa1f9abae, 0x613ce553, 0x2c556af5, 0x87d4500c, 0x498d1b41, 0x19fa0465, 0x19202b1c, 0x482ea31e, 0xa5b3461a, 0x7850037a, 0x2888ece0, 0x21c70a31, 0x87981270, 0xa437359d, 0x18238a08, 0x27fadfa7, 0x7f7ff66a, 0x4cea1ea9, 0xb467738c, 0x8c90d07e, 0xf94b99f3, 0xcb690322, 0xf7111424, 0x9730c510, 0x13c71ccd, 0x8fa2bbdb, 0xb0ebad85, 0x73b7d662, 0xddc64a96, 0x88574b, 0x67fcc06f, 0x9a551bae, 0xa97405fa, 0x4212f690, 0xc995405a, 0xd138989b, 0x1d31531e, 0xc2ade71e, 0x5cec2b45, 0xa0ec766e, 0x2283d8a9, 0xe6f159fb, 0x96006607, 0x7875912a, 0x6b5fbaf3, 0xce40fa54, 0x867ed047, 0xc52c724, 0x5c59abaa, 0x7709d2df, 0x7a0f02cb, 0x516ad6a5, 0x26695015, 0x43200474, 0x335487c7, 0xe5a82553, 0xa3c3be74, 0x9daa3f7a, 0xb695864d, 0x35de60cc, 0x16349c54, 0xa7cbe058, 0x7c125f48, 0x74540d25, 0xea677afe, 0x8320a875, 0x1646e37a, 0x3f325454, 0x4374330a, 0x167feb9, 0x127eecb6, 0xe6485ef6, 0x8de89e8a, 0x1d2c79d0, 0x16ddad40, 0x6fb898bd, 0xf87dae4, 0x48787ec0, 0x9b0b076f, 0x4a8b151b, 0x22000b81, 0xab447e91, 0x4b39e0fe, 0x16204748, 0xc1236a91, 0x7abd101d, 0x3173b2ca, 0x9022a0a3, 0x3e5399f7, 0x9209275, 0xb5eca73b, 0xc11489d8, 0x11f56ee0, 0xb8f36b3d, 0x7e0107a9, 0x7533b6ba, 0x77b7c002, 0x781608d8, 0x44ca9af5, 0xbec9cb04, 0x60b1a54f, 0x28e6aa3b, 0x3d7402a0, 0xca46f160, 0x54368f73, 0x2d5b8034, 0x9712679f, 0x7cf0acc4, 0x47285c8b, 0x6cc433cd, 0x24336b60, 0xbcb75e0f, 0x86c5314c, 0xa495cb52, 0x9144665b, 0x2e70d64f, 0xf45a79d3, 0x4b4d9aa, 0x5e76c62e, 0xc3a1a6c1, 0x44d668b5, 0xa9953290, 0x98dc8522, 0x5f89dc49, 0x6764b163, 0xa868cc56, 0x7ab1f677, 0xa53215b7, 0x90c891a8, 0x854acd1d, 0x2012978d, 0xc4821777, 0x3cb71911, 0x2f02f06c, 0x30011ccc, 0x3f86c170, 0xda4288e5, 0x924190fb, 0x763cad5f, 0x4978d222, 0x713859b0, 0xc7f63765, 0xd0545647, 0x4a491da9, 0x384c092, 0x9a78e2ba, 0x87eb9ddc, 0x41cc2089, 0x531e1bb0, 0x820a9b2b, 0x3b08c621, 0x630da222, 0xd6230bbc, 0xadc29bc8, 0xf94d619f, 0x89b98ef3, 0xbfb57209, 0x44b122a0, 0x316a2b70, 0x108a5589, 0x850302df, 0xdcfc9262, 0x6a2a144d, 0xad35a5c9, 0xf8ed15e3, 0x5cace692, 0x5278a4d8, 0x5a8551e3, 0x29462f9a, 0x757cd74f, 0x4bbe20cb, 0xf502865, 0xf342e07d, 0x575b3857, 0x4e09ed0d, 0xf43a8c7, 0x9c23499c, 0x9df6302f, 0x2e0f732b, 0x5b4a3f6, 0x47881634, 0x74be908f, 0x1b153676, 0xa823d04, 0x1c38a1b9, 0x4cb01cd3, 0x4c3c0868, 0x650a86ce, 0xe68497b6, 0xc5377a5b, 0x366a0cb4, 0xacb2c378, 0xa345be7c, 0xaa35d2bd, 0xa5348655, 0x4563ac85, 0x5d155b52, 0x273487fa, 0x7e78ccc0, 0xea48d3ec, 0xc6ae4608, 0x9c3b566f, 0x8c0ba081, 0x69d92cb4, 0x2f7ad1f, 0x884c9045, 0xc1334b8b, 0x6ad0ab54, 0x2c85a09a, 0x9a529d99, 0x66ab140a, 0x92a4445b, 0x9819360b, 0xbb67a10f, 0xb3bec443, 0xfb28b299, 0x6bf6ee3d, 0x7da3ea22, 0x97dd7a54, 0x8317a20d, 0x3b37185a, 0xb9676da6, 0xc932ac3e, 0x4b7c490d, 0x57408cc4, 0x638a0fb0, 0xd3c6eb8e, 0x85c13255, 0xc656bac5, 0x2f0650c9, 0x37116601, 0x2520871a, 0xf2104a11, 0xb0742e57, 0x7d83066c, 0x387ed633, 0xf5c51f49, 0xce2ce180, 0xd66b10e3, 0x193559eb, 0x9db9ed60, 0x1b957652, 0xe7e04839, 0x21cb70a4, 0xdc6259a3, 0xb27f9468, 0x8fc9a444, 0x3510fc36, 0x903255, 0x91506dc2, 0xe969754a, 0xf66228b1, 0x34c19d73, 0x41063bdf, 0xe61e7981, 0xcd3b568f, 0x574500a, 0x7669666b, 0x228518b1, 0x54ae82e9, 0xe9f74f7b, 0xc0f0c515, 0x63ba290b, 0x29782d20, 0x79862637, 0xf5ccd559, 0x6a86aa19, 0x51e0e8bc, 0xbd86f359, 0x6c04986c, 0xa1270c0e, 0x2e9e7cad, 0xd7707672, 0x25e383ab, 0xa9c8f217, 0xe80506f2, 0x153bc163, 0x5cb148ce, 0xb7fa96b9, 0x7f2b94c1, 0xfd622505, 0x285c0822, 0x121a6b4b, 0xc1a5e7b0, 0xe130cc73, 0x1d70136c, 0xe35cf867, 0x512c0b06, 0x6dfc3f02, 0x295c0546, 0x509f2334, 0x93e7bca8, 0xc80c268, 0x2cb5715b, 0xbd517b17, 0xcb2d65f5, 0x61f21418, 0x4df578ae, 0x8abfb66b, 0x6635249, 0x2e99eb3e, 0x9791f18b, 0x48130e8b, 0x17e98b8f, 0x1ca8a39, 0x95131d39, 0xbecc07c1, 0xe562e82f, 0x7a6b86c3, 0x92c14f97, 0xc09bc0fd, 0x44df72b4, 0xb0943f27, 0x4f58b8be, 0xd0347e9b, 0xb2a479e3, 0x5a9e7a70, 0xc0d31a76, 0xddb7b29d, 0x25cfb291, 0x1013aa08, ] ) } fn test_encapsulate_and_decapsulate() { let mut mlkem = unsafe { MlKem1024::new(AbrReg::new()) }; // Generate key pair let seed_d = LEArray4x8::from(SEED_D); let seed_z = LEArray4x8::from(SEED_Z); let seeds = MlKem1024Seeds::Arrays(&seed_d, &seed_z); let (encaps_key, decaps_key) = mlkem.key_pair(seeds).unwrap(); // Test encapsulation with array message and array output let message = MlKem1024Message::from(MESSAGE); let mut shared_key_out = MlKem1024SharedKey::default(); let ciphertext = mlkem .encapsulate( encaps_key, MlKem1024MessageSource::Array(&message), MlKem1024SharedKeyOut::Array(&mut shared_key_out), ) .unwrap(); // Ciphertext should be non-zero assert_ne!(ciphertext.0, [0u32; 392]); // Shared key should be non-zero assert_ne!(shared_key_out.0, [0u32; 8]); // Test decapsulation let mut decaps_shared_key = MlKem1024SharedKey::default(); mlkem .decapsulate( decaps_key, &ciphertext, MlKem1024SharedKeyOut::Array(&mut decaps_shared_key), ) .unwrap(); // The decapsulated shared key should match the encapsulated one assert_eq!(shared_key_out.0, decaps_shared_key.0); } fn test_encapsulate_with_kv_message() { let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let mut mlkem = unsafe { MlKem1024::new(AbrReg::new()) }; let mut hmac = unsafe { Hmac::new(HmacReg::new()) }; // Generate key pair let seed_d = LEArray4x8::from(SEED_D); let seed_z = LEArray4x8::from(SEED_Z); let seeds = MlKem1024Seeds::Arrays(&seed_d, &seed_z); let (encaps_key, _decaps_key) = mlkem.key_pair(seeds).unwrap(); // Store message in key vault let msg_key_id = KeyId::KeyId3; let msg_key_out = KeyWriteArgs { id: msg_key_id, usage: KeyUsage::default().set_mlkem_msg_en(), }; let message_array = LEArray4x8::from(MESSAGE); let message_bytes = message_array.as_bytes(); hmac.hmac( HmacKey::from(&Array4x12::default()), HmacData::from(message_bytes), &mut trng, HmacTag::Key(msg_key_out), HmacMode::Hmac384, ) .unwrap(); // Test encapsulation with key vault message let mut shared_key_out = MlKem1024SharedKey::default(); let ciphertext = mlkem .encapsulate( encaps_key, MlKem1024MessageSource::Key(KeyReadArgs::new(msg_key_id)), MlKem1024SharedKeyOut::Array(&mut shared_key_out), ) .unwrap(); // Ciphertext should be non-zero assert_eq!( ciphertext.0, [ 0x4681e224, 0x71d1b46e, 0x9444853f, 0x3394715, 0xf7d97f6e, 0xb29b805c, 0xf8ee64a5, 0x1b530da1, 0x627439a6, 0x8afbd839, 0x6badb349, 0xa2c0c50e, 0xd44b800c, 0xae621886, 0x6310d9b5, 0x3ac60c4e, 0x35a483fd, 0x808baf32, 0x840ac264, 0x202e71bd, 0x434e07f2, 0x3a285bbf, 0xf6a4f647, 0x8ce6b445, 0x2678c45c, 0x4808ba1e, 0x5791f175, 0x57a648a3, 0xaaba12c6, 0x5c0f5eb2, 0xaca90159, 0x3c0e2585, 0xa8421c88, 0xa0109552, 0x7b921e0d, 0xb0de3aff, 0xca486b47, 0xfc14f5e4, 0xf449037, 0xbe8d4d6b, 0xd2857b0c, 0x9e7ab3dc, 0xc522ae14, 0xdb297747, 0xb54cada8, 0xaff14a4c, 0xc4f64b7a, 0x553d58f0, 0x57ba44a1, 0x93bed2f0, 0x2806e57c, 0xfef08b84, 0x7961d495, 0x22926932, 0x7844744d, 0x961becfe, 0x69c53292, 0xbe149e64, 0x62234417, 0x9d9b9103, 0x42747ceb, 0x70f3218a, 0x849bce15, 0xd9dc6dbf, 0x6970ae0b, 0x3c129892, 0x937f0750, 0xeb13da81, 0x65737b78, 0xff17f102, 0x3f381d36, 0x461d61e4, 0x6ecf41a1, 0xde48a4d4, 0xd8c6a63d, 0xbf54c324, 0x610b94eb, 0x51d2743b, 0xf18f2d88, 0x2c45f0cd, 0x744e4a72, 0x6e64c6e7, 0xbc68ed94, 0x1f8fe44b, 0x9eb8d8e9, 0xd4c2b296, 0xdb8c7bd7, 0xa03cd64d, 0x108d18c9, 0xd620c44e, 0xc1228af6, 0x29efba35, 0x8cb6a650, 0x9599d69c, 0x3ffad6b1, 0x4ebecca, 0x69045b9c, 0xa56de734, 0xa40a8b9e, 0xb08194b5, 0x37af0740, 0xfb30f8cc, 0x5186eff6, 0xca907e75, 0x25d61dd6, 0xf88111c2, 0x3d2602f1, 0x146cc3d5, 0x15829765, 0xacac7fa7, 0x1234979d, 0xe639050a, 0x7ba2fcc4, 0xd10e5f17, 0x6a8b4a0a, 0x549d6846, 0x8dd9d267, 0xa4f07358, 0x7c639582, 0x6f19fcdd, 0xe8603ea0, 0x9e413d4e, 0xa67b120d, 0x8cc7f647, 0x1f9d380f, 0xb5c2f470, 0x1e7330c6, 0x4e05083, 0xa28640c0, 0x6530de51, 0x92445734, 0xe8173355, 0xf0d517cf, 0xb291ff64, 0xd0e5df90, 0x389299, 0x8ce93977, 0x92f26303, 0xeead9648, 0xc2fdb19b, 0x85ee440b, 0x39367488, 0x9cb8c3a, 0xacd3bf80, 0x710c2161, 0xb3c68772, 0xf0aac68b, 0x1baf3686, 0x75c087ba, 0xe7e7302b, 0x276ff784, 0xd283a32f, 0x15511be8, 0xefc52108, 0xcc8d2980, 0x67870d2, 0x76d56a00, 0x8d0226ec, 0x89c89d60, 0x4541de8, 0x260a2f4c, 0xaf5ab391, 0xf64a6286, 0xe27d0264, 0x5fa5e3e5, 0xdaa5edf9, 0xca7327e6, 0xc5def8c4, 0x7fc3d247, 0x8f5d823b, 0x54d9c32d, 0x6dc1321d, 0xc9ef0f61, 0x25b132ed, 0x88c6914, 0x4335680d, 0xc6763cee, 0x60f247fd, 0x10c52e03, 0x956ea682, 0xc9e507a, 0xc383b111, 0xe308a5e6, 0xe8189b4e, 0x979f1dd7, 0x98c8a2f4, 0x49a65a02, 0xbb2309f5, 0xe910fbf3, 0x216098, 0xf799fa21, 0xcbc33cb0, 0xc14c2ba0, 0x30bcf8be, 0xd9d142cf, 0x171fe772, 0xe28b77c3, 0x4a895df1, 0x1c25f7ce, 0x9abc4ad, 0xb418afd7, 0x89c44ea4, 0x9c963654, 0x31be18e8, 0x4905a225, 0xf7662598, 0x713d204, 0x60d6e86a, 0x83f40c3d, 0x4e96c2ca, 0x7e81f40e, 0xec4945f2, 0x97fcb1dd, 0xbfb4497c, 0x890680eb, 0x70b96a2f, 0x1410a287, 0xcf92162, 0x82e1027e, 0x4d192863, 0x1474d879, 0xec3c5d7b, 0xf7e278a6, 0xd2b5ff7, 0xf1585880, 0x918b9eda, 0x88be0f51, 0x4333712c, 0xa0173710, 0xe7096173, 0x847d3224, 0xba64f57, 0x1acb5725, 0x33ce4568, 0xd8ca9223, 0xb45f1a51, 0x97134080, 0xea1f02da, 0x75c0635f, 0xb5e3c3a4, 0xcef429f6, 0x332388c6, 0x308d760, 0x1d04e0b0, 0x6f12646f, 0x25360e7, 0xacc5efa9, 0x5c2d8851, 0x59fe70f6, 0x5e75409d, 0x3ba3eb4d, 0xd745eb3e, 0xc6d0c290, 0x4bddb05a, 0x290a71bb, 0x6b4a72ae, 0xe863550c, 0x1fce23a2, 0x64beb483, 0xb2ab7f55, 0x60cd192d, 0xfb8d65f, 0x4acddd9, 0x95601ae6, 0x3f86a356, 0x60dac33b, 0xcb1faf88, 0x18e42969, 0x22676e56, 0x433a959b, 0xc398d0a7, 0x3e5eb4e4, 0xeb8f3e70, 0x4ee0a383, 0xaf4d53e, 0x11bf1b0f, 0x4dd29751, 0x221749ea, 0xbec12360, 0x4ab1f5c2, 0xa3c28085, 0xf651b73f, 0xc4c4213f, 0xb018e695, 0xd599214, 0x9a3a52f2, 0x741a04a, 0xe690d8ce, 0x3df9a0d, 0xf3d6d3e6, 0x59c29223, 0x93eb5443, 0xde2f4dfe, 0xc97ff56c, 0xb8bcbd87, 0x144915f, 0x68ba0d84, 0x5965fd26, 0x658f32f8, 0xde6d0cd6, 0xa940db02, 0x30c39243, 0x1d30bb4c, 0x6c3d4d92, 0x5b3f9dbc, 0x2c53902c, 0x9fbb738a, 0x9ac62dd9, 0x7ac07ace, 0xf44125eb, 0xbcd0282, 0x838246ae, 0xa997d059, 0x27b779b1, 0x6fca2d52, 0xe231914e, 0x9493a4e7, 0xdc7bd30f, 0xf4fbfbb4, 0x3a257fd3, 0x700816fe, 0x9e669d2, 0x2b6af1f8, 0x73c1cadd, 0x7413c519, 0x518348f3, 0xef3f7d9e, 0x3e68f25c, 0xf504446a, 0x423e1cc6, 0xe58f2707, 0xa6cd57fc, 0x80fffb2c, 0xb5bceace, 0x93497d7f, 0x1fa7fc5f, 0xa212d02f, 0x71d7724f, 0x442f7b68, 0x65062f31, 0xd071d954, 0x8425cafd, 0x65aa40b7,
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/csrng_fail_repcnt_tests.rs
drivers/test-fw/src/bin/csrng_fail_repcnt_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: csrng_fail_repcnt_tests.rs Abstract: https://opentitan.org/book/hw/ip/entropy_src/doc/theory_of_operation.html#repetition-count-test File contains test cases for CSRNG API when the physical entropy source has a stuck bit on at least one of the four external RNG wires. We expect the Repetition Count health check to fail for these tests. --*/ #![no_std] #![no_main] use caliptra_drivers::Csrng; use caliptra_error::CaliptraError; use caliptra_registers::{csrng::CsrngReg, entropy_src::EntropySrcReg, soc_ifc::SocIfcReg}; use caliptra_test_harness::test_suite; fn test_boot_fail_repcnt_check() { let csrng_reg = unsafe { CsrngReg::new() }; let entropy_src_reg = unsafe { EntropySrcReg::new() }; let soc_ifc_reg = unsafe { SocIfcReg::new() }; let csrng = Csrng::new(csrng_reg, entropy_src_reg, &soc_ifc_reg); if let Err(e) = csrng { assert_eq!( e, CaliptraError::DRIVER_CSRNG_REPCNT_HEALTH_CHECK_FAILED, "error code should indicate the repetition count test failed" ) } else { panic!("failing repetition count test should prevent CSRNG from being constructed"); } } test_suite! { test_boot_fail_repcnt_check, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/test_uart.rs
drivers/test-fw/src/bin/test_uart.rs
// Licensed under the Apache-2.0 license //! A very simple ROM. Prints a serious of strings using the UART driver. #![no_std] #![no_main] use caliptra_drivers::{ExitCtrl, Uart}; // Needed to bring in startup code #[allow(unused)] use caliptra_test_harness; #[panic_handler] pub fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } #[no_mangle] pub extern "C" fn main() { Uart::new().write("aa"); Uart::new().write("aaa"); Uart::new().write("ahello"); ExitCtrl::exit(0); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/pcrbank_tests.rs
drivers/test-fw/src/bin/pcrbank_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: pcrbank_tests.rs Abstract: File contains test cases for PCR bank API --*/ #![no_std] #![no_main] use caliptra_drivers::{PcrBank, PcrId}; use caliptra_registers::pv::PvReg; use caliptra_test_harness::test_suite; const PCR_IDS: [PcrId; 32] = [ PcrId::PcrId0, PcrId::PcrId1, PcrId::PcrId2, PcrId::PcrId3, PcrId::PcrId4, PcrId::PcrId5, PcrId::PcrId6, PcrId::PcrId7, PcrId::PcrId8, PcrId::PcrId9, PcrId::PcrId10, PcrId::PcrId11, PcrId::PcrId12, PcrId::PcrId13, PcrId::PcrId14, PcrId::PcrId15, PcrId::PcrId16, PcrId::PcrId17, PcrId::PcrId18, PcrId::PcrId19, PcrId::PcrId20, PcrId::PcrId21, PcrId::PcrId22, PcrId::PcrId23, PcrId::PcrId24, PcrId::PcrId25, PcrId::PcrId26, PcrId::PcrId27, PcrId::PcrId28, PcrId::PcrId29, PcrId::PcrId30, PcrId::PcrId31, ]; fn test_lock_and_erase_pcrs() { let mut pcr_bank = unsafe { PcrBank::new(PvReg::new()) }; for pcr_id in PCR_IDS { assert!(pcr_bank.erase_pcr(pcr_id).is_ok()); // Set lock. assert!(!pcr_bank.pcr_lock(pcr_id)); pcr_bank.set_pcr_lock(pcr_id); assert!(pcr_bank.pcr_lock(pcr_id)); // Test erasing pcr. This should fail. assert!(pcr_bank.erase_pcr(pcr_id).is_err()); } } fn test_erase_all_pcrs() { let mut pcr_bank = unsafe { PcrBank::new(PvReg::new()) }; pcr_bank.erase_all_pcrs(); } fn test_write_protection_stickiness() { let mut pcr_bank = unsafe { PcrBank::new(PvReg::new()) }; for pcr_id in PCR_IDS { assert!(pcr_bank.pcr_lock(pcr_id)); pcr_bank.clear_pcr_lock(pcr_id); assert!(pcr_bank.pcr_lock(pcr_id)); } } // Maintain the order of the tests. test_suite! { test_lock_and_erase_pcrs, test_erase_all_pcrs, test_write_protection_stickiness, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/ocp_lock_tests.rs
drivers/test-fw/src/bin/ocp_lock_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: ocp_lock_tests.rs Abstract: File contains test cases for OCP LOCK. --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{ cmac_kdf, hmac_kdf, AesKey, Array4x4, HmacKey, HmacMode, HmacTag, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, LEArray4x16, }; use caliptra_drivers_test_bin::{ hmac_kv_sequence_check, kv_release, populate_slot, TestRegisters, DOE_TEST_IV, ENCRYPTED_MEK, }; use caliptra_test_harness::test_suite; use itertools::Itertools; use zerocopy::IntoBytes; const REGULAR_LOCK_KV_RANGE: core::ops::Range<u8> = core::ops::Range { start: 0, end: 17 }; const OCP_LOCK_KV_RANGE: core::ops::Range<u8> = core::ops::Range { start: 16, end: 24 }; // TODO(clundin): Write test to verify DOE flow works. test_suite! { test_ocp_lock_enabled, test_hek_seed_fuse_bank, test_hek_seed_doe, test_aes_kv_release_unlocked, test_hmac_regular_kv_to_ocp_lock_kv_unlocked, // Run `test_hmac_regular_kv_to_ocp_lock_kv_unlocked` before to avoid overwriting MDK slot. test_populate_mdk, test_populate_hek, // Modifies behavior of subsequent tests. // Tests before should test "ROM" flows, afterwards they should test "Runtime" flows. test_set_ocp_lock_in_progress, test_decrypt_to_mek_kv_locked, test_kv_release, // Should be after `test_decrypt_to_mek_kv_locked`. test_decrypt_to_mek_kv_with_mek_secret_locked, test_hmac_regular_kv_to_ocp_lock_kv_locked, test_hmac_ocp_lock_kv_to_ocp_lock_kv_unlocked, test_aes_kv_release_locked, } fn test_ocp_lock_enabled() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let test_regs = TestRegisters::default(); assert!(test_regs.soc.ocp_lock_enabled()); } fn test_set_ocp_lock_in_progress() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut test_regs = TestRegisters::default(); test_regs.soc.ocp_lock_set_lock_in_progress(); assert!(test_regs.soc.ocp_lock_get_lock_in_progress()); } fn test_hek_seed_fuse_bank() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let test_regs = TestRegisters::default(); let fuse_bank = test_regs.soc.fuse_bank().ocp_hek_seed(); // Check hard coded hek seed from test MCU ROM. assert_eq!(fuse_bank, [0xABDE_FC82u32; 8].into()); } // TODO(clundin): Verify decrypted contents // TODO(clundin): Test can't be called twice. fn test_hek_seed_doe() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut test_regs = TestRegisters::default(); test_regs .doe .decrypt_hek_seed(&Array4x4::from(DOE_TEST_IV), KeyId::KeyId22) .unwrap(); } // AES Decrypt to KV should never work for all KVs until register OCP in progress is set. fn test_aes_kv_release_unlocked() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut test_regs = TestRegisters::default(); for (input_kv, output_kv) in OCP_LOCK_KV_RANGE.cartesian_product(OCP_LOCK_KV_RANGE) { let input = KeyId::try_from(input_kv).unwrap(); let output = KeyId::try_from(output_kv).unwrap(); let key = KeyReadArgs::new(input); let output = KeyWriteArgs::new(output, KeyUsage::default().set_dma_data_en()); populate_slot( &mut test_regs.hmac, &mut test_regs.trng, input, KeyUsage::default().set_aes_key_en(), ) .unwrap(); assert!(test_regs .aes .aes_256_ecb_decrypt_kv_internal(AesKey::KV(key), output, &LEArray4x16::default()) .is_err(),); } } // AES Decrypt to KV only work for KV 16 -> KV 23 when OCP in progress is set. fn test_aes_kv_release_locked() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut test_regs = TestRegisters::default(); for (input_kv, output_kv) in OCP_LOCK_KV_RANGE.cartesian_product(OCP_LOCK_KV_RANGE) { let input = KeyId::try_from(input_kv).unwrap(); let output = KeyId::try_from(output_kv).unwrap(); // Already exercised on the happy path. // Can't HMAC into KV 23, so we skip that as input. if (input == KeyId::KeyId16 || input == KeyId::KeyId23) || output == KeyId::KeyId23 { continue; } let key = KeyReadArgs::new(input); let output = KeyWriteArgs::new(output, KeyUsage::default().set_dma_data_en()); populate_slot( &mut test_regs.hmac, &mut test_regs.trng, input, KeyUsage::default().set_aes_key_en(), ) .unwrap(); assert!(test_regs .aes .aes_256_ecb_decrypt_kv_internal(AesKey::KV(key), output, &LEArray4x16::default()) .is_err(),); } } fn test_populate_mdk() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut test_regs = TestRegisters::default(); let cdi_slot = HmacKey::Key(KeyReadArgs::new(KeyId::KeyId3)); let mdk_slot = HmacTag::Key(KeyWriteArgs::from(KeyWriteArgs::new( KeyId::KeyId16, KeyUsage::default().set_aes_key_en(), ))); populate_slot( &mut test_regs.hmac, &mut test_regs.trng, KeyId::KeyId3, KeyUsage::default().set_hmac_key_en(), ) .unwrap(); hmac_kdf( &mut test_regs.hmac, cdi_slot, b"OCP_LOCK_MDK", // TODO: Use real label from spec. None, &mut test_regs.trng, mdk_slot, HmacMode::Hmac512, ) .unwrap(); } fn test_populate_hek() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut test_regs = TestRegisters::default(); let hek_seed = test_regs.soc.fuse_bank().ocp_hek_seed(); let cdi_slot = HmacKey::Key(KeyReadArgs::new(KeyId::KeyId3)); let hek_slot = HmacTag::Key(KeyWriteArgs::from(KeyWriteArgs::new( KeyId::KeyId22, KeyUsage::default().set_hmac_key_en(), ))); populate_slot( &mut test_regs.hmac, &mut test_regs.trng, KeyId::KeyId3, KeyUsage::default().set_hmac_key_en(), ) .unwrap(); hmac_kdf( &mut test_regs.hmac, cdi_slot, b"OCP_LOCK_HEK", // TODO: Use real label from spec. Some(hek_seed.as_bytes()), &mut test_regs.trng, hek_slot, HmacMode::Hmac512, ) .unwrap(); } // Before `ocp_lock_set_lock_in_progress` it's okay to HMAC from regular KV to OCP LOCK KV. fn test_hmac_regular_kv_to_ocp_lock_kv_unlocked() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); hmac_kv_sequence_check(REGULAR_LOCK_KV_RANGE, OCP_LOCK_KV_RANGE, true, |res| { assert!(res.is_ok()) }); } // After `ocp_lock_set_lock_in_progress` it's not okay to HMAC from regular KV to OCP LOCK KV. fn test_hmac_regular_kv_to_ocp_lock_kv_locked() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); hmac_kv_sequence_check(REGULAR_LOCK_KV_RANGE, OCP_LOCK_KV_RANGE, false, |res| { assert!(res.is_err()) }); } fn test_hmac_ocp_lock_kv_to_ocp_lock_kv_unlocked() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); hmac_kv_sequence_check(OCP_LOCK_KV_RANGE, OCP_LOCK_KV_RANGE, false, |res| { assert!(res.is_ok()) }); } // Checks if MEK can be decrypted to KV. // NOTE: Must be run after `test_populate_mdk`. fn test_decrypt_to_mek_kv_locked() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut test_regs = TestRegisters::default(); test_regs .aes .aes_256_ecb_decrypt_kv(&LEArray4x16::from(ENCRYPTED_MEK)) .unwrap(); } // Tests MEK derive flow. Does not validate Key release contents. fn test_decrypt_to_mek_kv_with_mek_secret_locked() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut test_regs = TestRegisters::default(); let mek_secret_kv = KeyId::KeyId21; populate_slot( &mut test_regs.hmac, &mut test_regs.trng, mek_secret_kv, KeyUsage::default().set_aes_key_en(), ) .unwrap(); let mek_seed = cmac_kdf( &mut test_regs.aes, AesKey::KV(KeyReadArgs::new(mek_secret_kv)), b"derived_mek", None, 4, ) .unwrap(); test_regs .aes .aes_256_ecb_decrypt_kv(&mek_seed.into()) .unwrap(); } // Must be after `test_decrypt_to_mek_kv_locked`. // Validates the contents of the MEK DMA KV release. fn test_kv_release() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut test_regs = TestRegisters::default(); kv_release(&mut test_regs); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/sha2_512_384acc_tests.rs
drivers/test-fw/src/bin/sha2_512_384acc_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha2_512_384_tests.rs Abstract: File contains test cases for SHA-384 Accelerator API --*/ #![no_std] #![no_main] use caliptra_drivers::{ memory_layout, Array4x12, Array4x16, Mailbox, Sha2_512_384Acc, ShaAccLockState, StreamEndianness, MBOX_SIZE_SUBSYSTEM, }; use caliptra_kat::Sha2_512_384AccKat; use caliptra_registers::mbox::MboxCsr; use caliptra_registers::sha512_acc::Sha512AccCsr; use caliptra_test_harness::test_suite; use core::slice; const SHA384_HASH_SIZE: usize = 48; const SHA512_HASH_SIZE: usize = 64; fn test_digest0() { let mut sha_acc = unsafe { Sha2_512_384Acc::new(Sha512AccCsr::new()) }; let mut mbox = unsafe { Mailbox::new(MboxCsr::new()) }; let data = "abcd".as_bytes(); let expected: [u8; SHA384_HASH_SIZE] = [ 0x11, 0x65, 0xb3, 0x40, 0x6f, 0xf0, 0xb5, 0x2a, 0x3d, 0x24, 0x72, 0x1f, 0x78, 0x54, 0x62, 0xca, 0x22, 0x76, 0xc9, 0xf4, 0x54, 0xa1, 0x16, 0xc2, 0xb2, 0xba, 0x20, 0x17, 0x1a, 0x79, 0x5, 0xea, 0x5a, 0x2, 0x66, 0x82, 0xeb, 0x65, 0x9c, 0x4d, 0x5f, 0x11, 0x5c, 0x36, 0x3a, 0xa3, 0xc7, 0x9b, ]; let expected_512: [u8; SHA512_HASH_SIZE] = [ 0xd8, 0x02, 0x2f, 0x20, 0x60, 0xad, 0x6e, 0xfd, 0x29, 0x7a, 0xb7, 0x3d, 0xcc, 0x53, 0x55, 0xc9, 0xb2, 0x14, 0x05, 0x4b, 0x0d, 0x17, 0x76, 0xa1, 0x36, 0xa6, 0x69, 0xd2, 0x6a, 0x7d, 0x3b, 0x14, 0xf7, 0x3a, 0xa0, 0xd0, 0xeb, 0xff, 0x19, 0xee, 0x33, 0x33, 0x68, 0xf0, 0x16, 0x4b, 0x64, 0x19, 0xa9, 0x6d, 0xa4, 0x9e, 0x3e, 0x48, 0x17, 0x53, 0xe7, 0xe9, 0x6b, 0x71, 0x6b, 0xdc, 0xcb, 0x6f, ]; if let Some(mut txn) = mbox.try_start_send_txn() { const CMD: u32 = 0x1c; assert!(txn.send_request(CMD, &data).is_ok()); let mut digest = Array4x12::default(); let mut digest_512 = Array4x16::default(); if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_384( data.len() as u32, 0, StreamEndianness::Reorder, (&mut digest).into(), ); assert!(result.is_ok()); assert_eq!(digest, Array4x12::from(expected)); drop(sha_acc_op); } else { assert!(false); } if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_512( data.len() as u32, 0, StreamEndianness::Reorder, (&mut digest_512).into(), ); assert!(result.is_ok()); assert_eq!(digest_512, Array4x16::from(expected_512)); drop(sha_acc_op); } else { assert!(false); } drop(txn); }; } fn test_digest1() { let mut sha_acc = unsafe { Sha2_512_384Acc::new(Sha512AccCsr::new()) }; let mut mbox = unsafe { Mailbox::new(MboxCsr::new()) }; let data = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".as_bytes(); let expected: [u8; SHA384_HASH_SIZE] = [ 0x09, 0x33, 0x0C, 0x33, 0xF7, 0x11, 0x47, 0xE8, 0x3D, 0x19, 0x2F, 0xC7, 0x82, 0xCD, 0x1B, 0x47, 0x53, 0x11, 0x1B, 0x17, 0x3B, 0x3B, 0x05, 0xD2, 0x2F, 0xA0, 0x80, 0x86, 0xE3, 0xB0, 0xF7, 0x12, 0xFC, 0xC7, 0xC7, 0x1A, 0x55, 0x7E, 0x2D, 0xB9, 0x66, 0xC3, 0xE9, 0xFA, 0x91, 0x74, 0x60, 0x39, ]; let expected_512: [u8; SHA512_HASH_SIZE] = [ 0x8e, 0x95, 0x9b, 0x75, 0xda, 0xe3, 0x13, 0xda, 0x8c, 0xf4, 0xf7, 0x28, 0x14, 0xfc, 0x14, 0x3f, 0x8f, 0x77, 0x79, 0xc6, 0xeb, 0x9f, 0x7f, 0xa1, 0x72, 0x99, 0xae, 0xad, 0xb6, 0x88, 0x90, 0x18, 0x50, 0x1d, 0x28, 0x9e, 0x49, 0x00, 0xf7, 0xe4, 0x33, 0x1b, 0x99, 0xde, 0xc4, 0xb5, 0x43, 0x3a, 0xc7, 0xd3, 0x29, 0xee, 0xb6, 0xdd, 0x26, 0x54, 0x5e, 0x96, 0xe5, 0x5b, 0x87, 0x4b, 0xe9, 0x09, ]; if let Some(mut txn) = mbox.try_start_send_txn() { const CMD: u32 = 0x1c; assert!(txn.send_request(CMD, &data).is_ok()); let mut digest = Array4x12::default(); let mut digest_512 = Array4x16::default(); if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_384( data.len() as u32, 0, StreamEndianness::Reorder, (&mut digest).into(), ); assert!(result.is_ok()); assert_eq!(digest, Array4x12::from(expected)); drop(sha_acc_op); } else { assert!(false); } if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_512( data.len() as u32, 0, StreamEndianness::Reorder, (&mut digest_512).into(), ); assert!(result.is_ok()); assert_eq!(digest_512, Array4x16::from(expected_512)); drop(sha_acc_op); } else { assert!(false); } drop(txn); }; } fn test_digest2() { let mut sha_acc = unsafe { Sha2_512_384Acc::new(Sha512AccCsr::new()) }; let mut mbox = unsafe { Mailbox::new(MboxCsr::new()) }; let data = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx".as_bytes(); let expected: [u8; SHA384_HASH_SIZE] = [ 0x67, 0x4b, 0x2e, 0x80, 0xff, 0x8d, 0x94, 0x00, 0x8d, 0xe7, 0x40, 0x9c, 0x7b, 0x1f, 0x87, 0x8f, 0x9f, 0xae, 0x3a, 0x0a, 0x6d, 0xae, 0x2f, 0x98, 0x2c, 0xca, 0x7e, 0x3a, 0xae, 0xf9, 0x1b, 0xf3, 0x25, 0xd3, 0xeb, 0x56, 0x82, 0x63, 0xa2, 0xe1, 0xe6, 0x85, 0x6a, 0xc7, 0x50, 0x70, 0x06, 0x2a, ]; let expected_512: [u8; SHA512_HASH_SIZE] = [ 0x21, 0x7d, 0x3d, 0x9c, 0x09, 0x52, 0xc3, 0xe4, 0x90, 0x7f, 0x06, 0xd4, 0xfb, 0xf3, 0x44, 0x60, 0xee, 0x85, 0x2c, 0x6a, 0xf5, 0x91, 0xb0, 0x7c, 0x2f, 0xa1, 0xc5, 0xe1, 0x64, 0x55, 0x83, 0x63, 0x74, 0xc9, 0x5a, 0xe3, 0x3e, 0x18, 0x42, 0x27, 0x91, 0x3f, 0x8a, 0x2e, 0x22, 0x7e, 0x3b, 0xbd, 0x51, 0x87, 0xce, 0x57, 0xaa, 0x1b, 0xad, 0x11, 0xa8, 0x0f, 0x62, 0x24, 0x12, 0xeb, 0x08, 0x84, ]; let mut digest = Array4x12::default(); let mut digest_512 = Array4x16::default(); if let Some(mut txn) = mbox.try_start_send_txn() { const CMD: u32 = 0x1c; assert!(txn.send_request(CMD, &data).is_ok()); if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_384( data.len() as u32, 0, StreamEndianness::Reorder, (&mut digest).into(), ); assert!(result.is_ok()); assert_eq!(digest, Array4x12::from(expected)); drop(sha_acc_op); } else { assert!(false); } if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_512( data.len() as u32, 0, StreamEndianness::Reorder, (&mut digest_512).into(), ); assert!(result.is_ok()); assert_eq!(digest_512, Array4x16::from(expected_512)); drop(sha_acc_op); } else { assert!(false); } drop(txn); }; } fn test_digest_offset() { let mut sha_acc = unsafe { Sha2_512_384Acc::new(Sha512AccCsr::new()) }; let mut mbox = unsafe { Mailbox::new(MboxCsr::new()) }; let data = "abcdefghijklmnopqrst".as_bytes(); let expected: [u8; SHA384_HASH_SIZE] = [ 0xd4, 0xcc, 0x9a, 0x0d, 0xc5, 0x46, 0x09, 0x40, 0xb0, 0x50, 0xa2, 0x42, 0x14, 0xf6, 0x78, 0xf6, 0x3b, 0x99, 0x3e, 0xc3, 0xc5, 0x7d, 0xb9, 0xcc, 0x20, 0x7b, 0x20, 0x9c, 0xbd, 0xa7, 0xcc, 0x09, 0xe9, 0x4a, 0x84, 0x62, 0x83, 0x56, 0x7d, 0x28, 0xd8, 0xc7, 0x73, 0xc1, 0x87, 0x39, 0x07, 0xa7, ]; let expected_512: [u8; SHA512_HASH_SIZE] = [ 0xfb, 0x98, 0x27, 0x30, 0xed, 0x3d, 0x46, 0x8a, 0xe7, 0xbe, 0x25, 0x12, 0x1e, 0x45, 0xcf, 0x4f, 0x7f, 0x2b, 0xd1, 0xfd, 0xd1, 0x77, 0x14, 0xf0, 0xae, 0x5b, 0x1c, 0xa9, 0x2d, 0x1f, 0xf3, 0xf2, 0x35, 0x2d, 0x57, 0xc0, 0x8f, 0x88, 0xe9, 0x23, 0xf0, 0x88, 0x06, 0xc6, 0x01, 0x6c, 0xc6, 0x7b, 0xf5, 0xf0, 0x09, 0x28, 0x27, 0x39, 0xa4, 0xe0, 0x0a, 0xf3, 0xce, 0x8c, 0xa8, 0xf7, 0x04, 0xca, ]; let mut digest = Array4x12::default(); let mut digest_512 = Array4x16::default(); if let Some(mut txn) = mbox.try_start_send_txn() { const CMD: u32 = 0x1c; assert!(txn.send_request(CMD, &data).is_ok()); if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_384(8, 4, StreamEndianness::Reorder, (&mut digest).into()); assert!(result.is_ok()); assert_eq!(digest, Array4x12::from(expected)); drop(sha_acc_op); } else { assert!(false); } if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_512(8, 4, StreamEndianness::Reorder, (&mut digest_512).into()); assert!(result.is_ok()); assert_eq!(digest_512, Array4x16::from(expected_512)); drop(sha_acc_op); } else { assert!(false); } drop(txn); }; } fn test_digest_zero_size_buffer() { let mut sha_acc = unsafe { Sha2_512_384Acc::new(Sha512AccCsr::new()) }; let expected: [u8; SHA384_HASH_SIZE] = [ 0x38, 0xB0, 0x60, 0xA7, 0x51, 0xAC, 0x96, 0x38, 0x4C, 0xD9, 0x32, 0x7E, 0xB1, 0xB1, 0xE3, 0x6A, 0x21, 0xFD, 0xB7, 0x11, 0x14, 0xBE, 0x07, 0x43, 0x4C, 0x0C, 0xC7, 0xBF, 0x63, 0xF6, 0xE1, 0xDA, 0x27, 0x4E, 0xDE, 0xBF, 0xE7, 0x6F, 0x65, 0xFB, 0xD5, 0x1A, 0xD2, 0xF1, 0x48, 0x98, 0xB9, 0x5B, ]; let expected_512: [u8; SHA512_HASH_SIZE] = [ 0xcf, 0x83, 0xe1, 0x35, 0x7e, 0xef, 0xb8, 0xbd, 0xf1, 0x54, 0x28, 0x50, 0xd6, 0x6d, 0x80, 0x07, 0xd6, 0x20, 0xe4, 0x05, 0x0b, 0x57, 0x15, 0xdc, 0x83, 0xf4, 0xa9, 0x21, 0xd3, 0x6c, 0xe9, 0xce, 0x47, 0xd0, 0xd1, 0x3c, 0x5d, 0x85, 0xf2, 0xb0, 0xff, 0x83, 0x18, 0xd2, 0x87, 0x7e, 0xec, 0x2f, 0x63, 0xb9, 0x31, 0xbd, 0x47, 0x41, 0x7a, 0x81, 0xa5, 0x38, 0x32, 0x7a, 0xf9, 0x27, 0xda, 0x3e, ]; let mut digest = Array4x12::default(); let mut digest_512 = Array4x16::default(); if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_384(0, 0, StreamEndianness::Native, (&mut digest).into()); assert!(result.is_ok()); assert_eq!(digest, Array4x12::from(expected)); drop(sha_acc_op); } else { assert!(false); }; if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_512(0, 0, StreamEndianness::Native, (&mut digest_512).into()); assert!(result.is_ok()); assert_eq!(digest_512, Array4x16::from(expected_512)); drop(sha_acc_op); } else { assert!(false); }; } // use the lowest common denominator in mailbox size fn test_digest_max_mailbox_size() { let mut sha_acc = unsafe { Sha2_512_384Acc::new(Sha512AccCsr::new()) }; let expected: [u8; SHA384_HASH_SIZE] = [ 0x65, 0xb1, 0xf4, 0x3f, 0x6d, 0x05, 0x05, 0x21, 0x05, 0x87, 0x73, 0x00, 0xa4, 0x4c, 0x7e, 0xc5, 0x69, 0x9b, 0xbe, 0x85, 0x10, 0xaa, 0xe4, 0xc9, 0xc6, 0x4f, 0x27, 0x87, 0x1b, 0xd5, 0xef, 0xfa, 0x69, 0xe8, 0x36, 0x7f, 0x57, 0x87, 0xf6, 0x6c, 0xe8, 0x15, 0xa3, 0x3e, 0x5c, 0xc8, 0xd2, 0x6e, ]; let expected_512: [u8; SHA512_HASH_SIZE] = [ 0x6e, 0xb7, 0xf1, 0x6c, 0xf7, 0xaf, 0xca, 0xbe, 0x9b, 0xde, 0xa8, 0x8b, 0xda, 0xb0, 0x46, 0x9a, 0x79, 0x37, 0xeb, 0x71, 0x5a, 0xda, 0x9d, 0xfd, 0x8f, 0x42, 0x8d, 0x9d, 0x38, 0xd8, 0x61, 0x33, 0x94, 0x5f, 0x5f, 0x2f, 0x26, 0x88, 0xdd, 0xd9, 0x60, 0x62, 0x22, 0x3a, 0x39, 0xb5, 0xd4, 0x7f, 0x07, 0xaf, 0xc3, 0xc4, 0x8d, 0x9d, 0xb1, 0xd5, 0xee, 0x3f, 0x41, 0xc8, 0xd2, 0x74, 0xdc, 0xcf, ]; { // Clear the mailbox SRAM; FPGA model doesn't clear this on reset. let mut mbox = unsafe { MboxCsr::new() }; // Grab lock assert!(!mbox.regs().lock().read().lock()); let mbox_sram = unsafe { slice::from_raw_parts_mut( memory_layout::MBOX_ORG as *mut u8, MBOX_SIZE_SUBSYSTEM as usize, ) }; mbox_sram.fill(0); mbox.regs_mut().unlock().write(|w| w.unlock(true)); } let mut digest = Array4x12::default(); let mut digest_512 = Array4x16::default(); if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_384( MBOX_SIZE_SUBSYSTEM as u32, 0, StreamEndianness::Native, (&mut digest).into(), ); assert!(result.is_ok()); assert_eq!(digest, Array4x12::from(expected)); drop(sha_acc_op); } else { assert!(false); }; if let Some(mut sha_acc_op) = sha_acc .try_start_operation(ShaAccLockState::NotAcquired) .unwrap() { let result = sha_acc_op.digest_512( MBOX_SIZE_SUBSYSTEM as u32, 0, StreamEndianness::Native, (&mut digest_512).into(), ); assert!(result.is_ok()); assert_eq!(digest_512, Array4x16::from(expected_512)); drop(sha_acc_op); } else { assert!(false); }; } fn test_kat() { let mut sha_acc = unsafe { Sha2_512_384Acc::new(Sha512AccCsr::new()) }; assert_eq!( Sha2_512_384AccKat::default() .execute(&mut sha_acc, ShaAccLockState::AssumedLocked) .is_ok(), true ); } test_suite! { test_kat, test_digest_max_mailbox_size, test_digest_offset, test_digest0, test_digest1, test_digest2, test_digest_zero_size_buffer, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/mailbox_driver_sender.rs
drivers/test-fw/src/bin/mailbox_driver_sender.rs
// Licensed under the Apache-2.0 license //! A very simple program that uses the driver to send mailbox messages #![no_main] #![no_std] // Needed to bring in startup code #[allow(unused)] use caliptra_test_harness::{self, println}; use caliptra_drivers::{self, Mailbox}; use caliptra_registers::mbox::MboxCsr; #[panic_handler] pub fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } #[no_mangle] extern "C" fn main() { let mut mbox = unsafe { Mailbox::new(MboxCsr::new()) }; // 0 byte request let mut txn = mbox.try_start_send_txn().unwrap(); txn.send_request(0xa000_0000, b"").unwrap(); while !txn.is_response_ready() {} txn.complete().unwrap(); drop(txn); // 3 byte request let mut txn = mbox.wait_until_start_send_txn(); txn.send_request(0xa000_1000, b"Hi!").unwrap(); while !txn.is_response_ready() {} txn.complete().unwrap(); drop(txn); // 4 byte request let mut txn = mbox.wait_until_start_send_txn(); txn.send_request(0xa000_2000, b"Hi!!").unwrap(); while !txn.is_response_ready() {} txn.complete().unwrap(); drop(txn); // 6 byte request let mut txn = mbox.wait_until_start_send_txn(); txn.send_request(0xa000_3000, b"Hello!").unwrap(); while !txn.is_response_ready() {} txn.complete().unwrap(); drop(txn); // 8 byte request let mut txn = mbox.wait_until_start_send_txn(); txn.send_request(0xa000_4000, b"Hello!!!").unwrap(); while !txn.is_response_ready() {} txn.complete().unwrap(); drop(txn); // write_cmd / write_dlen / execute_request used separately let mut txn = mbox.wait_until_start_send_txn(); txn.write_cmd(0xb000_0000).unwrap(); txn.write_dlen(0).unwrap(); txn.execute_request().unwrap(); while !txn.is_response_ready() {} txn.complete().unwrap(); drop(txn); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/lms_32_tests.rs
drivers/test-fw/src/bin/lms_32_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: lms_32_tests.rs Abstract: File contains test cases for LMS signature verification using SHA256. As of March 2023 Caliptra does not use SHA256 due to the additional size of the signatures and verification time compared to SHA256/192. These tests are included in case there is a desire in the future to use SHA256. --*/ #![no_std] #![no_main] use caliptra_drivers::{HashValue, Lms, LmsResult, Sha256}; use caliptra_lms_types::{ bytes_to_words_8, LmotsAlgorithmType, LmotsSignature, LmsAlgorithmType, LmsPublicKey, LmsSignature, }; use caliptra_registers::sha256::Sha256Reg; use caliptra_test_harness::test_suite; use zerocopy::{BigEndian, LittleEndian, U32}; fn test_hash_message_32() { let mut sha256 = unsafe { Sha256::new(Sha256Reg::new()) }; const MESSAGE: [u8; 162] = [ 0x54, 0x68, 0x65, 0x20, 0x70, 0x6f, 0x77, 0x65, 0x72, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x64, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x55, 0x6e, 0x69, 0x74, 0x65, 0x64, 0x20, 0x53, 0x74, 0x61, 0x74, 0x65, 0x73, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x6e, 0x6f, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x68, 0x69, 0x62, 0x69, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x69, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x53, 0x74, 0x61, 0x74, 0x65, 0x73, 0x2c, 0x20, 0x61, 0x72, 0x65, 0x20, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x53, 0x74, 0x61, 0x74, 0x65, 0x73, 0x20, 0x72, 0x65, 0x73, 0x70, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x6c, 0x79, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x65, 0x6f, 0x70, 0x6c, 0x65, 0x2e, 0x0a, ]; const LMS_IDENTIFIER: [u8; 16] = [ 0xd2, 0xf1, 0x4f, 0xf6, 0x34, 0x6a, 0xf9, 0x64, 0x56, 0x9f, 0x7d, 0x6c, 0xb8, 0x80, 0xa1, 0xb6, ]; const FINAL_C: [U32<LittleEndian>; 8] = bytes_to_words_8([ 0x07, 0x03, 0xc4, 0x91, 0xe7, 0x55, 0x8b, 0x35, 0x01, 0x1e, 0xce, 0x35, 0x92, 0xea, 0xa5, 0xda, 0x4d, 0x91, 0x87, 0x86, 0x77, 0x12, 0x33, 0xe8, 0x35, 0x3b, 0xc4, 0xf6, 0x23, 0x23, 0x18, 0x5c, ]); let lms_q: u32 = 0xa; let q_str = lms_q.to_be_bytes(); let result = Lms::default().hash_message::<8>(&mut sha256, &MESSAGE, &LMS_IDENTIFIER, &q_str, &FINAL_C); let expected = HashValue::from([ 197, 161, 71, 71, 171, 172, 219, 132, 181, 174, 255, 248, 113, 57, 175, 182, 199, 253, 140, 213, 215, 42, 14, 95, 56, 156, 32, 130, 218, 23, 63, 40, ]); assert_eq!(result.unwrap(), expected); } fn test_ots_32() { let mut sha256 = unsafe { Sha256::new(Sha256Reg::new()) }; const MESSAGE: [u8; 162] = [ 0x54, 0x68, 0x65, 0x20, 0x70, 0x6f, 0x77, 0x65, 0x72, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x64, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x55, 0x6e, 0x69, 0x74, 0x65, 0x64, 0x20, 0x53, 0x74, 0x61, 0x74, 0x65, 0x73, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x6e, 0x6f, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x68, 0x69, 0x62, 0x69, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x69, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x53, 0x74, 0x61, 0x74, 0x65, 0x73, 0x2c, 0x20, 0x61, 0x72, 0x65, 0x20, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x53, 0x74, 0x61, 0x74, 0x65, 0x73, 0x20, 0x72, 0x65, 0x73, 0x70, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x6c, 0x79, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x65, 0x6f, 0x70, 0x6c, 0x65, 0x2e, 0x0a, ]; const LMS_IDENTIFIER: [u8; 16] = [ 0xd2, 0xf1, 0x4f, 0xf6, 0x34, 0x6a, 0xf9, 0x64, 0x56, 0x9f, 0x7d, 0x6c, 0xb8, 0x80, 0xa1, 0xb6, ]; const FINAL_C: [U32<LittleEndian>; 8] = bytes_to_words_8([ 0x07, 0x03, 0xc4, 0x91, 0xe7, 0x55, 0x8b, 0x35, 0x01, 0x1e, 0xce, 0x35, 0x92, 0xea, 0xa5, 0xda, 0x4d, 0x91, 0x87, 0x86, 0x77, 0x12, 0x33, 0xe8, 0x35, 0x3b, 0xc4, 0xf6, 0x23, 0x23, 0x18, 0x5c, ]); const FINAL_Y: [[U32<LittleEndian>; 8]; 34] = [ bytes_to_words_8([ 0x95, 0xca, 0xe0, 0x5b, 0x89, 0x9e, 0x35, 0xdf, 0xfd, 0x71, 0x70, 0x54, 0x70, 0x62, 0x09, 0x98, 0x8e, 0xbf, 0xdf, 0x6e, 0x37, 0x96, 0x0b, 0xb5, 0xc3, 0x8d, 0x76, 0x57, 0xe8, 0xbf, 0xfe, 0xef, ]), bytes_to_words_8([ 0x9b, 0xc0, 0x42, 0xda, 0x4b, 0x45, 0x25, 0x65, 0x04, 0x85, 0xc6, 0x6d, 0x0c, 0xe1, 0x9b, 0x31, 0x75, 0x87, 0xc6, 0xba, 0x4b, 0xff, 0xcc, 0x42, 0x8e, 0x25, 0xd0, 0x89, 0x31, 0xe7, 0x2d, 0xfb, ]), bytes_to_words_8([ 0x6a, 0x12, 0x0c, 0x56, 0x12, 0x34, 0x42, 0x58, 0xb8, 0x5e, 0xfd, 0xb7, 0xdb, 0x1d, 0xb9, 0xe1, 0x86, 0x5a, 0x73, 0xca, 0xf9, 0x65, 0x57, 0xeb, 0x39, 0xed, 0x3e, 0x3f, 0x42, 0x69, 0x33, 0xac, ]), bytes_to_words_8([ 0x9e, 0xed, 0xdb, 0x03, 0xa1, 0xd2, 0x37, 0x4a, 0xf7, 0xbf, 0x77, 0x18, 0x55, 0x77, 0x45, 0x62, 0x37, 0xf9, 0xde, 0x2d, 0x60, 0x11, 0x3c, 0x23, 0xf8, 0x46, 0xdf, 0x26, 0xfa, 0x94, 0x20, 0x08, ]), bytes_to_words_8([ 0xa6, 0x98, 0x99, 0x4c, 0x08, 0x27, 0xd9, 0x0e, 0x86, 0xd4, 0x3e, 0x0d, 0xf7, 0xf4, 0xbf, 0xcd, 0xb0, 0x9b, 0x86, 0xa3, 0x73, 0xb9, 0x82, 0x88, 0xb7, 0x09, 0x4a, 0xd8, 0x1a, 0x01, 0x85, 0xac, ]), bytes_to_words_8([ 0x10, 0x0e, 0x4f, 0x2c, 0x5f, 0xc3, 0x8c, 0x00, 0x3c, 0x1a, 0xb6, 0xfe, 0xa4, 0x79, 0xeb, 0x2f, 0x5e, 0xbe, 0x48, 0xf5, 0x84, 0xd7, 0x15, 0x9b, 0x8a, 0xda, 0x03, 0x58, 0x6e, 0x65, 0xad, 0x9c, ]), bytes_to_words_8([ 0x96, 0x9f, 0x6a, 0xec, 0xbf, 0xe4, 0x4c, 0xf3, 0x56, 0x88, 0x8a, 0x7b, 0x15, 0xa3, 0xff, 0x07, 0x4f, 0x77, 0x17, 0x60, 0xb2, 0x6f, 0x9c, 0x04, 0x88, 0x4e, 0xe1, 0xfa, 0xa3, 0x29, 0xfb, 0xf4, ]), bytes_to_words_8([ 0xe6, 0x1a, 0xf2, 0x3a, 0xee, 0x7f, 0xa5, 0xd4, 0xd9, 0xa5, 0xdf, 0xcf, 0x43, 0xc4, 0xc2, 0x6c, 0xe8, 0xae, 0xa2, 0xce, 0x8a, 0x29, 0x90, 0xd7, 0xba, 0x7b, 0x57, 0x10, 0x8b, 0x47, 0xda, 0xbf, ]), bytes_to_words_8([ 0xbe, 0xad, 0xb2, 0xb2, 0x5b, 0x3c, 0xac, 0xc1, 0xac, 0x0c, 0xef, 0x34, 0x6c, 0xbb, 0x90, 0xfb, 0x04, 0x4b, 0xee, 0xe4, 0xfa, 0xc2, 0x60, 0x3a, 0x44, 0x2b, 0xdf, 0x7e, 0x50, 0x72, 0x43, 0xb7, ]), bytes_to_words_8([ 0x31, 0x9c, 0x99, 0x44, 0xb1, 0x58, 0x6e, 0x89, 0x9d, 0x43, 0x1c, 0x7f, 0x91, 0xbc, 0xcc, 0xc8, 0x69, 0x0d, 0xbf, 0x59, 0xb2, 0x83, 0x86, 0xb2, 0x31, 0x5f, 0x3d, 0x36, 0xef, 0x2e, 0xaa, 0x3c, ]), bytes_to_words_8([ 0xf3, 0x0b, 0x2b, 0x51, 0xf4, 0x8b, 0x71, 0xb0, 0x03, 0xdf, 0xb0, 0x82, 0x49, 0x48, 0x42, 0x01, 0x04, 0x3f, 0x65, 0xf5, 0xa3, 0xef, 0x6b, 0xbd, 0x61, 0xdd, 0xfe, 0xe8, 0x1a, 0xca, 0x9c, 0xe6, ]), bytes_to_words_8([ 0x00, 0x81, 0x26, 0x2a, 0x00, 0x00, 0x04, 0x80, 0xdc, 0xbc, 0x9a, 0x3d, 0xa6, 0xfb, 0xef, 0x5c, 0x1c, 0x0a, 0x55, 0xe4, 0x8a, 0x0e, 0x72, 0x9f, 0x91, 0x84, 0xfc, 0xb1, 0x40, 0x7c, 0x31, 0x52, ]), bytes_to_words_8([ 0x9d, 0xb2, 0x68, 0xf6, 0xfe, 0x50, 0x03, 0x2a, 0x36, 0x3c, 0x98, 0x01, 0x30, 0x68, 0x37, 0xfa, 0xfa, 0xbd, 0xf9, 0x57, 0xfd, 0x97, 0xea, 0xfc, 0x80, 0xdb, 0xd1, 0x65, 0xe4, 0x35, 0xd0, 0xe2, ]), bytes_to_words_8([ 0xdf, 0xd8, 0x36, 0xa2, 0x8b, 0x35, 0x40, 0x23, 0x92, 0x4b, 0x6f, 0xb7, 0xe4, 0x8b, 0xc0, 0xb3, 0xed, 0x95, 0xee, 0xa6, 0x4c, 0x2d, 0x40, 0x2f, 0x4d, 0x73, 0x4c, 0x8d, 0xc2, 0x6f, 0x3a, 0xc5, ]), bytes_to_words_8([ 0x91, 0x82, 0x5d, 0xae, 0xf0, 0x1e, 0xae, 0x3c, 0x38, 0xe3, 0x32, 0x8d, 0x00, 0xa7, 0x7d, 0xc6, 0x57, 0x03, 0x4f, 0x28, 0x7c, 0xcb, 0x0f, 0x0e, 0x1c, 0x9a, 0x7c, 0xbd, 0xc8, 0x28, 0xf6, 0x27, ]), bytes_to_words_8([ 0x20, 0x5e, 0x47, 0x37, 0xb8, 0x4b, 0x58, 0x37, 0x65, 0x51, 0xd4, 0x4c, 0x12, 0xc3, 0xc2, 0x15, 0xc8, 0x12, 0xa0, 0x97, 0x07, 0x89, 0xc8, 0x3d, 0xe5, 0x1d, 0x6a, 0xd7, 0x87, 0x27, 0x19, 0x63, ]), bytes_to_words_8([ 0x32, 0x7f, 0x0a, 0x5f, 0xbb, 0x6b, 0x59, 0x07, 0xde, 0xc0, 0x2c, 0x9a, 0x90, 0x93, 0x4a, 0xf5, 0xa1, 0xc6, 0x3b, 0x72, 0xc8, 0x26, 0x53, 0x60, 0x5d, 0x1d, 0xcc, 0xe5, 0x15, 0x96, 0xb3, 0xc2, ]), bytes_to_words_8([ 0xb4, 0x56, 0x96, 0x68, 0x9f, 0x2e, 0xb3, 0x82, 0x00, 0x74, 0x97, 0x55, 0x76, 0x92, 0xca, 0xac, 0x4d, 0x57, 0xb5, 0xde, 0x9f, 0x55, 0x69, 0xbc, 0x2a, 0xd0, 0x13, 0x7f, 0xd4, 0x7f, 0xb4, 0x7e, ]), bytes_to_words_8([ 0x66, 0x4f, 0xcb, 0x6d, 0xb4, 0x97, 0x1f, 0x5b, 0x3e, 0x07, 0xac, 0xed, 0xa9, 0xac, 0x13, 0x0e, 0x9f, 0x38, 0x18, 0x2d, 0xe9, 0x94, 0xcf, 0xf1, 0x92, 0xec, 0x0e, 0x82, 0xfd, 0x6d, 0x4c, 0xb7, ]), bytes_to_words_8([ 0xf3, 0xfe, 0x00, 0x81, 0x25, 0x89, 0xb7, 0xa7, 0xce, 0x51, 0x54, 0x40, 0x45, 0x64, 0x33, 0x01, 0x6b, 0x84, 0xa5, 0x9b, 0xec, 0x66, 0x19, 0xa1, 0xc6, 0xc0, 0xb3, 0x7d, 0xd1, 0x45, 0x0e, 0xd4, ]), bytes_to_words_8([ 0xf2, 0xd8, 0xb5, 0x84, 0x41, 0x0c, 0xed, 0xa8, 0x02, 0x5f, 0x5d, 0x2d, 0x8d, 0xd0, 0xd2, 0x17, 0x6f, 0xc1, 0xcf, 0x2c, 0xc0, 0x6f, 0xa8, 0xc8, 0x2b, 0xed, 0x4d, 0x94, 0x4e, 0x71, 0x33, 0x9e, ]), bytes_to_words_8([ 0xce, 0x78, 0x0f, 0xd0, 0x25, 0xbd, 0x41, 0xec, 0x34, 0xeb, 0xff, 0x9d, 0x42, 0x70, 0xa3, 0x22, 0x4e, 0x01, 0x9f, 0xcb, 0x44, 0x44, 0x74, 0xd4, 0x82, 0xfd, 0x2d, 0xbe, 0x75, 0xef, 0xb2, 0x03, ]), bytes_to_words_8([ 0x89, 0xcc, 0x10, 0xcd, 0x60, 0x0a, 0xbb, 0x54, 0xc4, 0x7e, 0xde, 0x93, 0xe0, 0x8c, 0x11, 0x4e, 0xdb, 0x04, 0x11, 0x7d, 0x71, 0x4d, 0xc1, 0xd5, 0x25, 0xe1, 0x1b, 0xed, 0x87, 0x56, 0x19, 0x2f, ]), bytes_to_words_8([ 0x92, 0x9d, 0x15, 0x46, 0x2b, 0x93, 0x9f, 0xf3, 0xf5, 0x2f, 0x22, 0x52, 0xda, 0x2e, 0xd6, 0x4d, 0x8f, 0xae, 0x88, 0x81, 0x8b, 0x1e, 0xfa, 0x2c, 0x7b, 0x08, 0xc8, 0x79, 0x4f, 0xb1, 0xb2, 0x14, ]), bytes_to_words_8([ 0xaa, 0x23, 0x3d, 0xb3, 0x16, 0x28, 0x33, 0x14, 0x1e, 0xa4, 0x38, 0x3f, 0x1a, 0x6f, 0x12, 0x0b, 0xe1, 0xdb, 0x82, 0xce, 0x36, 0x30, 0xb3, 0x42, 0x91, 0x14, 0x46, 0x31, 0x57, 0xa6, 0x4e, 0x91, ]), bytes_to_words_8([ 0x23, 0x4d, 0x47, 0x5e, 0x2f, 0x79, 0xcb, 0xf0, 0x5e, 0x4d, 0xb6, 0xa9, 0x40, 0x7d, 0x72, 0xc6, 0xbf, 0xf7, 0xd1, 0x19, 0x8b, 0x5c, 0x4d, 0x6a, 0xad, 0x28, 0x31, 0xdb, 0x61, 0x27, 0x49, 0x93, ]), bytes_to_words_8([ 0x71, 0x5a, 0x01, 0x82, 0xc7, 0xdc, 0x80, 0x89, 0xe3, 0x2c, 0x85, 0x31, 0xde, 0xed, 0x4f, 0x74, 0x31, 0xc0, 0x7c, 0x02, 0x19, 0x5e, 0xba, 0x2e, 0xf9, 0x1e, 0xfb, 0x56, 0x13, 0xc3, 0x7a, 0xf7, ]), bytes_to_words_8([ 0xae, 0x0c, 0x06, 0x6b, 0xab, 0xc6, 0x93, 0x69, 0x70, 0x0e, 0x1d, 0xd2, 0x6e, 0xdd, 0xc0, 0xd2, 0x16, 0xc7, 0x81, 0xd5, 0x6e, 0x4c, 0xe4, 0x7e, 0x33, 0x03, 0xfa, 0x73, 0x00, 0x7f, 0xf7, 0xb9, ]), bytes_to_words_8([ 0x49, 0xef, 0x23, 0xbe, 0x2a, 0xa4, 0xdb, 0xf2, 0x52, 0x06, 0xfe, 0x45, 0xc2, 0x0d, 0xd8, 0x88, 0x39, 0x5b, 0x25, 0x26, 0x39, 0x1a, 0x72, 0x49, 0x96, 0xa4, 0x41, 0x56, 0xbe, 0xac, 0x80, 0x82, ]), bytes_to_words_8([ 0x12, 0x85, 0x87, 0x92, 0xbf, 0x8e, 0x74, 0xcb, 0xa4, 0x9d, 0xee, 0x5e, 0x88, 0x12, 0xe0, 0x19, 0xda, 0x87, 0x45, 0x4b, 0xff, 0x9e, 0x84, 0x7e, 0xd8, 0x3d, 0xb0, 0x7a, 0xf3, 0x13, 0x74, 0x30, ]), bytes_to_words_8([ 0x82, 0xf8, 0x80, 0xa2, 0x78, 0xf6, 0x82, 0xc2, 0xbd, 0x0a, 0xd6, 0x88, 0x7c, 0xb5, 0x9f, 0x65, 0x2e, 0x15, 0x59, 0x87, 0xd6, 0x1b, 0xbf, 0x6a, 0x88, 0xd3, 0x6e, 0xe9, 0x3b, 0x60, 0x72, 0xe6, ]), bytes_to_words_8([ 0x65, 0x6d, 0x9c, 0xcb, 0xaa, 0xe3, 0xd6, 0x55, 0x85, 0x2e, 0x38, 0xde, 0xb3, 0xa2, 0xdc, 0xf8, 0x05, 0x8d, 0xc9, 0xfb, 0x6f, 0x2a, 0xb3, 0xd3, 0xb3, 0x53, 0x9e, 0xb7, 0x7b, 0x24, 0x8a, 0x66, ]), bytes_to_words_8([ 0x10, 0x91, 0xd0, 0x5e, 0xb6, 0xe2, 0xf2, 0x97, 0x77, 0x4f, 0xe6, 0x05, 0x35, 0x98, 0x45, 0x7c, 0xc6, 0x19, 0x08, 0x31, 0x8d, 0xe4, 0xb8, 0x26, 0xf0, 0xfc, 0x86, 0xd4, 0xbb, 0x11, 0x7d, 0x33, ]), bytes_to_words_8([ 0xe8, 0x65, 0xaa, 0x80, 0x50, 0x09, 0xcc, 0x29, 0x18, 0xd9, 0xc2, 0xf8, 0x40, 0xc4, 0xda, 0x43, 0xa7, 0x03, 0xad, 0x9f, 0x5b, 0x58, 0x06, 0x16, 0x3d, 0x71, 0x61, 0x69, 0x6b, 0x5a, 0x0a, 0xdc, ]), ]; const LMS_Q: u32 = 0xa; let q_str = LMS_Q.to_be_bytes(); let result = Lms::default() .hash_message::<8>(&mut sha256, &MESSAGE, &LMS_IDENTIFIER, &q_str, &FINAL_C) .unwrap(); let expected = HashValue::from([ 197, 161, 71, 71, 171, 172, 219, 132, 181, 174, 255, 248, 113, 57, 175, 182, 199, 253, 140, 213, 215, 42, 14, 95, 56, 156, 32, 130, 218, 23, 63, 40, ]); assert_eq!(result, expected); const FINAL_OTS_SIG: LmotsSignature<8, 34> = LmotsSignature { ots_type: LmotsAlgorithmType::LmotsSha256N32W8, nonce: FINAL_C, y: FINAL_Y, }; const EXPECTED_OTS: HashValue<8> = HashValue([ 2072627637, 1120309408, 704813360, 3313968810, 4052064326, 4058164870, 1148328746, 576791441, ]); let result_ots = Lms::default().candidate_ots_signature::<8, 34>( &mut sha256, &LMS_IDENTIFIER, FINAL_OTS_SIG.ots_type, &q_str, &FINAL_OTS_SIG.y, &result, ); assert_eq!(result_ots.unwrap(), EXPECTED_OTS); } // from https://www.rfc-editor.org/rfc/rfc8554#page-52 // this is the lower part of the HSS tree fn test_lms_lower_32() { let mut sha256 = unsafe { Sha256::new(Sha256Reg::new()) }; const MESSAGE: [u8; 162] = [ 0x54, 0x68, 0x65, 0x20, 0x70, 0x6f, 0x77, 0x65, 0x72, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x64, 0x65, 0x6c, 0x65, 0x67, 0x61, 0x74, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x55, 0x6e, 0x69, 0x74, 0x65, 0x64, 0x20, 0x53, 0x74, 0x61, 0x74, 0x65, 0x73, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x69, 0x74, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x6e, 0x6f, 0x72, 0x20, 0x70, 0x72, 0x6f, 0x68, 0x69, 0x62, 0x69, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x69, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x53, 0x74, 0x61, 0x74, 0x65, 0x73, 0x2c, 0x20, 0x61, 0x72, 0x65, 0x20, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x53, 0x74, 0x61, 0x74, 0x65, 0x73, 0x20, 0x72, 0x65, 0x73, 0x70, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x6c, 0x79, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x65, 0x6f, 0x70, 0x6c, 0x65, 0x2e, 0x0a, ]; const LMS_IDENTIFIER: [u8; 16] = [ 0xd2, 0xf1, 0x4f, 0xf6, 0x34, 0x6a, 0xf9, 0x64, 0x56, 0x9f, 0x7d, 0x6c, 0xb8, 0x80, 0xa1, 0xb6, ]; const LMS_PUBLIC_HASH: [U32<LittleEndian>; 8] = bytes_to_words_8([ 0x6c, 0x50, 0x04, 0x91, 0x7d, 0xa6, 0xea, 0xfe, 0x4d, 0x9e, 0xf6, 0xc6, 0x40, 0x7b, 0x3d, 0xb0, 0xe5, 0x48, 0x5b, 0x12, 0x2d, 0x9e, 0xbe, 0x15, 0xcd, 0xa9, 0x3c, 0xfe, 0xc5, 0x82, 0xd7, 0xab, ]); const FINAL_C: [U32<LittleEndian>; 8] = bytes_to_words_8([ 0x07, 0x03, 0xc4, 0x91, 0xe7, 0x55, 0x8b, 0x35, 0x01, 0x1e, 0xce, 0x35, 0x92, 0xea, 0xa5, 0xda, 0x4d, 0x91, 0x87, 0x86, 0x77, 0x12, 0x33, 0xe8, 0x35, 0x3b, 0xc4, 0xf6, 0x23, 0x23, 0x18, 0x5c, ]); const Y: [[U32<LittleEndian>; 8]; 34] = [ bytes_to_words_8([ 0x95, 0xca, 0xe0, 0x5b, 0x89, 0x9e, 0x35, 0xdf, 0xfd, 0x71, 0x70, 0x54, 0x70, 0x62, 0x09, 0x98, 0x8e, 0xbf, 0xdf, 0x6e, 0x37, 0x96, 0x0b, 0xb5, 0xc3, 0x8d, 0x76, 0x57, 0xe8, 0xbf, 0xfe, 0xef, ]), bytes_to_words_8([ 0x9b, 0xc0, 0x42, 0xda, 0x4b, 0x45, 0x25, 0x65, 0x04, 0x85, 0xc6, 0x6d, 0x0c, 0xe1, 0x9b, 0x31, 0x75, 0x87, 0xc6, 0xba, 0x4b, 0xff, 0xcc, 0x42, 0x8e, 0x25, 0xd0, 0x89, 0x31, 0xe7, 0x2d, 0xfb, ]), bytes_to_words_8([ 0x6a, 0x12, 0x0c, 0x56, 0x12, 0x34, 0x42, 0x58, 0xb8, 0x5e, 0xfd, 0xb7, 0xdb, 0x1d, 0xb9, 0xe1, 0x86, 0x5a, 0x73, 0xca, 0xf9, 0x65, 0x57, 0xeb, 0x39, 0xed, 0x3e, 0x3f, 0x42, 0x69, 0x33, 0xac, ]), bytes_to_words_8([ 0x9e, 0xed, 0xdb, 0x03, 0xa1, 0xd2, 0x37, 0x4a, 0xf7, 0xbf, 0x77, 0x18, 0x55, 0x77, 0x45, 0x62, 0x37, 0xf9, 0xde, 0x2d, 0x60, 0x11, 0x3c, 0x23, 0xf8, 0x46, 0xdf, 0x26, 0xfa, 0x94, 0x20, 0x08, ]), bytes_to_words_8([ 0xa6, 0x98, 0x99, 0x4c, 0x08, 0x27, 0xd9, 0x0e, 0x86, 0xd4, 0x3e, 0x0d, 0xf7, 0xf4, 0xbf, 0xcd, 0xb0, 0x9b, 0x86, 0xa3, 0x73, 0xb9, 0x82, 0x88, 0xb7, 0x09, 0x4a, 0xd8, 0x1a, 0x01, 0x85, 0xac, ]), bytes_to_words_8([ 0x10, 0x0e, 0x4f, 0x2c, 0x5f, 0xc3, 0x8c, 0x00, 0x3c, 0x1a, 0xb6, 0xfe, 0xa4, 0x79, 0xeb, 0x2f, 0x5e, 0xbe, 0x48, 0xf5, 0x84, 0xd7, 0x15, 0x9b, 0x8a, 0xda, 0x03, 0x58, 0x6e, 0x65, 0xad, 0x9c, ]), bytes_to_words_8([ 0x96, 0x9f, 0x6a, 0xec, 0xbf, 0xe4, 0x4c, 0xf3, 0x56, 0x88, 0x8a, 0x7b, 0x15, 0xa3, 0xff, 0x07, 0x4f, 0x77, 0x17, 0x60, 0xb2, 0x6f, 0x9c, 0x04, 0x88, 0x4e, 0xe1, 0xfa, 0xa3, 0x29, 0xfb, 0xf4, ]), bytes_to_words_8([ 0xe6, 0x1a, 0xf2, 0x3a, 0xee, 0x7f, 0xa5, 0xd4, 0xd9, 0xa5, 0xdf, 0xcf, 0x43, 0xc4, 0xc2, 0x6c, 0xe8, 0xae, 0xa2, 0xce, 0x8a, 0x29, 0x90, 0xd7, 0xba, 0x7b, 0x57, 0x10, 0x8b, 0x47, 0xda, 0xbf, ]), bytes_to_words_8([ 0xbe, 0xad, 0xb2, 0xb2, 0x5b, 0x3c, 0xac, 0xc1, 0xac, 0x0c, 0xef, 0x34, 0x6c, 0xbb, 0x90, 0xfb, 0x04, 0x4b, 0xee, 0xe4, 0xfa, 0xc2, 0x60, 0x3a, 0x44, 0x2b, 0xdf, 0x7e, 0x50, 0x72, 0x43, 0xb7, ]), bytes_to_words_8([ 0x31, 0x9c, 0x99, 0x44, 0xb1, 0x58, 0x6e, 0x89, 0x9d, 0x43, 0x1c, 0x7f, 0x91, 0xbc, 0xcc, 0xc8, 0x69, 0x0d, 0xbf, 0x59, 0xb2, 0x83, 0x86, 0xb2, 0x31, 0x5f, 0x3d, 0x36, 0xef, 0x2e, 0xaa, 0x3c, ]), bytes_to_words_8([ 0xf3, 0x0b, 0x2b, 0x51, 0xf4, 0x8b, 0x71, 0xb0, 0x03, 0xdf, 0xb0, 0x82, 0x49, 0x48, 0x42, 0x01, 0x04, 0x3f, 0x65, 0xf5, 0xa3, 0xef, 0x6b, 0xbd, 0x61, 0xdd, 0xfe, 0xe8, 0x1a, 0xca, 0x9c, 0xe6, ]), bytes_to_words_8([ 0x00, 0x81, 0x26, 0x2a, 0x00, 0x00, 0x04, 0x80, 0xdc, 0xbc, 0x9a, 0x3d, 0xa6, 0xfb, 0xef, 0x5c, 0x1c, 0x0a, 0x55, 0xe4, 0x8a, 0x0e, 0x72, 0x9f, 0x91, 0x84, 0xfc, 0xb1, 0x40, 0x7c, 0x31, 0x52, ]), bytes_to_words_8([ 0x9d, 0xb2, 0x68, 0xf6, 0xfe, 0x50, 0x03, 0x2a, 0x36, 0x3c, 0x98, 0x01, 0x30, 0x68, 0x37, 0xfa, 0xfa, 0xbd, 0xf9, 0x57, 0xfd, 0x97, 0xea, 0xfc, 0x80, 0xdb, 0xd1, 0x65, 0xe4, 0x35, 0xd0, 0xe2, ]), bytes_to_words_8([ 0xdf, 0xd8, 0x36, 0xa2, 0x8b, 0x35, 0x40, 0x23, 0x92, 0x4b, 0x6f, 0xb7, 0xe4, 0x8b, 0xc0, 0xb3, 0xed, 0x95, 0xee, 0xa6, 0x4c, 0x2d, 0x40, 0x2f, 0x4d, 0x73, 0x4c, 0x8d, 0xc2, 0x6f, 0x3a, 0xc5, ]), bytes_to_words_8([ 0x91, 0x82, 0x5d, 0xae, 0xf0, 0x1e, 0xae, 0x3c, 0x38, 0xe3, 0x32, 0x8d, 0x00, 0xa7, 0x7d, 0xc6, 0x57, 0x03, 0x4f, 0x28, 0x7c, 0xcb, 0x0f, 0x0e, 0x1c, 0x9a, 0x7c, 0xbd, 0xc8, 0x28, 0xf6, 0x27, ]), bytes_to_words_8([ 0x20, 0x5e, 0x47, 0x37, 0xb8, 0x4b, 0x58, 0x37, 0x65, 0x51, 0xd4, 0x4c, 0x12, 0xc3, 0xc2, 0x15, 0xc8, 0x12, 0xa0, 0x97, 0x07, 0x89, 0xc8, 0x3d, 0xe5, 0x1d, 0x6a, 0xd7, 0x87, 0x27, 0x19, 0x63, ]), bytes_to_words_8([ 0x32, 0x7f, 0x0a, 0x5f, 0xbb, 0x6b, 0x59, 0x07, 0xde, 0xc0, 0x2c, 0x9a, 0x90, 0x93, 0x4a, 0xf5, 0xa1, 0xc6, 0x3b, 0x72, 0xc8, 0x26, 0x53, 0x60, 0x5d, 0x1d, 0xcc, 0xe5, 0x15, 0x96, 0xb3, 0xc2, ]), bytes_to_words_8([ 0xb4, 0x56, 0x96, 0x68, 0x9f, 0x2e, 0xb3, 0x82, 0x00, 0x74, 0x97, 0x55, 0x76, 0x92, 0xca, 0xac, 0x4d, 0x57, 0xb5, 0xde, 0x9f, 0x55, 0x69, 0xbc, 0x2a, 0xd0, 0x13, 0x7f, 0xd4, 0x7f, 0xb4, 0x7e, ]), bytes_to_words_8([ 0x66, 0x4f, 0xcb, 0x6d, 0xb4, 0x97, 0x1f, 0x5b, 0x3e, 0x07, 0xac, 0xed, 0xa9, 0xac, 0x13, 0x0e, 0x9f, 0x38, 0x18, 0x2d, 0xe9, 0x94, 0xcf, 0xf1, 0x92, 0xec, 0x0e, 0x82, 0xfd, 0x6d, 0x4c, 0xb7, ]), bytes_to_words_8([ 0xf3, 0xfe, 0x00, 0x81, 0x25, 0x89, 0xb7, 0xa7, 0xce, 0x51, 0x54, 0x40, 0x45, 0x64, 0x33, 0x01, 0x6b, 0x84, 0xa5, 0x9b, 0xec, 0x66, 0x19, 0xa1, 0xc6, 0xc0, 0xb3, 0x7d, 0xd1, 0x45, 0x0e, 0xd4, ]), bytes_to_words_8([ 0xf2, 0xd8, 0xb5, 0x84, 0x41, 0x0c, 0xed, 0xa8, 0x02, 0x5f, 0x5d, 0x2d, 0x8d, 0xd0, 0xd2, 0x17, 0x6f, 0xc1, 0xcf, 0x2c, 0xc0, 0x6f, 0xa8, 0xc8, 0x2b, 0xed, 0x4d, 0x94, 0x4e, 0x71, 0x33, 0x9e, ]), bytes_to_words_8([ 0xce, 0x78, 0x0f, 0xd0, 0x25, 0xbd, 0x41, 0xec, 0x34, 0xeb, 0xff, 0x9d, 0x42, 0x70, 0xa3, 0x22, 0x4e, 0x01, 0x9f, 0xcb, 0x44, 0x44, 0x74, 0xd4, 0x82, 0xfd, 0x2d, 0xbe, 0x75, 0xef, 0xb2, 0x03, ]), bytes_to_words_8([ 0x89, 0xcc, 0x10, 0xcd, 0x60, 0x0a, 0xbb, 0x54, 0xc4, 0x7e, 0xde, 0x93, 0xe0, 0x8c, 0x11, 0x4e, 0xdb, 0x04, 0x11, 0x7d, 0x71, 0x4d, 0xc1, 0xd5, 0x25, 0xe1, 0x1b, 0xed, 0x87, 0x56, 0x19, 0x2f, ]), bytes_to_words_8([ 0x92, 0x9d, 0x15, 0x46, 0x2b, 0x93, 0x9f, 0xf3, 0xf5, 0x2f, 0x22, 0x52, 0xda, 0x2e, 0xd6, 0x4d, 0x8f, 0xae, 0x88, 0x81, 0x8b, 0x1e, 0xfa, 0x2c, 0x7b, 0x08, 0xc8, 0x79, 0x4f, 0xb1, 0xb2, 0x14, ]), bytes_to_words_8([ 0xaa, 0x23, 0x3d, 0xb3, 0x16, 0x28, 0x33, 0x14, 0x1e, 0xa4, 0x38, 0x3f, 0x1a, 0x6f, 0x12, 0x0b, 0xe1, 0xdb, 0x82, 0xce, 0x36, 0x30, 0xb3, 0x42, 0x91, 0x14, 0x46, 0x31, 0x57, 0xa6, 0x4e, 0x91, ]), bytes_to_words_8([ 0x23, 0x4d, 0x47, 0x5e, 0x2f, 0x79, 0xcb, 0xf0, 0x5e, 0x4d, 0xb6, 0xa9, 0x40, 0x7d, 0x72, 0xc6, 0xbf, 0xf7, 0xd1, 0x19, 0x8b, 0x5c, 0x4d, 0x6a, 0xad, 0x28, 0x31, 0xdb, 0x61, 0x27, 0x49, 0x93, ]), bytes_to_words_8([ 0x71, 0x5a, 0x01, 0x82, 0xc7, 0xdc, 0x80, 0x89, 0xe3, 0x2c, 0x85, 0x31, 0xde, 0xed, 0x4f, 0x74, 0x31, 0xc0, 0x7c, 0x02, 0x19, 0x5e, 0xba, 0x2e, 0xf9, 0x1e, 0xfb, 0x56, 0x13, 0xc3, 0x7a, 0xf7, ]), bytes_to_words_8([ 0xae, 0x0c, 0x06, 0x6b, 0xab, 0xc6, 0x93, 0x69, 0x70, 0x0e, 0x1d, 0xd2, 0x6e, 0xdd, 0xc0, 0xd2, 0x16, 0xc7, 0x81, 0xd5, 0x6e, 0x4c, 0xe4, 0x7e, 0x33, 0x03, 0xfa, 0x73, 0x00, 0x7f, 0xf7, 0xb9, ]), bytes_to_words_8([ 0x49, 0xef, 0x23, 0xbe, 0x2a, 0xa4, 0xdb, 0xf2, 0x52, 0x06, 0xfe, 0x45, 0xc2, 0x0d, 0xd8, 0x88, 0x39, 0x5b, 0x25, 0x26, 0x39, 0x1a, 0x72, 0x49, 0x96, 0xa4, 0x41, 0x56, 0xbe, 0xac, 0x80, 0x82, ]), bytes_to_words_8([ 0x12, 0x85, 0x87, 0x92, 0xbf, 0x8e, 0x74, 0xcb, 0xa4, 0x9d, 0xee, 0x5e, 0x88, 0x12, 0xe0, 0x19, 0xda, 0x87, 0x45, 0x4b, 0xff, 0x9e, 0x84, 0x7e, 0xd8, 0x3d, 0xb0, 0x7a, 0xf3, 0x13, 0x74, 0x30, ]), bytes_to_words_8([ 0x82, 0xf8, 0x80, 0xa2, 0x78, 0xf6, 0x82, 0xc2, 0xbd, 0x0a, 0xd6, 0x88, 0x7c, 0xb5, 0x9f, 0x65, 0x2e, 0x15, 0x59, 0x87, 0xd6, 0x1b, 0xbf, 0x6a, 0x88, 0xd3, 0x6e, 0xe9, 0x3b, 0x60, 0x72, 0xe6, ]), bytes_to_words_8([ 0x65, 0x6d, 0x9c, 0xcb, 0xaa, 0xe3, 0xd6, 0x55, 0x85, 0x2e, 0x38, 0xde, 0xb3, 0xa2, 0xdc, 0xf8, 0x05, 0x8d, 0xc9, 0xfb, 0x6f, 0x2a, 0xb3, 0xd3, 0xb3, 0x53, 0x9e, 0xb7, 0x7b, 0x24, 0x8a, 0x66, ]), bytes_to_words_8([ 0x10, 0x91, 0xd0, 0x5e, 0xb6, 0xe2, 0xf2, 0x97, 0x77, 0x4f, 0xe6, 0x05, 0x35, 0x98, 0x45, 0x7c, 0xc6, 0x19, 0x08, 0x31, 0x8d, 0xe4, 0xb8, 0x26, 0xf0, 0xfc, 0x86, 0xd4, 0xbb, 0x11, 0x7d, 0x33, ]), bytes_to_words_8([ 0xe8, 0x65, 0xaa, 0x80, 0x50, 0x09, 0xcc, 0x29, 0x18, 0xd9, 0xc2, 0xf8, 0x40, 0xc4, 0xda, 0x43, 0xa7, 0x03, 0xad, 0x9f, 0x5b, 0x58, 0x06, 0x16, 0x3d, 0x71, 0x61, 0x69, 0x6b, 0x5a, 0x0a, 0xdc, ]), ]; const PATH: [[U32<LittleEndian>; 8]; 5] = [ bytes_to_words_8([ 0xd5, 0xc0, 0xd1, 0xbe, 0xbb, 0x06, 0x04, 0x8e, 0xd6, 0xfe, 0x2e, 0xf2, 0xc6, 0xce, 0xf3, 0x05, 0xb3, 0xed, 0x63, 0x39, 0x41, 0xeb, 0xc8, 0xb3, 0xbe, 0xc9, 0x73, 0x87, 0x54, 0xcd, 0xdd, 0x60, ]), bytes_to_words_8([ 0xe1, 0x92, 0x0a, 0xda, 0x52, 0xf4, 0x3d, 0x05, 0x5b, 0x50, 0x31, 0xce, 0xe6, 0x19, 0x25, 0x20, 0xd6, 0xa5, 0x11, 0x55, 0x14, 0x85, 0x1c, 0xe7, 0xfd, 0x44, 0x8d, 0x4a, 0x39, 0xfa, 0xe2, 0xab, ]), bytes_to_words_8([ 0x23, 0x35, 0xb5, 0x25, 0xf4, 0x84, 0xe9, 0xb4, 0x0d, 0x6a, 0x4a, 0x96, 0x93, 0x94, 0x84, 0x3b, 0xdc, 0xf6, 0xd1, 0x4c, 0x48, 0xe8, 0x01, 0x5e, 0x08, 0xab, 0x92, 0x66, 0x2c, 0x05, 0xc6, 0xe9, ]), bytes_to_words_8([ 0xf9, 0x0b, 0x65, 0xa7, 0xa6, 0x20, 0x16, 0x89, 0x99, 0x9f, 0x32, 0xbf, 0xd3, 0x68, 0xe5, 0xe3, 0xec, 0x9c, 0xb7, 0x0a, 0xc7, 0xb8, 0x39, 0x90, 0x03, 0xf1, 0x75, 0xc4, 0x08, 0x85, 0x08, 0x1a, ]), bytes_to_words_8([ 0x09, 0xab, 0x30, 0x34, 0x91, 0x1f, 0xe1, 0x25, 0x63, 0x10, 0x51, 0xdf, 0x04, 0x08, 0xb3, 0x94, 0x6b, 0x0b, 0xde, 0x79, 0x09, 0x11, 0xe8, 0x97, 0x8b, 0xa0, 0x7d, 0xd5, 0x6c, 0x73, 0xe7, 0xee, ]), ]; // final signature const Q: U32<BigEndian> = U32::from_bytes([0x00, 0x00, 0x00, 0x0a]); const FINAL_LMS_SIG: LmsSignature<8, 34, 5> = LmsSignature::<8, 34, 5> { q: Q, ots: LmotsSignature { ots_type: LmotsAlgorithmType::LmotsSha256N32W8, nonce: FINAL_C, y: Y, }, tree_type: LmsAlgorithmType::LmsSha256N32H5, tree_path: PATH, }; const LMS_PUBLIC_KEY: LmsPublicKey<8> = LmsPublicKey { id: LMS_IDENTIFIER, digest: LMS_PUBLIC_HASH, tree_type: LmsAlgorithmType::LmsSha256N32H5, otstype: LmotsAlgorithmType::LmotsSha256N32W8, }; let final_result = Lms::default() .verify_lms_signature_generic(&mut sha256, &MESSAGE, &LMS_PUBLIC_KEY, &FINAL_LMS_SIG) .unwrap(); assert_eq!(final_result, LmsResult::Success); let candidate_key = Lms::default() .verify_lms_signature_cfi_generic(&mut sha256, &MESSAGE, &LMS_PUBLIC_KEY, &FINAL_LMS_SIG) .unwrap(); assert_eq!(candidate_key, HashValue::from(LMS_PUBLIC_KEY.digest)); } // from https://www.rfc-editor.org/rfc/rfc8554#page-49 // this tests the upper part of that HSS tree fn test_hss_upper_32() { let mut sha256 = unsafe { Sha256::new(Sha256Reg::new()) }; const IDENTIFIER: [u8; 16] = [ 0x61, 0xa5, 0xd5, 0x7d, 0x37, 0xf5, 0xe4, 0x6b, 0xfb, 0x75, 0x20, 0x80, 0x6b, 0x07, 0xa1, 0xb8, ]; const HSS_PUBLIC_HASH: [U32<LittleEndian>; 8] = bytes_to_words_8([ 0x50, 0x65, 0x0e, 0x3b, 0x31, 0xfe, 0x4a, 0x77, 0x3e, 0xa2, 0x9a, 0x07, 0xf0, 0x9c, 0xf2, 0xea, 0x30, 0xe5, 0x79, 0xf0, 0xdf, 0x58, 0xef, 0x8e, 0x29, 0x8d, 0xa0, 0x43, 0x4c, 0xb2, 0xb8, 0x78, ]); // In HSS the upper level tree signs the concatenation of // lower_tree_lms_type, lower_tree_lmots_type, lower_tree_I, lower_tree_pubic_hash const PUBLIC_BUFFER: [u8; 56] = [ 0, 0, 0, 5, // lms_type 0, 0, 0, 4, //lmots_type 0xd2, 0xf1, 0x4f, 0xf6, 0x34, 0x6a, 0xf9, 0x64, 0x56, 0x9f, 0x7d, 0x6c, 0xb8, 0x80, 0xa1, 0xb6, // I, aka identifier //the hash 0x6c, 0x50, 0x04, 0x91, 0x7d, 0xa6, 0xea, 0xfe, 0x4d, 0x9e, 0xf6, 0xc6, 0x40, 0x7b, 0x3d, 0xb0, 0xe5, 0x48, 0x5b, 0x12, 0x2d, 0x9e, 0xbe, 0x15, 0xcd, 0xa9, 0x3c, 0xfe, 0xc5, 0x82, 0xd7, 0xab, ]; const Q: U32<BigEndian> = U32::from_bytes([0x00, 0x00, 0x00, 0x05]); const UPPER_NONCE: [U32<LittleEndian>; 8] = bytes_to_words_8([ 0xd3, 0x2b, 0x56, 0x67, 0x1d, 0x7e, 0xb9, 0x88, 0x33, 0xc4, 0x9b, 0x43, 0x3c, 0x27, 0x25, 0x86, 0xbc, 0x4a, 0x1c, 0x8a, 0x89, 0x70, 0x52, 0x8f, 0xfa, 0x04, 0xb9, 0x66, 0xf9, 0x42, 0x6e, 0xb9, ]); const Y: [[U32<LittleEndian>; 8]; 34] = [ bytes_to_words_8([ 0x96, 0x5a, 0x25, 0xbf, 0xd3, 0x7f, 0x19, 0x6b, 0x90, 0x73, 0xf3, 0xd4, 0xa2, 0x32, 0xfe, 0xb6, 0x91, 0x28, 0xec, 0x45, 0x14, 0x6f, 0x86, 0x29, 0x2f, 0x9d, 0xff, 0x96, 0x10, 0xa7, 0xbf, 0x95, ]), bytes_to_words_8([ 0xa6, 0x4c, 0x7f, 0x60, 0xf6, 0x26, 0x1a, 0x62, 0x04, 0x3f, 0x86, 0xc7, 0x03, 0x24, 0xb7, 0x70, 0x7f, 0x5b, 0x4a, 0x8a, 0x6e, 0x19, 0xc1, 0x14, 0xc7, 0xbe, 0x86, 0x6d, 0x48, 0x87, 0x78, 0xa0, ]), bytes_to_words_8([ 0xe0, 0x5f, 0xd5, 0xc6, 0x50, 0x9a, 0x6e, 0x61, 0xd5, 0x59, 0xcf, 0x1a, 0x77, 0xa9, 0x70, 0xde, 0x92, 0x7d, 0x60, 0xc7, 0x0d, 0x3d, 0xe3, 0x1a, 0x7f, 0xa0, 0x10, 0x09, 0x94, 0xe1, 0x62, 0xa2, ]), bytes_to_words_8([ 0x58, 0x2e, 0x8f, 0xf1, 0xb1, 0x0c, 0xd9, 0x9d, 0x4e, 0x8e, 0x41, 0x3e, 0xf4, 0x69, 0x55, 0x9f, 0x7d, 0x7e, 0xd1, 0x2c, 0x83, 0x83, 0x42, 0xf9, 0xb9, 0xc9, 0x6b, 0x83, 0xa4, 0x94, 0x3d, 0x16, ]), bytes_to_words_8([ 0x81, 0xd8, 0x4b, 0x15, 0x35, 0x7f, 0xf4, 0x8c, 0xa5, 0x79, 0xf1, 0x9f, 0x5e, 0x71, 0xf1, 0x84, 0x66, 0xf2, 0xbb, 0xef, 0x4b, 0xf6, 0x60, 0xc2, 0x51, 0x8e, 0xb2, 0x0d, 0xe2, 0xf6, 0x6e, 0x3b, ]), bytes_to_words_8([ 0x14, 0x78, 0x42, 0x69, 0xd7, 0xd8, 0x76, 0xf5, 0xd3, 0x5d, 0x3f, 0xbf, 0xc7, 0x03, 0x9a, 0x46, 0x2c, 0x71, 0x6b, 0xb9, 0xf6, 0x89, 0x1a, 0x7f, 0x41, 0xad, 0x13, 0x3e, 0x9e, 0x1f, 0x6d, 0x95, ]), bytes_to_words_8([ 0x60, 0xb9, 0x60, 0xe7, 0x77, 0x7c, 0x52, 0xf0, 0x60, 0x49, 0x2f, 0x2d, 0x7c, 0x66, 0x0e, 0x14, 0x71, 0xe0, 0x7e, 0x72, 0x65, 0x55, 0x62, 0x03, 0x5a, 0xbc, 0x9a, 0x70, 0x1b, 0x47, 0x3e, 0xcb, ]), bytes_to_words_8([ 0xc3, 0x94, 0x3c, 0x6b, 0x9c, 0x4f, 0x24, 0x05, 0xa3, 0xcb, 0x8b, 0xf8, 0xa6, 0x91, 0xca, 0x51, 0xd3, 0xf6, 0xad, 0x2f, 0x42, 0x8b, 0xab, 0x6f, 0x3a, 0x30, 0xf5, 0x5d, 0xd9, 0x62, 0x55, 0x63, ]), bytes_to_words_8([ 0xf0, 0xa7, 0x5e, 0xe3, 0x90, 0xe3, 0x85, 0xe3, 0xae, 0x0b, 0x90, 0x69, 0x61, 0xec, 0xf4, 0x1a, 0xe0, 0x73, 0xa0, 0x59, 0x0c, 0x2e, 0xb6, 0x20, 0x4f, 0x44, 0x83, 0x1c, 0x26, 0xdd, 0x76, 0x8c, ]), bytes_to_words_8([ 0x35, 0xb1, 0x67, 0xb2, 0x8c, 0xe8, 0xdc, 0x98, 0x8a, 0x37, 0x48, 0x25, 0x52, 0x30, 0xce, 0xf9, 0x9e, 0xbf, 0x14, 0xe7, 0x30, 0x63, 0x2f, 0x27, 0x41, 0x44, 0x89, 0x80, 0x8a, 0xfa, 0xb1, 0xd1, ]), bytes_to_words_8([ 0xe7, 0x83, 0xed, 0x04, 0x51, 0x6d, 0xe0, 0x12, 0x49, 0x86, 0x82, 0x21, 0x2b, 0x07,
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/axi_bypass.rs
drivers/test-fw/src/bin/axi_bypass.rs
/*++ Licensed under the Apache-2.0 license. File Name: axi_bypass.rs Abstract: File contains test cases for the AXI bypass recovery flow. Note: This test is triggered from `caliptra-mcu-sw`. --*/ #![no_std] #![no_main] use core::mem::ManuallyDrop; use caliptra_drivers::{AxiAddr, Dma, DmaRecovery, Mailbox, MailboxRecvTxn, SocIfc}; use caliptra_registers::{mbox::MboxCsr, soc_ifc::SocIfcReg}; use caliptra_test_harness::test_suite; use zerocopy::FromBytes; // The MCU test firmware will try to write a 16 KiB image. const EXPECTED_IMAGE_SIZE: u32 = 16 * 1024; test_suite! { test_axi_bypass, } fn test_axi_bypass() { let soc_ifc = SocIfc::new(unsafe { SocIfcReg::new() }); let dma = Dma::default(); let mut mbox = unsafe { Mailbox::new(MboxCsr::new()) }; let caliptra_base = AxiAddr::from(soc_ifc.caliptra_base_axi_addr()); let recovery_base = AxiAddr::from(soc_ifc.recovery_interface_base_addr()); let mci_base = AxiAddr::from(soc_ifc.mci_base_addr()); let dma_recovery = DmaRecovery::new(recovery_base, caliptra_base, mci_base, &dma); dma_recovery .set_device_status(DmaRecovery::DEVICE_STATUS_READY_TO_ACCEPT_RECOVERY_IMAGE_VALUE) .unwrap(); // Need to grab a lock of the Mailbox SRAM for the DMA engine. let txn: ManuallyDrop<MailboxRecvTxn<'_>> = ManuallyDrop::new(mbox.recovery_recv_txn()); let recovery_bytes = dma_recovery.download_image_to_mbox(0).unwrap(); assert_eq!(recovery_bytes, EXPECTED_IMAGE_SIZE); let mbox_contents = txn.raw_mailbox_contents(); let recovery_bytes = usize::try_from(recovery_bytes).unwrap(); for word in mbox_contents[..recovery_bytes].chunks(4) { let word = u32::read_from_bytes(word).unwrap(); assert_eq!(word, 0xFEEDCAFE); } dma_recovery .set_recovery_status(DmaRecovery::RECOVERY_STATUS_SUCCESSFUL, 0) .unwrap(); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/doe_tests.rs
drivers/test-fw/src/bin/doe_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: doe_tests.rs Abstract: File contains test cases for Deobfuscation Engine API --*/ #![no_std] #![no_main] use caliptra_drivers::{ Array4x12, Array4x4, DeobfuscationEngine, Ecc384, Ecc384PubKey, Hmac, HmacData, HmacKey, HmacMode, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, Mailbox, Trng, }; use caliptra_drivers_test_bin::{DoeTestResults, DOE_TEST_HMAC_KEY, DOE_TEST_IV}; use caliptra_cfi_lib::CfiCounter; use caliptra_registers::ecc::EccReg; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_registers::soc_ifc_trng::SocIfcTrngReg; use caliptra_registers::{ csrng::CsrngReg, doe::DoeReg, entropy_src::EntropySrcReg, hmac::HmacReg, mbox::MboxCsr, }; use caliptra_test_harness::test_suite; use zerocopy::IntoBytes; fn export_result_from_kv(ecc: &mut Ecc384, trng: &mut Trng, key_id: KeyId) -> Ecc384PubKey { ecc.key_pair( KeyReadArgs::new(key_id).into(), &Array4x12::default(), trng, KeyWriteArgs::new(KeyId::KeyId3, KeyUsage::default().set_ecc_private_key_en()).into(), ) .unwrap() } fn test_decrypt() { let mut test_results = DoeTestResults::default(); let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut hmac384 = Hmac::new(unsafe { HmacReg::new() }); let mut doe = unsafe { DeobfuscationEngine::new(DoeReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // Init CFI let mut entropy_gen = || trng.generate4(); CfiCounter::reset(&mut entropy_gen); assert_eq!( doe.decrypt_uds(&Array4x4::from(DOE_TEST_IV), KeyId::KeyId0) .ok(), Some(()) ); let key_out_id = KeyId::KeyId2; let key_out = KeyWriteArgs::new(key_out_id, KeyUsage::default().set_ecc_key_gen_seed_en()); // Make sure the UDS can be used as a HMAC key hmac384 .hmac( KeyReadArgs::new(KeyId::KeyId0).into(), HmacData::Slice("Hello world!".as_bytes()), &mut trng, key_out.into(), HmacMode::Hmac384, ) .unwrap(); test_results.hmac_uds_as_key_out_pub = export_result_from_kv(&mut ecc, &mut trng, key_out_id); // Make sure the UDS can be used as HMAC data hmac384 .hmac( HmacKey::Array4x12(&Array4x12::new(DOE_TEST_HMAC_KEY)), HmacData::Key(KeyReadArgs { id: KeyId::KeyId0 }), &mut trng, key_out.into(), HmacMode::Hmac384, ) .unwrap(); test_results.hmac_uds_as_data_out_pub = export_result_from_kv(&mut ecc, &mut trng, key_out_id); doe.decrypt_field_entropy(&Array4x4::from(DOE_TEST_IV), KeyId::KeyId1) .unwrap(); // Make sure the FE can be used as a HMAC key hmac384 .hmac( HmacKey::Key(KeyReadArgs { id: KeyId::KeyId1 }), HmacData::Slice("Hello world!".as_bytes()), &mut trng, key_out.into(), HmacMode::Hmac384, ) .unwrap(); test_results.hmac_field_entropy_as_key_out_pub = export_result_from_kv(&mut ecc, &mut trng, key_out_id); // Make sure the FE can be used as HMAC data hmac384 .hmac( HmacKey::Array4x12(&Array4x12::new(DOE_TEST_HMAC_KEY)), HmacData::Key(KeyReadArgs { id: KeyId::KeyId1 }), &mut trng, key_out.into(), HmacMode::Hmac384, ) .unwrap(); test_results.hmac_field_entropy_as_data_out_pub = export_result_from_kv(&mut ecc, &mut trng, key_out_id); let mut mbox = Mailbox::new(unsafe { MboxCsr::new() }); let mut txn = mbox.try_start_send_txn().unwrap(); txn.send_request(0, test_results.as_bytes()).unwrap(); while !txn.is_response_ready() {} } fn test_clear_secrets() { let mut doe = unsafe { DeobfuscationEngine::new(DoeReg::new()) }; doe.clear_secrets().unwrap(); } test_suite! { test_decrypt, test_clear_secrets, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/sha256_tests.rs
drivers/test-fw/src/bin/sha256_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha256_tests.rs Abstract: File contains test cases for SHA-256 API --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{Array4x8, Sha256, Sha256Alg, Sha256DigestOp}; use caliptra_kat::Sha256Kat; use caliptra_registers::sha256::Sha256Reg; use caliptra_test_harness::test_suite; fn test_digest0() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8, 0x99, 0x6F, 0xB9, 0x24, 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C, 0xA4, 0x95, 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55, ]; let data = []; let digest = sha.digest(&data).unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_digest1() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x1, 0xCF, 0xEA, 0x41, 0x41, 0x40, 0xDE, 0x5D, 0xAE, 0x22, 0x23, 0xB0, 0x3, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C, 0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x0, 0x15, 0xAD, ]; let data = "abc".as_bytes(); let digest = sha.digest(data).unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_digest2() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0x24, 0x8D, 0x6A, 0x61, 0xD2, 0x6, 0x38, 0xB8, 0xE5, 0xC0, 0x26, 0x93, 0xC, 0x3E, 0x60, 0x39, 0xA3, 0x3C, 0xE4, 0x59, 0x64, 0xFF, 0x21, 0x67, 0xF6, 0xEC, 0xED, 0xD4, 0x19, 0xDB, 0x6, 0xC1, ]; let data = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".as_bytes(); let digest = sha.digest(data).unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_digest3() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0xCF, 0x5B, 0x16, 0xA7, 0x78, 0xAF, 0x83, 0x80, 0x3, 0x6C, 0xE5, 0x9E, 0x7B, 0x4, 0x92, 0x37, 0xB, 0x24, 0x9B, 0x11, 0xE8, 0xF0, 0x7A, 0x51, 0xAF, 0xAC, 0x45, 0x3, 0x7A, 0xFE, 0xE9, 0xD1, ]; let data = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".as_bytes(); let digest = sha.digest(data).unwrap(); assert_eq!(digest, Array4x8::from(expected)); } fn test_op0() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8, 0x99, 0x6F, 0xB9, 0x24, 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C, 0xA4, 0x95, 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55, ]; let mut digest = Array4x8::default(); let digest_op = sha.digest_init().unwrap(); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x8::from(expected)); } fn test_op1() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, 0x1C, 0x14, 0x9A, 0xFB, 0xF4, 0xC8, 0x99, 0x6F, 0xB9, 0x24, 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C, 0xA4, 0x95, 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55, ]; let data = []; let mut digest = Array4x8::default(); let mut digest_op = sha.digest_init().unwrap(); assert!(digest_op.update(&data).is_ok()); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x8::from(expected)); } fn test_op2() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x1, 0xCF, 0xEA, 0x41, 0x41, 0x40, 0xDE, 0x5D, 0xAE, 0x22, 0x23, 0xB0, 0x3, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C, 0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x0, 0x15, 0xAD, ]; let data = "abc".as_bytes(); let mut digest = Array4x8::default(); let mut digest_op = sha.digest_init().unwrap(); assert!(digest_op.update(data).is_ok()); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x8::from(expected)); } fn test_op3() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0x24, 0x8D, 0x6A, 0x61, 0xD2, 0x6, 0x38, 0xB8, 0xE5, 0xC0, 0x26, 0x93, 0xC, 0x3E, 0x60, 0x39, 0xA3, 0x3C, 0xE4, 0x59, 0x64, 0xFF, 0x21, 0x67, 0xF6, 0xEC, 0xED, 0xD4, 0x19, 0xDB, 0x6, 0xC1, ]; let data = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".as_bytes(); let mut digest = Array4x8::default(); let mut digest_op = sha.digest_init().unwrap(); assert!(digest_op.update(data).is_ok()); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x8::from(expected)); } fn test_op4() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0xCF, 0x5B, 0x16, 0xA7, 0x78, 0xAF, 0x83, 0x80, 0x3, 0x6C, 0xE5, 0x9E, 0x7B, 0x4, 0x92, 0x37, 0xB, 0x24, 0x9B, 0x11, 0xE8, 0xF0, 0x7A, 0x51, 0xAF, 0xAC, 0x45, 0x3, 0x7A, 0xFE, 0xE9, 0xD1, ]; let data = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".as_bytes(); let mut digest = Array4x8::default(); let mut digest_op = sha.digest_init().unwrap(); assert!(digest_op.update(data).is_ok()); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x8::from(expected)); } fn test_op5() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0xCD, 0xC7, 0x6E, 0x5C, 0x99, 0x14, 0xFB, 0x92, 0x81, 0xA1, 0xC7, 0xE2, 0x84, 0xD7, 0x3E, 0x67, 0xF1, 0x80, 0x9A, 0x48, 0xA4, 0x97, 0x20, 0xE, 0x4, 0x6D, 0x39, 0xCC, 0xC7, 0x11, 0x2C, 0xD0, ]; const DATA: [u8; 1000] = [0x61; 1000]; let mut digest = Array4x8::default(); let mut digest_op = sha.digest_init().unwrap(); for _ in 0..1_000 { assert!(digest_op.update(&DATA).is_ok()); } let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x8::from(expected)); } fn test_op6() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0x06, 0xf9, 0xb1, 0xa7, 0xac, 0x97, 0xbc, 0x8e, 0x6a, 0x83, 0x5c, 0x08, 0x98, 0x6f, 0xe5, 0x38, 0xf0, 0x47, 0x8b, 0x03, 0x82, 0x6e, 0xfb, 0x4e, 0xed, 0x35, 0xdc, 0x51, 0x7b, 0x43, 0x3b, 0x8a, ]; let data = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz".as_bytes(); let mut digest = Array4x8::default(); let mut digest_op = sha.digest_init().unwrap(); for idx in 0..data.len() { assert!(digest_op.update(&data[idx..idx + 1]).is_ok()); } let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x8::from(expected)); } fn test_op7() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0x2f, 0xcd, 0x5a, 0x0d, 0x60, 0xe4, 0xc9, 0x41, 0x38, 0x1f, 0xcc, 0x4e, 0x00, 0xa4, 0xbf, 0x8b, 0xe4, 0x22, 0xc3, 0xdd, 0xfa, 0xfb, 0x93, 0xc8, 0x09, 0xe8, 0xd1, 0xe2, 0xbf, 0xff, 0xae, 0x8e, ]; let data = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl".as_bytes(); let mut digest = Array4x8::default(); let mut digest_op = sha.digest_init().unwrap(); for idx in 0..data.len() { assert!(digest_op.update(&data[idx..idx + 1]).is_ok()); } let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x8::from(expected)); } fn test_op8() { let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; let expected: [u8; 32] = [ 0x78, 0x4f, 0x62, 0x3b, 0x78, 0x74, 0x95, 0x07, 0x8e, 0x93, 0xff, 0x28, 0xa2, 0x5b, 0x58, 0x1d, 0xf0, 0x58, 0x40, 0x55, 0xa7, 0xe7, 0x1d, 0x8c, 0xd9, 0x0c, 0x45, 0x47, 0x16, 0xb9, 0x2f, 0x51, ]; let data = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd".as_bytes(); // Exact single block let mut digest = Array4x8::default(); let mut digest_op = sha.digest_init().unwrap(); for idx in 0..data.len() { assert!(digest_op.update(&data[idx..idx + 1]).is_ok()); } let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, Array4x8::from(expected)); } fn test_kat() { // Init CFI CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeed, 0xdeadbeef, 0xdeadbeef))); let mut sha = unsafe { Sha256::new(Sha256Reg::new()) }; assert_eq!(Sha256Kat::default().execute(&mut sha).is_ok(), true); } test_suite! { test_kat, test_digest0, test_digest1, test_digest2, test_digest3, test_op0, test_op1, test_op2, test_op3, test_op4, test_op5, test_op6, test_op7, test_op8, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/ecc384_sign_validation_failure_test.rs
drivers/test-fw/src/bin/ecc384_sign_validation_failure_test.rs
// Licensed under the Apache-2.0 license #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{Array4x12, Ecc384, Ecc384PrivKeyIn, Ecc384PubKey, Ecc384Scalar, Trng}; use caliptra_registers::csrng::CsrngReg; use caliptra_registers::ecc::EccReg; use caliptra_registers::entropy_src::EntropySrcReg; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_registers::soc_ifc_trng::SocIfcTrngReg; use caliptra_test_harness::test_suite; const PRIV_KEY: [u8; 48] = [ 0xfe, 0xee, 0xf5, 0x54, 0x4a, 0x76, 0x56, 0x49, 0x90, 0x12, 0x8a, 0xd1, 0x89, 0xe8, 0x73, 0xf2, 0x1f, 0xd, 0xfd, 0x5a, 0xd7, 0xe2, 0xfa, 0x86, 0x11, 0x27, 0xee, 0x6e, 0x39, 0x4c, 0xa7, 0x84, 0x87, 0x1c, 0x1a, 0xec, 0x3, 0x2c, 0x7a, 0x8b, 0x10, 0xb9, 0x3e, 0xe, 0xab, 0x89, 0x46, 0xd6, ]; fn test_sign_validation_failure() { let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let wrong_pub_key = Ecc384PubKey { x: Ecc384Scalar::from([ 0xD7, 0x9C, 0x6D, 0x97, 0x2B, 0x34, 0xA1, 0xDF, 0xC9, 0x16, 0xA7, 0xB6, 0xE0, 0xA9, 0x9B, 0x6B, 0x53, 0x87, 0xB3, 0x4D, 0xA2, 0x18, 0x76, 0x07, 0xC1, 0xAD, 0x0A, 0x4D, 0x1A, 0x8C, 0x2E, 0x41, 0x72, 0xAB, 0x5F, 0xA5, 0xD9, 0xAB, 0x58, 0xFE, 0x45, 0xE4, 0x3F, 0x56, 0xBB, 0xB6, 0x6B, 0xA4, ]), y: Ecc384Scalar::from([ 0x5A, 0x73, 0x63, 0x93, 0x2B, 0x06, 0xB4, 0xF2, 0x23, 0xBE, 0xF0, 0xB6, 0x0A, 0x63, 0x90, 0x26, 0x51, 0x12, 0xDB, 0xBD, 0x0A, 0xAE, 0x67, 0xFE, 0xF2, 0x6B, 0x46, 0x5B, 0xE9, 0x35, 0xB4, 0x8E, 0x45, 0x1E, 0x68, 0xD1, 0x6F, 0x11, 0x18, 0xF2, 0xB3, 0x2B, 0x4C, 0x28, 0x60, 0x87, 0x49, 0xED, ]), }; // Init CFI let mut entropy_gen = || trng.generate4(); CfiCounter::reset(&mut entropy_gen); let digest = Array4x12::new([0u32; 12]); // This line will jump to cfi_panic_handler let _ = ecc.sign( Ecc384PrivKeyIn::from(&Array4x12::from(PRIV_KEY)), &wrong_pub_key, &digest, &mut trng, ); } test_suite! { test_sign_validation_failure, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/hmac_tests.rs
drivers/test-fw/src/bin/hmac_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: hmac_tests.rs Abstract: File contains test cases for HMAC-384 and HMAC-512 API --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{ hmac_kdf, Array4x12, Array4x16, Ecc384, Ecc384PrivKeyOut, Ecc384Scalar, Ecc384Seed, Hmac, HmacMode, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, Trng, }; use caliptra_kat::{Hmac384KdfKat, Hmac512KdfKat}; use caliptra_registers::csrng::CsrngReg; use caliptra_registers::ecc::EccReg; use caliptra_registers::entropy_src::EntropySrcReg; use caliptra_registers::hmac::HmacReg; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_registers::soc_ifc_trng::SocIfcTrngReg; use caliptra_test_harness::test_suite; fn test_hmac0() { let mut hmac = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let key: [u8; 48] = [ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, ]; let data: [u8; 8] = [0x48, 0x69, 0x20, 0x54, 0x68, 0x65, 0x72, 0x65]; let result: [u8; 48] = [ 0xb6, 0xa8, 0xd5, 0x63, 0x6f, 0x5c, 0x6a, 0x72, 0x24, 0xf9, 0x97, 0x7d, 0xcf, 0x7e, 0xe6, 0xc7, 0xfb, 0x6d, 0x0c, 0x48, 0xcb, 0xde, 0xe9, 0x73, 0x7a, 0x95, 0x97, 0x96, 0x48, 0x9b, 0xdd, 0xbc, 0x4c, 0x5d, 0xf6, 0x1d, 0x5b, 0x32, 0x97, 0xb4, 0xfb, 0x68, 0xda, 0xb9, 0xf1, 0xb5, 0x82, 0xc2, ]; let mut out_tag = Array4x12::default(); let actual = hmac.hmac( (&Array4x12::from(key)).into(), (&data).into(), &mut trng, (&mut out_tag).into(), HmacMode::Hmac384, ); assert!(actual.is_ok()); assert_eq!(out_tag, Array4x12::from(result)); } fn test_hmac1() { let mut hmac384 = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let key: [u8; 48] = [ 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, ]; let data: [u8; 28] = [ 0x77, 0x68, 0x61, 0x74, 0x20, 0x64, 0x6f, 0x20, 0x79, 0x61, 0x20, 0x77, 0x61, 0x6e, 0x74, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x6e, 0x6f, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x3f, ]; let result: [u8; 48] = [ 0x2c, 0x73, 0x53, 0x97, 0x4f, 0x18, 0x42, 0xfd, 0x66, 0xd5, 0x3c, 0x45, 0x2c, 0xa4, 0x21, 0x22, 0xb2, 0x8c, 0x0b, 0x59, 0x4c, 0xfb, 0x18, 0x4d, 0xa8, 0x6a, 0x36, 0x8e, 0x9b, 0x8e, 0x16, 0xf5, 0x34, 0x95, 0x24, 0xca, 0x4e, 0x82, 0x40, 0x0c, 0xbd, 0xe0, 0x68, 0x6d, 0x40, 0x33, 0x71, 0xc9, ]; let mut out_tag = Array4x12::default(); let actual = hmac384.hmac( (&Array4x12::from(key)).into(), (&data).into(), &mut trng, (&mut out_tag).into(), HmacMode::Hmac384, ); assert!(actual.is_ok()); assert_eq!(out_tag, Array4x12::from(result)); } fn test_kv_hmac(seed: &[u8; 48], data: &[u8], out_pub_x: &[u8; 48], out_pub_y: &[u8; 48]) { let mut hmac384 = unsafe { Hmac::new(HmacReg::new()) }; let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // // Step 1: Place a key in the key-vault. // ecc.key_pair( Ecc384Seed::from(&Ecc384Scalar::from(seed)), &Array4x12::default(), &mut trng, KeyWriteArgs::new( KeyId::KeyId0, KeyUsage::default() .set_hmac_key_en() .set_ecc_private_key_en(), ) .into(), ) .unwrap(); // // Step 2: Hash the data with the key from key-vault. // hmac384 .hmac( KeyReadArgs::new(KeyId::KeyId0).into(), data.into(), &mut trng, KeyWriteArgs::new(KeyId::KeyId1, KeyUsage::default().set_ecc_key_gen_seed_en()).into(), HmacMode::Hmac384, ) .unwrap(); let pub_key = ecc .key_pair( KeyReadArgs::new(KeyId::KeyId1).into(), &Array4x12::default(), &mut trng, KeyWriteArgs::new(KeyId::KeyId2, KeyUsage::default().set_ecc_private_key_en()).into(), ) .unwrap(); assert_eq!(pub_key.x, Array4x12::from(out_pub_x)); assert_eq!(pub_key.y, Array4x12::from(out_pub_y)); } fn test_hmac2() { let seed = [ 0x58, 0x8d, 0xe9, 0x0e, 0x26, 0xd0, 0x46, 0x6d, 0x8d, 0xdb, 0xb5, 0xd7, 0x47, 0x20, 0x3c, 0x9b, 0x6f, 0xab, 0xaa, 0xcb, 0x1f, 0x3c, 0xeb, 0xbf, 0x8b, 0x1c, 0x0b, 0x98, 0x00, 0xbb, 0xf9, 0xbc, 0x01, 0x52, 0x06, 0x89, 0x37, 0xc9, 0x6f, 0x0b, 0x8b, 0x12, 0x46, 0x4b, 0x3c, 0x2c, 0xde, 0xea, ]; let data = [0x64, 0xab, 0x1f, 0x00, 0x23, 0x75, 0xdc, 0x00]; let out_pub_x = [ 0xde, 0x54, 0x96, 0xfe, 0x72, 0xb2, 0xa4, 0x75, 0x52, 0x06, 0x3f, 0x87, 0x4b, 0xd1, 0x0a, 0x57, 0x26, 0x98, 0x0d, 0xb9, 0x34, 0xaf, 0x36, 0x41, 0xc4, 0xb9, 0xe7, 0xa1, 0x8e, 0x45, 0x90, 0xd6, 0xce, 0xf6, 0x82, 0xdd, 0x93, 0xce, 0x6b, 0xf4, 0x09, 0xae, 0x39, 0x13, 0x90, 0x3e, 0xab, 0xeb, ]; let out_pub_y = [ 0x85, 0x95, 0xa2, 0xc0, 0x7c, 0x2e, 0x89, 0x33, 0x91, 0x4f, 0x52, 0xf8, 0x6d, 0xa3, 0x4c, 0xf1, 0x01, 0x33, 0x24, 0x0c, 0x50, 0x4e, 0xd2, 0x53, 0x53, 0x79, 0x29, 0x80, 0x06, 0x0a, 0x47, 0x90, 0x89, 0x11, 0x0c, 0xd2, 0xe8, 0x00, 0x30, 0x6e, 0x22, 0x98, 0x30, 0xbc, 0xa6, 0x76, 0xe8, 0xd5, ]; test_kv_hmac(&seed, &data, &out_pub_x, &out_pub_y); } fn test_hmac3() { let seed = [ 0x0e, 0xd2, 0xca, 0x91, 0x29, 0x1b, 0x3b, 0x8d, 0xa5, 0xab, 0xb4, 0x77, 0x15, 0x75, 0x1a, 0xca, 0xe0, 0x85, 0x7e, 0x56, 0x88, 0xd4, 0x8c, 0xcb, 0xc9, 0xad, 0x50, 0xf8, 0xa1, 0x3e, 0xdf, 0x3c, 0x1a, 0x47, 0x01, 0xf7, 0x90, 0x05, 0xa5, 0x65, 0x52, 0x37, 0xf5, 0x92, 0x79, 0x95, 0x68, 0x22, ]; let data = [ 0x01, 0x7a, 0x3a, 0x10, 0xf8, 0x1f, 0xd4, 0x2a, 0xc7, 0xb6, 0x4c, 0x7c, 0xab, 0x37, 0x4e, 0xed, 0xde, 0xcc, 0x3f, 0xff, 0x9a, 0x62, 0x58, 0xbd, 0x98, 0x17, 0x37, 0x14, ]; let out_pub_x = [ 0xe3, 0x86, 0xfb, 0x91, 0xd8, 0xc9, 0x3e, 0x23, 0x44, 0xe2, 0xfd, 0x21, 0x11, 0x6e, 0x74, 0x89, 0xf6, 0x32, 0xde, 0x8d, 0xa9, 0x47, 0xb3, 0x04, 0x6e, 0xb5, 0x59, 0xf4, 0x2a, 0x96, 0xd9, 0x3a, 0x77, 0x41, 0x4c, 0xed, 0x0b, 0x9c, 0x97, 0xf8, 0xa6, 0xc0, 0x3e, 0x3e, 0x3b, 0xac, 0x47, 0x9b, ]; let out_pub_y = [ 0xa3, 0xd2, 0x8b, 0x8d, 0xae, 0x31, 0x3a, 0xe3, 0x76, 0x03, 0xab, 0xa1, 0x88, 0xd7, 0x70, 0xfb, 0xce, 0x75, 0x6a, 0xeb, 0x40, 0x1e, 0xbb, 0x01, 0x1b, 0x88, 0xa3, 0xf2, 0x91, 0x1d, 0x11, 0xda, 0x57, 0xba, 0x09, 0xe2, 0xf6, 0x1f, 0xc5, 0xec, 0xed, 0x14, 0xf8, 0xf5, 0x12, 0x53, 0x8b, 0x25, ]; test_kv_hmac(&seed, &data, &out_pub_x, &out_pub_y); } fn test_hmac4() { let seed = [ 0x32, 0x36, 0xcf, 0xba, 0x5d, 0xf3, 0x86, 0x39, 0x3e, 0x41, 0x13, 0x2b, 0x2d, 0x70, 0x6c, 0x00, 0x66, 0xe9, 0x2a, 0xa7, 0xb6, 0xe7, 0x09, 0x35, 0x16, 0xb6, 0xeb, 0x5f, 0x0b, 0x1e, 0x09, 0x3d, 0x7c, 0x9f, 0xa8, 0x1a, 0x0e, 0x61, 0x23, 0xac, 0x09, 0x0a, 0x40, 0xa4, 0x42, 0xf9, 0x3f, 0xaa, ]; let data = [ 0x35, 0xc8, 0x57, 0xb5, 0x0f, 0x0f, 0xb2, 0x1a, 0x39, 0xab, 0xc8, 0xa3, 0xe7, 0xed, 0xf7, 0xe0, 0x4f, 0x16, 0xa4, 0xd5, 0xe6, 0x86, 0xe3, 0xf2, 0x1f, 0x38, 0xf5, 0x6e, 0xbd, 0x88, 0x74, 0x3f, 0x0f, 0xfb, 0x27, 0x29, 0x60, 0x3f, 0x84, 0x07, 0x5e, 0x5e, 0xc4, 0x57, 0x79, 0xce, 0xfa, 0x30, ]; let out_pub_x = [ 0x21, 0x00, 0xca, 0xc8, 0x6d, 0xa4, 0x88, 0xa0, 0x39, 0xbd, 0x91, 0x52, 0x6e, 0xc0, 0x46, 0x47, 0x9b, 0x46, 0x6b, 0x99, 0x2a, 0x31, 0x7d, 0xba, 0xea, 0xd6, 0x6d, 0xc9, 0x1e, 0x20, 0xa1, 0x8e, 0xa6, 0x6d, 0x60, 0xc4, 0xf8, 0xd0, 0xd7, 0x8f, 0x85, 0x10, 0x35, 0x12, 0x38, 0x90, 0xb4, 0x7d, ]; let out_pub_y = [ 0x54, 0xc3, 0xa0, 0x20, 0xc6, 0x9b, 0xe9, 0x21, 0xc1, 0x8d, 0xb1, 0x19, 0xac, 0xa9, 0xdd, 0x10, 0x28, 0xa9, 0x4f, 0x93, 0x1b, 0x77, 0xea, 0xaa, 0x0c, 0x5e, 0x38, 0x08, 0x71, 0xfa, 0x4b, 0xd7, 0x0b, 0x10, 0x5f, 0xf1, 0x23, 0x86, 0xef, 0x5f, 0x6d, 0xa2, 0xc5, 0x72, 0x44, 0xd5, 0x7e, 0xbf, ]; test_kv_hmac(&seed, &data, &out_pub_x, &out_pub_y); } fn test_hmac_kv_multiblock() { let seed = [ 0x32, 0x36, 0xcf, 0xba, 0x5d, 0xf3, 0x86, 0x39, 0x3e, 0x41, 0x13, 0x2b, 0x2d, 0x70, 0x6c, 0x00, 0x66, 0xe9, 0x2a, 0xa7, 0xb6, 0xe7, 0x09, 0x35, 0x16, 0xb6, 0xeb, 0x5f, 0x0b, 0x1e, 0x09, 0x3d, 0x7c, 0x9f, 0xa8, 0x1a, 0x0e, 0x61, 0x23, 0xac, 0x09, 0x0a, 0x40, 0xa4, 0x42, 0xf9, 0x3f, 0xaa, ]; let data: [u8; 256] = [ 0x35, 0xc8, 0x57, 0xb5, 0x0f, 0x0f, 0xb2, 0x1a, 0x39, 0xab, 0xc8, 0xa3, 0xe7, 0xed, 0xf7, 0xe0, 0x4f, 0x16, 0xa4, 0xd5, 0xe6, 0x86, 0xe3, 0xf2, 0x1f, 0x38, 0xf5, 0x6e, 0xbd, 0x88, 0x74, 0x3f, 0x0f, 0xfb, 0x27, 0x29, 0x60, 0x3f, 0x84, 0x07, 0x5e, 0x5e, 0xc4, 0x57, 0x79, 0xce, 0xfa, 0x30, 0x5b, 0xb2, 0xed, 0xdd, 0xd7, 0xe2, 0xd2, 0xb3, 0xa6, 0x7a, 0xd9, 0x1e, 0x5d, 0x86, 0xa1, 0x96, 0x67, 0x2a, 0x47, 0x48, 0x4e, 0x72, 0xd6, 0xec, 0xde, 0x96, 0xbe, 0x5f, 0x9f, 0x09, 0x71, 0xbf, 0xe3, 0xc9, 0x06, 0x59, 0x1a, 0x3b, 0x2e, 0x3b, 0xe8, 0x97, 0x56, 0x27, 0x13, 0x5e, 0xf7, 0xf3, 0x7c, 0xde, 0xe0, 0x94, 0xdd, 0xf3, 0x3d, 0xa0, 0x7f, 0xf5, 0x77, 0x47, 0xca, 0x32, 0xbc, 0xb3, 0x0d, 0x6a, 0x40, 0xeb, 0xeb, 0x07, 0x86, 0x01, 0x27, 0x82, 0x55, 0x6b, 0x8e, 0x0a, 0x48, 0x34, 0x9b, 0x72, 0x91, 0x10, 0x55, 0xeb, 0x2b, 0x0d, 0x53, 0x2d, 0xe2, 0x6b, 0x62, 0xa4, 0x06, 0xfd, 0x03, 0x9b, 0xfd, 0x74, 0x9d, 0xd3, 0x59, 0x3d, 0x66, 0xd6, 0xfb, 0x09, 0x83, 0x63, 0x7d, 0xbf, 0x34, 0x40, 0x40, 0x5b, 0xf7, 0xf8, 0xb0, 0xd3, 0xe8, 0x72, 0x7c, 0x4c, 0xc8, 0xd2, 0x01, 0x8a, 0xf4, 0xc3, 0xf0, 0xff, 0x12, 0x21, 0x17, 0xfb, 0x6a, 0x44, 0x00, 0x52, 0xc2, 0x0c, 0x6a, 0x9b, 0x93, 0x21, 0xd1, 0x65, 0x22, 0x8d, 0xae, 0x70, 0xbf, 0x90, 0xdb, 0xe4, 0x8a, 0x1a, 0xb9, 0x79, 0x48, 0x7a, 0x35, 0x6d, 0x96, 0x29, 0x22, 0x82, 0xd1, 0xfb, 0x06, 0x42, 0x09, 0xbc, 0xe5, 0xd0, 0x1c, 0xec, 0xf5, 0xc1, 0x74, 0x13, 0x4d, 0x89, 0x4a, 0xae, 0xdb, 0xfb, 0xe6, 0xe0, 0x21, 0x89, 0x32, 0xad, 0xa2, 0x0e, 0xcb, 0xc0, 0x96, 0xc7, 0x01, 0xc5, 0xf8, 0x3b, 0xee, 0xf8, 0x4c, 0x6a, ]; let out_pub_x = [ 0x75, 0x08, 0xb8, 0xfe, 0x7f, 0x1e, 0x44, 0x19, 0x1b, 0x12, 0x4e, 0xd6, 0x11, 0x7b, 0x1d, 0x0b, 0xce, 0x6d, 0xdc, 0x87, 0xf7, 0x1c, 0x0b, 0xb5, 0x5d, 0x88, 0xb7, 0x1a, 0x48, 0x8d, 0x1b, 0x19, 0x08, 0x3b, 0x30, 0xbf, 0x42, 0x29, 0x2b, 0x8d, 0xf5, 0xdc, 0xd8, 0x0b, 0x89, 0xc8, 0x23, 0x6d, ]; let out_pub_y = [ 0xab, 0x30, 0x6a, 0x98, 0xa3, 0x75, 0x2d, 0xaa, 0xd2, 0xfd, 0x72, 0xa9, 0x96, 0x85, 0xf4, 0xcf, 0xe9, 0x8c, 0xbf, 0x0d, 0x94, 0xab, 0x8d, 0x66, 0x86, 0x5e, 0xba, 0x54, 0x56, 0xba, 0x19, 0x07, 0x4f, 0xd7, 0xfe, 0x3d, 0xc0, 0xa5, 0x56, 0x77, 0xdf, 0x78, 0xab, 0x89, 0x6a, 0x02, 0x43, 0xb9, ]; test_kv_hmac(&seed, &data, &out_pub_x, &out_pub_y); } /// /// Step 1: /// Key From Key Vault /// Generate the output tag in the buffer. /// Generate the HMAC of the output tag in the buffer - step_1 Tag /// /// /// Step 2: /// Key From Key Vault /// Generate the output tag that goes in the KV /// Generate the HMAC of the tag in KV and the tag goes in specified buffer /// /// fn test_hmac5() { let mut hmac384 = unsafe { Hmac::new(HmacReg::new()) }; let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // // Step 1: Place a key in the key-vault. // // Key is [ 0xfe, 0xee, 0xf5, 0x54, 0x4a, 0x76, 0x56, 0x49, 0x90, 0x12, 0x8a, 0xd1, 0x89, 0xe8, 0x73, 0xf2, // 0x1f, 0xd, 0xfd, 0x5a, 0xd7, 0xe2, 0xfa, 0x86, 0x11, 0x27, 0xee, 0x6e, 0x39, 0x4c, 0xa7, 0x84, // 0x87, 0x1c, 0x1a, 0xec, 0x3, 0x2c, 0x7a, 0x8b, 0x10, 0xb9, 0x3e, 0xe, 0xab, 0x89, 0x46, 0xd6,]; // let seed = [0u8; 48]; let key_out_1 = KeyWriteArgs { id: KeyId::KeyId0, usage: KeyUsage::default() .set_hmac_key_en() .set_ecc_private_key_en(), }; let result = ecc.key_pair( Ecc384Seed::from(&Ecc384Scalar::from(seed)), &Array4x12::default(), &mut trng, Ecc384PrivKeyOut::from(key_out_1), ); assert!(result.is_ok()); // Key vault key to be used for all the operations. This is a constant let key = KeyReadArgs::new(KeyId::KeyId0); let data: [u8; 28] = [ 0x77, 0x68, 0x61, 0x74, 0x20, 0x64, 0x6f, 0x20, 0x79, 0x61, 0x20, 0x77, 0x61, 0x6e, 0x74, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x6e, 0x6f, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x3f, ]; // The hardware no longer reveals HMAC results to the CPU that use data from // the key-vault, returning all zeroes instead let result = [0u8; 48]; // Take the Data Generate the Tag in buffer let mut out_tag = Array4x12::default(); let actual = hmac384.hmac( key.into(), (&data).into(), &mut trng, (&mut out_tag).into(), HmacMode::Hmac384, ); assert!(actual.is_ok()); assert_eq!(out_tag, Array4x12::from(result)); let step_1_result_expected: [u8; 48] = [0u8; 48]; // Generate the HMAC of the Tag in to a hmac_step_1 let mut hmac_step_1 = Array4x12::default(); let actual = hmac384.hmac( key.into(), (&result).into(), &mut trng, (&mut hmac_step_1).into(), HmacMode::Hmac384, ); assert!(actual.is_ok()); assert_eq!(hmac_step_1, Array4x12::from(step_1_result_expected)); // Generate the Tag Of Original Data and put the tag In KV @5. KV @5 will be used as data in the next step let out_tag = KeyWriteArgs::new(KeyId::KeyId5, KeyUsage::default().set_hmac_data_en()); let actual = hmac384.hmac( key.into(), (&data).into(), &mut trng, out_tag.into(), HmacMode::Hmac384, ); assert!(actual.is_ok()); // Data From Key Vault generate HMAC in to output buffer let mut hmac_step_2 = Array4x12::default(); let data_input: KeyReadArgs = KeyReadArgs::new(KeyId::KeyId5); let actual = hmac384.hmac( key.into(), data_input.into(), &mut trng, (&mut hmac_step_2).into(), HmacMode::Hmac384, ); assert!(actual.is_ok()); assert_eq!(hmac_step_1, hmac_step_2); } fn test_kdf_hmac384( key_0: &[u8; 48], msg_0: &[u8], label: &[u8], context: Option<&[u8]>, out_pub_x: &[u8; 48], out_pub_y: &[u8; 48], ) { let mut hmac384 = unsafe { Hmac::new(HmacReg::new()) }; let mut ecc = unsafe { Ecc384::new(EccReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let key_0 = Array4x12::from(key_0); let kdf_key_out = KeyWriteArgs::new( KeyId::KeyId0, KeyUsage::default().set_hmac_key_en().set_hmac_data_en(), ); let kdf_key_in = KeyReadArgs::new(KeyId::KeyId0); hmac384 .hmac( (&key_0).into(), msg_0.into(), &mut trng, kdf_key_out.into(), HmacMode::Hmac384, ) .unwrap(); let kdf_out = KeyWriteArgs::new(KeyId::KeyId1, KeyUsage::default().set_ecc_key_gen_seed_en()); hmac_kdf( &mut hmac384, kdf_key_in.into(), label, context, &mut trng, kdf_out.into(), HmacMode::Hmac384, ) .unwrap(); let ecc_out = KeyWriteArgs::new(KeyId::KeyId2, KeyUsage::default().set_ecc_private_key_en()); let pub_key = ecc .key_pair( KeyReadArgs::new(KeyId::KeyId1).into(), &Array4x12::default(), &mut trng, Ecc384PrivKeyOut::from(ecc_out), ) .unwrap(); assert_eq!(pub_key.x, Array4x12::from(out_pub_x)); assert_eq!(pub_key.y, Array4x12::from(out_pub_y)); } // context_len = 48 fn test_kdf0_hmac384() { let key_0 = [ 0x9e, 0x2c, 0xce, 0xc7, 0x00, 0x16, 0x1e, 0x42, 0xff, 0x0e, 0x13, 0x8c, 0x48, 0x89, 0xe4, 0xd6, 0xa0, 0x88, 0x8d, 0x13, 0x1d, 0x58, 0xcb, 0x44, 0xf5, 0xe2, 0x92, 0x47, 0x59, 0x64, 0xac, 0x6a, 0x8c, 0x63, 0xff, 0x7c, 0x0c, 0x95, 0xe7, 0xda, 0x0b, 0x4e, 0x17, 0xdf, 0x67, 0xa5, 0x5c, 0xb6, ]; let msg_0 = [ 0x2c, 0x60, 0xda, 0x7c, 0xd6, 0xfc, 0x88, 0x99, 0x58, 0x3e, 0xf7, 0xa8, 0x10, 0xe7, 0x4b, 0xb1, 0x37, 0x7b, 0xaa, 0x72, 0x66, 0x38, 0xb4, 0x15, 0x7c, 0x72, 0x41, 0x61, 0x06, 0x93, 0xcb, 0xc9, 0xb1, 0x78, 0xa7, 0x85, 0x61, 0xeb, 0xa7, 0x5d, 0x0e, 0x65, 0x99, 0x10, 0x49, 0xd9, 0x57, 0x93, ]; let label = [0x2d, 0xd2, 0x38, 0x86]; let context = [ 0x9a, 0x81, 0x9e, 0xf0, 0xc9, 0x67, 0xb2, 0x13, 0x88, 0x41, 0x72, 0x1e, 0xd9, 0xde, 0x2f, 0xd4, 0x1c, 0xb9, 0xa7, 0x7e, 0x78, 0x4e, 0x38, 0x5b, 0x90, 0x36, 0x26, 0x2a, 0xe2, 0x81, 0xf6, 0x21, 0x93, 0x55, 0x85, 0xf6, 0xf7, 0x59, 0xeb, 0x16, 0xcc, 0xed, 0x7f, 0x65, 0x13, 0x04, 0xd7, 0x9d, ]; let out_pub_x = [ 0x67, 0x3e, 0x4d, 0x0d, 0x4a, 0x7b, 0x15, 0x17, 0x8a, 0x87, 0x5a, 0x28, 0x3a, 0xa4, 0x98, 0x80, 0x84, 0x99, 0xf6, 0x91, 0x76, 0xde, 0xaa, 0x52, 0x9f, 0x44, 0xb2, 0xdb, 0x6c, 0x2c, 0xac, 0xd3, 0x68, 0xe6, 0x8f, 0xdc, 0xdc, 0x7a, 0xfd, 0xef, 0x3f, 0x7f, 0x96, 0xef, 0x95, 0x0e, 0x08, 0x0a, ]; let out_pub_y = [ 0x34, 0x28, 0x5e, 0x58, 0xb9, 0x4a, 0x3a, 0xcc, 0x1c, 0x4b, 0xb3, 0x8f, 0xca, 0xf4, 0xf9, 0xc5, 0x91, 0x7c, 0xd7, 0x41, 0xd7, 0x0f, 0x72, 0xae, 0x29, 0x3d, 0xf7, 0x81, 0x76, 0xb4, 0x6f, 0xfd, 0xc3, 0xf8, 0xf1, 0x99, 0xd6, 0x97, 0x6a, 0x58, 0x63, 0x80, 0xcc, 0x80, 0x76, 0xcb, 0x13, 0x18, ]; test_kdf_hmac384( &key_0, &msg_0, &label, Some(&context), &out_pub_x, &out_pub_y, ); } // context_len = 0 fn test_kdf1_hmac384() { let key_0 = [ 0xd3, 0x45, 0xe5, 0x14, 0x19, 0xda, 0xc6, 0x9c, 0x70, 0xc8, 0x22, 0x71, 0xe9, 0x12, 0x28, 0x58, 0x65, 0x64, 0x16, 0xc9, 0x92, 0xf3, 0xda, 0x58, 0x5a, 0xca, 0x96, 0xe5, 0x99, 0x29, 0x30, 0x53, 0xc0, 0xba, 0x0b, 0x5d, 0xe8, 0x52, 0xa8, 0x32, 0xd9, 0xb5, 0xe9, 0x4a, 0xf3, 0xbd, 0x38, 0x1b, ]; let msg_0 = [ 0x46, 0x4c, 0x40, 0xe2, 0xab, 0x31, 0x06, 0x5c, 0x7b, 0x88, 0x0b, 0x6b, 0x32, 0x5d, 0x86, 0xe4, 0xea, 0x5c, 0x98, 0x08, 0x16, 0xf4, 0x6a, 0x47, 0x60, 0x49, 0x19, 0x5a, 0xa8, 0x65, 0xa2, 0x5c, 0xc7, 0x89, 0x5f, 0x1a, 0xbd, 0x03, 0x06, 0x9c, 0x16, 0x89, 0xaf, 0x1c, 0xfa, 0x23, 0x27, 0xa0, ]; let label = [0xef, 0xe5, 0x19, 0x77]; let out_pub_x = [ 0x95, 0x58, 0xd3, 0xa7, 0xec, 0x5d, 0xe3, 0xf9, 0xb9, 0x22, 0xe5, 0xe5, 0x2e, 0x19, 0x87, 0x80, 0x74, 0x9f, 0x29, 0x87, 0x7c, 0xb0, 0x0a, 0x2b, 0xcf, 0x27, 0x89, 0x9c, 0x7d, 0x05, 0xfd, 0xe3, 0xa8, 0xf2, 0x3a, 0xde, 0x40, 0x35, 0x10, 0x4e, 0xfb, 0x5c, 0xf8, 0xe3, 0xf3, 0xac, 0x54, 0xca, ]; let out_pub_y = [ 0x45, 0x26, 0x18, 0xc9, 0xe7, 0xe1, 0x6d, 0x42, 0xa4, 0x94, 0x3a, 0x5e, 0xc4, 0xfe, 0x79, 0xb0, 0x29, 0x48, 0x92, 0x95, 0xf4, 0x2e, 0x60, 0xec, 0x3f, 0x64, 0xc6, 0xf3, 0x8b, 0xa7, 0x68, 0xf5, 0x2e, 0xf0, 0x64, 0x93, 0xb6, 0x73, 0x42, 0x82, 0x0e, 0x37, 0xf8, 0x46, 0x9a, 0x9a, 0xa4, 0x19, ]; test_kdf_hmac384(&key_0, &msg_0, &label, None, &out_pub_x, &out_pub_y); } // Test using a NIST vector. fn test_kdf2_hmac384() { let mut hmac384 = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let key = [ 0xb5, 0x7d, 0xc5, 0x23, 0x54, 0xaf, 0xee, 0x11, 0xed, 0xb4, 0xc9, 0x05, 0x2a, 0x52, 0x83, 0x44, 0x34, 0x8b, 0x2c, 0x6b, 0x6c, 0x39, 0xf3, 0x21, 0x33, 0xed, 0x3b, 0xb7, 0x20, 0x35, 0xa4, 0xab, 0x55, 0xd6, 0x64, 0x8c, 0x15, 0x29, 0xef, 0x7a, 0x91, 0x70, 0xfe, 0xc9, 0xef, 0x26, 0xa8, 0x1e, ]; let label = [ 0x17, 0xe6, 0x41, 0x90, 0x9d, 0xed, 0xfe, 0xe4, 0x96, 0x8b, 0xb9, 0x5d, 0x7f, 0x77, 0x0e, 0x45, 0x57, 0xca, 0x34, 0x7a, 0x46, 0x61, 0x4c, 0xb3, 0x71, 0x42, 0x3f, 0x0d, 0x91, 0xdf, 0x3b, 0x58, 0xb5, 0x36, 0xed, 0x54, 0x53, 0x1f, 0xd2, 0xa2, 0xeb, 0x0b, 0x8b, 0x2a, 0x16, 0x34, 0xc2, 0x3c, 0x88, 0xfa, 0xd9, 0x70, 0x6c, 0x45, 0xdb, 0x44, 0x11, 0xa2, 0x3b, 0x89, ]; let out = [ 0x59, 0x49, 0xac, 0xf9, 0x63, 0x5a, 0x77, 0x29, 0x79, 0x28, 0xc1, 0xe1, 0x55, 0xd4, 0x3a, 0x4e, 0x4b, 0xca, 0x61, 0xb1, 0x36, 0x9a, 0x5e, 0xf5, 0x05, 0x30, 0x88, 0x85, 0x50, 0xba, 0x27, 0x0e, 0x26, 0xbe, 0x4a, 0x42, 0x1c, 0xdf, 0x80, 0xb7, ]; let mut out_buf = Array4x12::default(); hmac_kdf( &mut hmac384, (&Array4x12::from(&key)).into(), &label, None, &mut trng, (&mut out_buf).into(), HmacMode::Hmac384, ) .unwrap(); assert_eq!(<[u8; 48]>::from(out_buf)[..out.len()], out); } fn test_hmac_multi_block() { let mut hmac384 = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let key: [u8; 48] = [ 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, ]; let data: [u8; 130] = [ 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, ]; let result: [u8; 48] = [ 0x70, 0xF1, 0xF6, 0x3C, 0x8C, 0x0A, 0x0D, 0xFE, 0x09, 0x65, 0xE7, 0x3D, 0x79, 0x62, 0x93, 0xFD, 0x6E, 0xCD, 0x56, 0x43, 0xB4, 0x20, 0x15, 0x46, 0x58, 0x7E, 0xBD, 0x46, 0xCD, 0x07, 0xE3, 0xEA, 0xE2, 0x51, 0x4A, 0x61, 0xC1, 0x61, 0x44, 0x24, 0xE7, 0x71, 0xCC, 0x4B, 0x7C, 0xCA, 0xC8, 0xC3, ]; let mut out_tag = Array4x12::default(); let actual = hmac384.hmac( (&Array4x12::from(key)).into(), (&data).into(), &mut trng, (&mut out_tag).into(), HmacMode::Hmac384, ); assert!(actual.is_ok()); assert_eq!(out_tag, Array4x12::from(result)); } fn test_hmac_exact_single_block() { let mut hmac384 = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let key: [u8; 48] = [ 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, ]; let data: [u8; 130] = [ 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, ]; let result: [u8; 48] = [ 0x70, 0xF1, 0xF6, 0x3C, 0x8C, 0x0A, 0x0D, 0xFE, 0x09, 0x65, 0xE7, 0x3D, 0x79, 0x62, 0x93, 0xFD, 0x6E, 0xCD, 0x56, 0x43, 0xB4, 0x20, 0x15, 0x46, 0x58, 0x7E, 0xBD, 0x46, 0xCD, 0x07, 0xE3, 0xEA, 0xE2, 0x51, 0x4A, 0x61, 0xC1, 0x61, 0x44, 0x24, 0xE7, 0x71, 0xCC, 0x4B, 0x7C, 0xCA, 0xC8, 0xC3, ]; let mut out_tag = Array4x12::default(); let actual = hmac384.hmac( (&Array4x12::from(key)).into(), (&data).into(), &mut trng, (&mut out_tag).into(), HmacMode::Hmac384, ); assert!(actual.is_ok()); assert_eq!(out_tag, Array4x12::from(result)); } fn test_hmac_multi_block_two_step() { let mut hmac384 = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let key: [u8; 48] = [ 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, ]; let data: [u8; 130] = [ 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, ]; let result: [u8; 48] = [ 0x70, 0xF1, 0xF6, 0x3C, 0x8C, 0x0A, 0x0D, 0xFE, 0x09, 0x65, 0xE7, 0x3D, 0x79, 0x62, 0x93, 0xFD, 0x6E, 0xCD, 0x56, 0x43, 0xB4, 0x20, 0x15, 0x46, 0x58, 0x7E, 0xBD, 0x46, 0xCD, 0x07, 0xE3, 0xEA, 0xE2, 0x51, 0x4A, 0x61, 0xC1, 0x61, 0x44, 0x24, 0xE7, 0x71, 0xCC, 0x4B, 0x7C, 0xCA, 0xC8, 0xC3, ]; let mut out_tag = Array4x12::default(); let mut hmac_op = hmac384 .hmac_init( (&Array4x12::from(key)).into(), &mut trng, (&mut out_tag).into(), HmacMode::Hmac384, ) .unwrap(); assert!(hmac_op.update(&data).is_ok()); let actual = hmac_op.finalize(); assert!(actual.is_ok()); assert_eq!(out_tag, Array4x12::from(result)); } // This test initializes CFI and MUST be ran first. fn test_kat_384() { let mut hmac384 = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; // Init CFI let mut entropy_gen = || trng.generate4(); CfiCounter::reset(&mut entropy_gen); assert!(Hmac384KdfKat::default() .execute(&mut hmac384, &mut trng) .is_ok()); } fn test_kat_512() { let mut hmac = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; assert!(Hmac512KdfKat::default() .execute(&mut hmac, &mut trng) .is_ok()); } fn test_hmac0_512() { let mut hmac = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let key: [u8; 64] = [ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, ]; let data: [u8; 8] = [0x48, 0x69, 0x20, 0x54, 0x68, 0x65, 0x72, 0x65]; let result: [u8; 64] = [ 0x63, 0x7e, 0xdc, 0x6e, 0x01, 0xdc, 0xe7, 0xe6, 0x74, 0x2a, 0x99, 0x45, 0x1a, 0xae, 0x82, 0xdf, 0x23, 0xda, 0x3e, 0x92, 0x43, 0x9e, 0x59, 0x0e, 0x43, 0xe7, 0x61, 0xb3, 0x3e, 0x91, 0x0f, 0xb8, 0xac, 0x28, 0x78, 0xeb, 0xd5, 0x80, 0x3f, 0x6f, 0x0b, 0x61, 0xdb, 0xce, 0x5e, 0x25, 0x1f, 0xf8, 0x78, 0x9a, 0x47, 0x22, 0xc1, 0xbe, 0x65, 0xae, 0xa4, 0x5f, 0xd4, 0x64, 0xe8, 0x9f, 0x8f, 0x5b, ]; let mut out_tag = Array4x16::default(); let actual = hmac.hmac( (&Array4x16::from(key)).into(), (&data).into(), &mut trng, (&mut out_tag).into(), HmacMode::Hmac512, ); assert!(actual.is_ok()); assert_eq!(out_tag, Array4x16::from(result)); } fn test_hmac1_512() { let mut hmac = unsafe { Hmac::new(HmacReg::new()) }; let mut trng = unsafe { Trng::new( CsrngReg::new(), EntropySrcReg::new(), SocIfcTrngReg::new(), &SocIfcReg::new(), ) .unwrap() }; let key: [u8; 64] = [ 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, 0x4a, 0x65, 0x66, 0x65, ]; let data: [u8; 28] = [ 0x77, 0x68, 0x61, 0x74, 0x20, 0x64, 0x6f, 0x20, 0x79, 0x61, 0x20, 0x77, 0x61, 0x6e, 0x74, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x6e, 0x6f, 0x74, 0x68, 0x69, 0x6e, 0x67, 0x3f, ]; let result: [u8; 64] = [
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/csrng_tests2.rs
drivers/test-fw/src/bin/csrng_tests2.rs
// Licensed under the Apache-2.0 license #![no_std] #![no_main] use caliptra_drivers::Csrng; use caliptra_registers::{csrng::CsrngReg, entropy_src::EntropySrcReg, soc_ifc::SocIfcReg}; use caliptra_test_harness::test_suite; fn test_assume_initialized() { let csrng_reg = unsafe { CsrngReg::new() }; let entropy_src_reg = unsafe { EntropySrcReg::new() }; let soc_ifc_reg = unsafe { SocIfcReg::new() }; let mut csrng0 = Csrng::new(csrng_reg, entropy_src_reg, &soc_ifc_reg).expect("construct CSRNG"); assert_eq!(csrng0.generate12().unwrap()[0], 0xca3d3c2f); { let mut csrng1 = unsafe { Csrng::assume_initialized(CsrngReg::new(), EntropySrcReg::new()) }; assert_eq!(csrng1.generate12().unwrap()[0], 0x7d63f096); } assert_eq!(csrng0.generate12().unwrap()[0], 0x248474c6); } test_suite! { test_assume_initialized, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/mldsa87_external_mu_tests.rs
drivers/test-fw/src/bin/mldsa87_external_mu_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: ml_dsa87_tests.rs Abstract: File contains test cases for ML_DSA87 API tests --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{ Mldsa87, Mldsa87PrivKey, Mldsa87PubKey, Mldsa87Result, Mldsa87Seed, Mldsa87SignRnd, Mldsa87Signature, Trng, }; use caliptra_registers::abr::AbrReg; use caliptra_registers::csrng::CsrngReg; use caliptra_registers::entropy_src::EntropySrcReg; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_registers::soc_ifc_trng::SocIfcTrngReg; use caliptra_test_harness::test_suite; mod acvp_vector { /// Test vector from https://github.com/usnistgov/ACVP-Server/blob/master/gen-val/json-files/ML-DSA-sigGen-FIPS204/internalProjection.json pub struct AcvpVector { /// Public key pub pk: [u32; 648], /// Private key pub sk: [u32; 1224], /// External mu to sign/verify pub external_mu: [u32; 16], // Expected signature. Actual signature size is 4627 bytes, the last word is padded with a zero. pub signature: [u32; 1157], } /// Test vector "tcId": 151 pub const EXTERNAL_MU_TEST: AcvpVector = AcvpVector { pk: [ 0xc8243989, 0xefb40aaa, 0x735fc646, 0x5276eaf9, 0xe73dd5a9, 0xd7374096, 0x13f3d535, 0x27bf23e3, 0xf4ff4633, 0x583991d5, 0x3f066bb9, 0x3cd09c4e, 0x0ab1cd2d, 0x302df185, 0x08cd14a1, 0x09c7f0a2, 0x93933536, 0xa0f28cb6, 0xb1f362e0, 0x5a4c6feb, 0xaa281f51, 0xf1f4e4c2, 0x22281a33, 0xac7164d4, 0x0ad77177, 0xa8f96287, 0x236ea11b, 0x4361f384, 0xae4db555, 0xd717ee7c, 0xea7c8cc9, 0x239e9f91, 0xa0f2b20c, 0x55471c08, 0x01c4eceb, 0x7fe0e268, 0x0f84ce7a, 0x150a97f8, 0x2fe677f0, 0xb1f4c195, 0xe7b3a427, 0xcdaf05e3, 0x4a6eedf6, 0x4337266c, 0x7f8b98d7, 0x7fd76a91, 0x768f0d8e, 0x991b2e1a, 0x9e9d6202, 0x8b7f0fa2, 0x4bd33950, 0x988953b6, 0x18545915, 0x4f210f15, 0x1e8b4d10, 0x90c4f2b9, 0x41e57e22, 0x12c51baf, 0xab00e50a, 0x85f458d8, 0xb64a1712, 0x55504738, 0x25bd677f, 0x421a50fa, 0x0440644e, 0x5ebf3c5c, 0x71f4d31c, 0x645b9c84, 0x1a96b342, 0x83b3d7d0, 0xceec62bf, 0xdd2df1b0, 0xd68bab02, 0xe98e3772, 0x5e1ed615, 0x87966162, 0x7c12ac43, 0x1dc68e44, 0x6b7aed4a, 0x1d810e33, 0xb7a47210, 0xad70a78b, 0x64fe868c, 0x716be1ec, 0x8f4c23e3, 0x0a1c9dfe, 0x5fce90e8, 0x97811b28, 0x7202e2c3, 0xd03d5d38, 0x14217691, 0x12d523e4, 0xe5645f16, 0x86b1e017, 0xb687ffe5, 0xed536067, 0xddfdd631, 0xa3545939, 0xab43da6d, 0xe9830809, 0x8396f506, 0xe6090204, 0x7da9d8f2, 0x9cd8a885, 0xeb0c550e, 0x9dde48e6, 0x7c53f88a, 0x705eb700, 0x66978ffc, 0xebdbb405, 0x4cdadc9c, 0xccd8ae95, 0x949fbbc3, 0x6724a717, 0xa2f2a7f6, 0x80442d5a, 0xf273d7ef, 0xec69c947, 0xde17c799, 0xb794c4f0, 0xfcf8fb0b, 0x725663bd, 0x4a512326, 0xfa4ea35c, 0xcfaf8d16, 0x768cc593, 0xcab845b8, 0x7ff9d9ea, 0xfa15a7bb, 0xbb89ceab, 0xf608c371, 0xfbfa5318, 0x063e8c77, 0x0c92f396, 0x4de1451e, 0xa7a90445, 0xec4d101d, 0xb9ae75c1, 0x1f965e4a, 0x26a36539, 0x447c33e2, 0xec55b810, 0x6b9464a4, 0xd356f2ae, 0x09cde584, 0xa5488495, 0xcb606772, 0xef149716, 0x997dcbc0, 0x52316971, 0xb402c4d5, 0x5f3d0346, 0xb66fb956, 0xcece22ad, 0x66e0936f, 0x1db47d51, 0xa8c2d30a, 0x6dd6eb78, 0x2c348cdc, 0xb65a3b1f, 0xac255a8b, 0x0c4f5044, 0xfe364a19, 0x137545ba, 0x074c261b, 0x0f81a5c0, 0xf0ac0a47, 0xf70a927c, 0xd47bf146, 0x706ca6f0, 0x11b94f27, 0x662756d8, 0x28211d3c, 0x700f2a86, 0x4600ee1f, 0x5684177b, 0x5871ca74, 0xe40d92fe, 0xb4e09e26, 0x36d5a303, 0x1ad6a923, 0x48129f35, 0x63a5bb37, 0x1062d9fc, 0x75e69a12, 0x99458303, 0xe4f82142, 0x36ddde4e, 0x53dadfb3, 0x4c851bc4, 0xe775526e, 0x1b77ec7f, 0x52d247a9, 0x9f74b842, 0x5a74f068, 0xe0a70575, 0x4e98ded0, 0x8b3b0678, 0xe2559d0f, 0x622ce556, 0x0f5a046e, 0xbe241307, 0x057067be, 0x1e0f7280, 0x11239211, 0x84b109af, 0x23ab75e8, 0x9e40ef3f, 0xa5c2449c, 0x033aae29, 0x8bced945, 0x3bac5e84, 0xa2aa1544, 0xd6693a55, 0xeeed9565, 0x4c3aa09e, 0xedb856a4, 0x23ec13ae, 0x6692544c, 0x83698aba, 0x0a107f6c, 0x6b919148, 0x4c147969, 0x7fe2a243, 0xe4a26125, 0xde3289f5, 0x1006bbad, 0x60836457, 0x79a74c8a, 0x5f89cbc1, 0x73ba0f9a, 0xe53ddd84, 0x85197e59, 0x0cfea5f7, 0x3b47a2d9, 0xefaf4837, 0xb5482921, 0x959f4bd9, 0xa3188da9, 0xa81d2ba4, 0x742cb45e, 0x410d3286, 0x1d78e6c5, 0x00ae0ae6, 0x5d1a6da0, 0x6256669f, 0x695bdfb8, 0x7b00b31c, 0x6db885aa, 0x26639d1c, 0xb37e144f, 0x72cdb8fb, 0x8e7b83e3, 0x51ba4e38, 0xdf04d199, 0xf3a08aec, 0x19cde660, 0xa2d4ddeb, 0x22343d6d, 0xdce095d8, 0xca6c3aeb, 0xf1d4a6dd, 0xe8a410fa, 0xb2d26712, 0x61a52d2a, 0x830b4e54, 0x5ec12ccb, 0x4d0cd56c, 0x4630a940, 0x80481580, 0xc604cd9c, 0xcdca5e05, 0x481e88e5, 0x8daba865, 0x245734c5, 0xfa4f3d32, 0x8a97aa20, 0xaa3338ad, 0x4a1e348c, 0xbab6ee34, 0x4ee88b18, 0xd2f44b58, 0x8f4484f3, 0x31e925e2, 0xf56fbbeb, 0x180b896c, 0x9f6c5e3e, 0xa55c05cc, 0x117a11da, 0xbd4a00ef, 0xc33aa4d8, 0xe9157caf, 0x1879ea01, 0xd299d05e, 0x22aaaa6c, 0x8367ca56, 0x91bde9a9, 0x5fd71f8b, 0xffc57459, 0x940eecae, 0xb0024ff3, 0xa4e833fe, 0x9336b396, 0x63b9c1d4, 0x4ab71bb5, 0x516ec190, 0x63e0017e, 0xc7512e45, 0x42e80af3, 0x027f738e, 0x1e54aac8, 0x294cbc24, 0x7629deee, 0x6eacc2e9, 0x6728d325, 0x10189813, 0x3fd2b9ec, 0x0e403a1c, 0x3429c17e, 0x9e84766c, 0x8ecf0c6d, 0xcfc51b61, 0x6b54ad7a, 0xad005bfc, 0xb4806851, 0x87287123, 0xe1b04085, 0x1a0c239e, 0x6b3b4dc7, 0xd9a121ec, 0x5f350092, 0xfb74874a, 0x22b6f5e0, 0xa56fd086, 0xaee94505, 0x32d524c5, 0x26c938d3, 0x3871a105, 0x6fc74a5c, 0xf4c8f9d8, 0x9d24fc2b, 0xef6404aa, 0xd87ffb5d, 0x6eedf338, 0x5f4b0b71, 0xf9adaf57, 0xc33b5192, 0xd5eb9b3c, 0x2a85bed6, 0x27afc2f9, 0x5e27526c, 0x826139e6, 0xd8f26ce2, 0x192fee05, 0x88bd5ae1, 0xd71bc743, 0xbfe2fe4b, 0x079e1b55, 0xf4b7fb3c, 0xf39fe4bd, 0x8813b99a, 0x4b21b882, 0x65e391da, 0x2e2718f0, 0x308b65d1, 0x9ea23da1, 0x16417119, 0x55ce2efd, 0x936233f4, 0x87021308, 0x26d89562, 0x26d97801, 0x59e265ae, 0x2f1331d0, 0x2045a99d, 0x5f7d7482, 0xf8d01f7c, 0xa89431e8, 0xf14d55cc, 0xa9529227, 0x36460494, 0x4de1f8bd, 0x2d1d4ac7, 0x6b5d68cf, 0xba4a1741, 0x651165ac, 0x38dddea9, 0xafad4e99, 0x0e0df157, 0x9a92c4fa, 0xdd434437, 0x1cd6601f, 0x66430f9f, 0x5c1e9a2d, 0x0a9f02c2, 0x1640510a, 0x7619c610, 0xfc24cc60, 0xbfb4a0da, 0xb371a532, 0x5f7e70f7, 0xf4cf289f, 0x639e879a, 0x27a7e8d6, 0x3247032e, 0x893d5456, 0x18387f78, 0x961b3e2e, 0xe1e0ae85, 0x7f57f54d, 0xd536a067, 0xbda86619, 0x448f4941, 0x71fcb695, 0x91662b6a, 0x12808e16, 0xa66817d9, 0x5d8ffcd6, 0xf45e51c8, 0xfce4a8aa, 0xb08efb97, 0x74bbb6f1, 0x9eae6e97, 0xb4104bc7, 0x17d6b6c8, 0x4e413eb7, 0x45ae10f6, 0xa9624426, 0xc55077bb, 0xd3a8d386, 0x74f67f3b, 0xc5dfa4fe, 0x57f9ca71, 0x308208b4, 0x531db33d, 0x0fcd9fef, 0xe0a85656, 0xf52ee42d, 0xacfd1028, 0x7f889ceb, 0xa0ff5d9d, 0x6a494f8a, 0x796d267f, 0x3421ae3b, 0xd136b499, 0x4b3eb9cd, 0x3932d989, 0x1e22e561, 0x0df14727, 0x38f32517, 0x5ff98d8b, 0xd0d97f62, 0xf17fbe86, 0x6b3ed371, 0x07dc1f4c, 0x2180d8ef, 0x95b60e18, 0xf2b272de, 0x8c5be2a0, 0x17918bd5, 0xc2ca32a5, 0x0e117366, 0x4b237a30, 0xcbaec7d2, 0x3472b0f7, 0xb63641ae, 0xf0233a0e, 0x3a79b906, 0x008ca293, 0x00152275, 0xcf332763, 0xd422bad3, 0xb62042eb, 0x5674e97a, 0x1856e91a, 0xbe0fa44f, 0x008c1f3c, 0xf3d32819, 0xaa9e13ba, 0x49ad98be, 0x2cc85da7, 0x1158a35d, 0x5197d325, 0xf1b889a0, 0xf61565b0, 0xb4ae704c, 0xfca421f2, 0x57ca53f8, 0xd6133289, 0xe63c9bdf, 0x63d05603, 0xf30f2299, 0x737ded61, 0x3f5cdb83, 0xcf56f878, 0x3ca82f1b, 0xa6046340, 0xbd5ba24f, 0xe9f4e12c, 0x8bae88d7, 0x3206912f, 0x4e061606, 0x2a8b440b, 0x3d610a84, 0x5f6ce24d, 0x59367f62, 0x06c6996f, 0xa43338f5, 0xd7764b82, 0x4a577465, 0x78c2da14, 0x0f74ebe8, 0xc01a6e3f, 0x1f4bd1be, 0x0dcb979c, 0x537ed079, 0xd123a1bd, 0xedd2f902, 0xb860ee16, 0x360f242e, 0x852b4293, 0x8cabeb06, 0xe513c163, 0x8a082be5, 0x96377161, 0x54a518cc, 0xc0ed83e3, 0xf3ba2b69, 0x698fb68c, 0x21f7705a, 0x649a28a5, 0x432b61c9, 0xaff99cb6, 0x3c0f79db, 0x32ae1b25, 0xa597be6b, 0xe6289e25, 0xf721eb27, 0x37ceb0c1, 0x7bcedef0, 0xd3860ac0, 0xb719a59d, 0xe849e9e6, 0x037356bf, 0xccead649, 0xedb51765, 0xb879c15c, 0x4ec867a3, 0xe258f233, 0xe35d114d, 0xed02514c, 0x621c55ce, 0xee151b44, 0x577a5f34, 0x171d6c5e, 0xb659f9f3, 0x99533268, 0xc710c844, 0x5b33684c, 0xa9aef28a, 0x39b0a309, 0x16ec6439, 0xcd2e2742, 0x0ab4bf71, 0x7da76d58, 0x0fec3563, 0xd7471db0, 0xaa95872b, 0x6761fecc, 0x698d6b06, 0x33d4c163, 0x321c0d86, 0x87ff511d, 0xe943a04d, 0x4c926c36, 0x6dd0ce37, 0x429d42fe, 0x7fe2b221, 0x21a3c1f9, 0x97b916d6, 0xd348a001, 0x428fd4aa, 0x8c51b18b, 0x387bfe1e, 0x9bb98b1b, 0x23145bde, 0x915e3747, 0x3458b5eb, 0x0f2956d9, 0x29caefb8, 0x1cd16d70, 0xa0577b00, 0x3d826788, 0xd7724835, 0xbd726baa, 0x5ed8d680, 0x461f02e0, 0xded4618c, 0xa37adfb8, 0xf16c7f4d, 0x15f659f2, 0xfbeb58c5, 0x3d8696e4, 0x353b00ed, 0x1fef385e, 0xda6ef7cb, 0xf978d2d6, 0x743ee9ef, 0x33b49612, 0x46bf3301, 0xe9b87ad0, 0x65cd0151, 0x9dc6bb5c, 0xebe88e10, 0xe6948730, 0xac7655ef, 0xc63d9e30, 0x46f67e7e, 0x0fb03959, 0xfcc3edf0, 0x6d8f39c7, 0xf6cb42b2, 0xa66ce9f6, 0x7a8b1548, 0x734c60ab, 0x193752ec, 0xf7c020cc, 0xac4fedf2, 0x67bbe429, 0x568c03b7, 0x754d32b3, 0xf10f0e0e, 0x649ceafa, 0x30c244a2, 0x8f5c93ef, 0x545afa7a, 0x761f23b3, 0xa30b3f18, 0x95b54a50, 0x4f9aea48, 0x28426e77, 0x9d6c359d, 0x73a83f80, 0x0c7ffa6e, 0x43afc8b5, 0xf6a75f72, 0xf8d50b9b, 0x3ecbd8cd, ], sk: [ 0xc8243989, 0xefb40aaa, 0x735fc646, 0x5276eaf9, 0xe73dd5a9, 0xd7374096, 0x13f3d535, 0x27bf23e3, 0x7d103e64, 0x86d3193a, 0x2a970c0a, 0xb674daaa, 0xb7f26dbd, 0x833ca404, 0xabb4f390, 0xd7d135c9, 0x01027c60, 0xa6240083, 0xecad8514, 0xd4f8281f, 0x9fe555a1, 0x1d0875f5, 0xbe897945, 0x28789f4c, 0x1b730d13, 0x3988d76d, 0x5a81c880, 0x3dd1c5f8, 0x94141017, 0xb40285a1, 0x9c42eb06, 0x3ad44bf8, 0x8330c48c, 0x38d341c4, 0x60b4a081, 0xcb7130a0, 0x369a9194, 0x2136e40e, 0x244db618, 0x369c0482, 0x0d470302, 0x900a4248, 0x38402480, 0x6e485971, 0x5c902814, 0x80221248, 0x72141980, 0xd009a2d8, 0xc8046110, 0x85340845, 0x21661503, 0x08886db9, 0x32165181, 0x4491904c, 0x96c27036, 0x61941a60, 0xe33206d9, 0xb0116220, 0x28029990, 0xc185101a, 0x09014a38, 0x8a221929, 0x9c4cc320, 0x370a8580, 0x09951b31, 0x9b60a118, 0xa8042d88, 0x6d952250, 0x19224219, 0x49088920, 0x2996da46, 0x53843220, 0x920b4c14, 0x25a6920c, 0xca30c8e0, 0xa91a40a8, 0x21a64220, 0xdb290441, 0x402321a8, 0x31129168, 0xd831b014, 0xb2590088, 0x49c11285, 0x0b2a02a3, 0x13236a01, 0x41920c48, 0x2108c21a, 0x47086cc0, 0x2610224e, 0x8a2498d4, 0x88cb6cc0, 0x00886068, 0x408800c2, 0x10102600, 0x08051021, 0xc20986d0, 0x36927148, 0x8c330b8d, 0x0b82225b, 0x04043107, 0x4008d110, 0x5a249059, 0xb2224606, 0x2c46910d, 0x596d491b, 0x36505188, 0x20c4c461, 0x820a12e3, 0x08880c10, 0x4526a400, 0xe46e14d0, 0x389991c6, 0x2a08e392, 0x424a0499, 0x900a4108, 0x08a8c280, 0xa220a8d2, 0x044b8c40, 0x4d92e171, 0x03643454, 0xb4926203, 0x25a84430, 0x9a41100b, 0xa6d16a26, 0x68c71291, 0x2104b898, 0x944a09b5, 0x2d361928, 0xd9908909, 0xb4592180, 0x0c308021, 0xcc29a408, 0x289a69b4, 0x2e40014c, 0xd201941b, 0xb30a70c4, 0x8406d34d, 0x0c0e08a2, 0x90606414, 0x6031226c, 0xc8311652, 0x05238a16, 0x5116a328, 0x643004a4, 0x808c11b2, 0x4d32c171, 0x02419658, 0x389c2a44, 0x51802440, 0xa20540a3, 0x34d380c2, 0x61310b2e, 0x512c1821, 0x92242520, 0x0a042248, 0xa2652249, 0x86108802, 0x40945b89, 0x09463314, 0x92cb6626, 0x8216c12c, 0x014dc452, 0x845c5210, 0x4c084c60, 0xdb64b501, 0xb28b6c82, 0x9009048d, 0x0c264414, 0x40d28140, 0x6c04a128, 0x142e40cb, 0x172350a9, 0x90b04111, 0x5a514808, 0xc8236e20, 0x2cb46205, 0x142c44d2, 0x469b4893, 0x0db5124a, 0xc8004863, 0x14a32610, 0x71481c90, 0xdc6cc654, 0x30190d38, 0x9244d26a, 0xcc510880, 0x071b8dc0, 0x08b51228, 0x08041689, 0x945c50b4, 0x89422111, 0x1b2cc521, 0x08204812, 0x40460169, 0xd249b2dc, 0x045c8498, 0x8816a34d, 0xe444a08c, 0x92146492, 0x05245388, 0x14322294, 0x18602515, 0x4da2a482, 0x9046341c, 0xb0202dc4, 0x50311421, 0x20303901, 0x27208d97, 0x4510a110, 0x94009251, 0x08141024, 0x04402405, 0x6111c6c4, 0xc2082508, 0x4e28c221, 0x03618302, 0x24524646, 0x2c84a061, 0x196e400a, 0x08106849, 0x2190e38c, 0x8c40a45b, 0xc8a44dc0, 0x29224c84, 0xa3310814, 0x97242144, 0x09c0008c, 0x8a003484, 0x30498886, 0x4a365849, 0x086d8123, 0x40db89a3, 0x02485020, 0x18693023, 0x28422216, 0x0d826100, 0x5a12180a, 0x32195222, 0x11a4040c, 0x02913524, 0x42024124, 0x0990e244, 0x182428e1, 0x131b51b2, 0x8da49386, 0x12040844, 0x968a0827, 0x4d369250, 0xe26032c2, 0x30d12d98, 0x0634e289, 0x0041c119, 0x46520d44, 0x2da72064, 0x0885888a, 0x265231c8, 0x01190882, 0xc32a2863, 0x35110408, 0x6d170320, 0x580632da, 0x400a6816, 0x51a48a0c, 0x0a5216a0, 0xb4900883, 0x2c97018c, 0x9b008819, 0x241b6880, 0x6d185c0e, 0x5a2d311b, 0xa29c0924, 0x90265925, 0x9308a4a0, 0x86d04a40, 0x50a2244c, 0x24120409, 0x30506513, 0x8c86016a, 0xc345970a, 0x404809c8, 0x50981a01, 0x1304389b, 0x86e308a5, 0x06452444, 0x83483282, 0x320b6d22, 0x44010808, 0x588024d9, 0x389a2cc4, 0x28a66201, 0x1a019280, 0x06e02d09, 0x1236646a, 0x0c0c94c2, 0x36984c45, 0x0926db8a, 0xa44e445c, 0x22248c80, 0x32129b86, 0x138448cb, 0x00635249, 0x2d308b24, 0x820db823, 0x29189148, 0x0500d371, 0x20709683, 0x229a2519, 0x7130216d, 0xe42e169b, 0x40dc2c06, 0x2cc60482, 0x0464c049, 0x82136e49, 0x04805169, 0x88640888, 0x820c1008, 0x46325a45, 0x812c3091, 0xb21a8484, 0x05330001, 0x9a12424b, 0x40629002, 0x8938448e, 0x9245c890, 0x888b6128, 0x31430b68, 0xa0024320, 0x84cb8c86, 0x4218840c, 0x926db324, 0xc5020108, 0x26362460, 0x5b201309, 0xa84c64c6, 0x0918da0d, 0x13914001, 0x99080d04, 0x84948200, 0xa2924291, 0xa8107008, 0x4244a28c, 0xa2260291, 0x02240246, 0x2d445c8d, 0xa290025b, 0x07240e02, 0x6a184380, 0x6365405b, 0x069b25c6, 0x28c68904, 0x4109a682, 0xb5214542, 0x2c902281, 0x922a10d9, 0x39088e12, 0x0da2586d, 0x82043022, 0x024c2438, 0x89348928, 0xc050c650, 0xb0d89046, 0x88a52321, 0x980e1860, 0x37116e12, 0x6c901169, 0x428c98c3, 0xa2832624, 0x2d88e149, 0x43083489, 0xb8886a26, 0x04145345, 0x5c094921, 0x910a6090, 0x11144b8d, 0xc1861841, 0x84212d16, 0x2e240c68, 0xd2259001, 0x12106082, 0x7088904c, 0x0a824712, 0x14802981, 0x2994d061, 0x0084330a, 0xb6192223, 0x11a6d890, 0x0328b524, 0xb8992c33, 0x60949320, 0x1b421514, 0x110c4a33, 0x0c084460, 0x99be1e90, 0xc3633112, 0x0e3a98de, 0x7933baac, 0x3c00df50, 0xb9d0caab, 0x1fd9514c, 0xe60e6870, 0xe218f943, 0x6eb6790b, 0x2be329a3, 0xf4b1bd96, 0x25986420, 0x1e1b01c2, 0xa89bf8c0, 0x0875fc91, 0x3b9b9c8b, 0x7d400c54, 0x5e90a086, 0xb5f05519, 0x1abb9322, 0x0ada836a, 0xa88f3be8, 0xa48a0996, 0xe8a012cd, 0xc4dd363f, 0xbfeadf40, 0x9f384156, 0xe14bca4d, 0x3e6b1e5e, 0x48a27b91, 0xfdc90f38, 0x29220bb7, 0x84824274, 0x42761133, 0x55f87329, 0x95ee819f, 0xd92cbe80, 0x458aad69, 0xcbbba48a, 0x704d7582, 0x57461dc5, 0xc1d1761d, 0x71abe7fc, 0x6dfe3f3d, 0x4d7d979f, 0x046dc868, 0xca5fcde5, 0xa918a316, 0x21d641da, 0x6c86ce40, 0x14e871ee, 0x782c6db3, 0xe6cc8538, 0x3025c6ce, 0x6aa77841, 0xfb0e7194, 0xb6cc90b3, 0xaccd953a, 0x2cfe93ab, 0x419c00cf, 0xa9676bfc, 0xfaf940f7, 0x1123231e, 0xbd0099a3, 0x24714aec, 0x1c827764, 0x79fd1a48, 0x910225a9, 0x981981a0, 0x0e1f6c63, 0x7ca6c302, 0xfcae5de3, 0x2a8f58f0, 0xf8dc18d8, 0x6f07eb43, 0xf110f708, 0x38512709, 0xd2af3bfa, 0xa4b68c98, 0xf41ffe08, 0x6798f5c9, 0xb31af31a, 0x253a7f08, 0x48c895d5, 0x5c2efb30, 0x8d827b3e, 0x45d82ce0, 0x8e13d07e, 0x006380b8, 0x7e6c54a0, 0xbc37de08, 0x4196a130, 0xa5fc9918, 0x0d1f0cac, 0x47de43cd, 0x6e0d6ea8, 0x71c1e101, 0x01356bb7, 0xde34c427, 0xf7a12efb, 0x63c653db, 0x7c705eec, 0x6a4b606e, 0x332d905b, 0x91e16123, 0x3f04db42, 0xe485755b, 0xfd7e60c8, 0xcd484011, 0x142982b4, 0xa578367f, 0x31ffe828, 0x4aca43d9, 0x6bd343d6, 0x4f7570cc, 0x184568f2, 0x3e0f8cfe, 0x520e2975, 0xeb0488ed, 0x64647f3a, 0x798460fa, 0xc7e65643, 0x710d0fa5, 0x396de1c8, 0x8ed6ab2d, 0xfc9c57d0, 0x48775a75, 0xb9f9bc4f, 0xd1c9d8b2, 0x51b9f3bf, 0x15aecd96, 0x39bf6172, 0x78af7bc3, 0x5f6ad800, 0x2f077f97, 0xeb8b0ff9, 0x144b7788, 0x2b32f263, 0xc99519d0, 0xa9eebd90, 0x0f2b3803, 0xe88e1b3d, 0x031f267d, 0x6770f61c, 0xd308f24c, 0xce93c3a5, 0x7f53ad6c, 0x982e297b, 0x99a6a0d1, 0x9ee27e34, 0xe7cef355, 0xe6f27b35, 0x870f581c, 0xa4da7fcc, 0x3d19c88a, 0x02fb3cce, 0x84c6577d, 0xba542117, 0x8478c7b4, 0x430cd6b8, 0x866c73ef, 0xca037353, 0x71c296e3, 0xec5e2981, 0x9973e118, 0xe16b36aa, 0x3abe5954, 0x53115de1, 0x21096407, 0x5dc57b63, 0xb65d5430, 0xdc4e98ad, 0xd5f58983, 0x05184482, 0x91184bd7, 0x0eee18fb, 0xdc694e9f, 0x6daf8d55, 0x785edf3c, 0x524b09f4, 0x62c242cd, 0x403d1bca, 0xef1016cb, 0xcb43c09f, 0xe185d8cf, 0xedf7164f, 0x9ab83aaa, 0xf3576f62, 0x8f743d43, 0x3660ab23, 0x75d9e589, 0xa16b8699, 0xd1c65778, 0x3833c81a, 0x362ed2e5, 0x86835d2a, 0xd8522d6f, 0x6bc9509a, 0x604c4dc6, 0x97b1c225, 0x8d14a2d1, 0xc48c18bc, 0x0c2bb469, 0xdc00e84c, 0xebfc01d4, 0x4a39f30a, 0x3f502529, 0xf10f3613, 0x14f8c9cf, 0x550ef3e3, 0x590134fd, 0xc3753cff, 0xd5e328a4, 0xe1f3c5b6, 0x4b3de46b, 0x04ccccd8, 0x80f4ed24, 0x5a551b09, 0xc02ce9e5, 0x0b73c10b, 0x2bc8a7d4, 0xd8b1df9c, 0xf19f3d3a, 0x16545781, 0x48615b2a, 0xefe77f0c, 0xd5201867, 0x8416b1a2, 0xc49d5d29, 0x5e8d4dab, 0x96c67f8a, 0x0166ad81, 0x5eba8943, 0x20aded53, 0x15158d4a, 0x23692f78, 0x16df9077, 0xad0b7595, 0x1317f327, 0xcbeb935b, 0x6acb6400, 0x07ab8888, 0x91b00275, 0x162aa0f0, 0xcff0f27f, 0x0872b1fc, 0xeda23e89, 0x695089e9, 0x30137e73, 0x4e3198c8, 0x1a16d4d0, 0x16464813, 0x6ee5b6a9, 0x7f89a5e0, 0x605ca8dc, 0x5413b798, 0x738fbca6, 0xab4fccb9, 0x3bf2c7fe, 0x72ff16ad, 0xbadd06fe, 0xfed78ad2, 0x5ab8a398, 0x60373829, 0x6414673f, 0x9be8c5fb, 0x4d42a472, 0x06f484b4, 0x31029935, 0x55a61ed7, 0x6be540e4, 0x0894cb3a, 0x358e22c7, 0x2a25b976, 0xfa4730d3, 0xa21fb155, 0x4e64d494, 0x414a8dd4, 0x0c33bf24, 0xd9125f34, 0x65ef86d3, 0x1769cbb1, 0xf3cd2f6e, 0xe848994e, 0xaff778c9, 0x6b28c97d, 0x3e4cdacc, 0xa931eb5b, 0x4411d7b2, 0x278b6d8d, 0xe98deb89, 0x724acd28, 0x796e1a1a, 0x423e4f2c, 0x4aa3333c, 0x64d71ebf, 0xc6597274, 0xaf5f2025, 0x14cd1223, 0x5f2bd807, 0x98b04e67, 0xdf393b12, 0x90be5f0b, 0xbab19f4b, 0xcd4783ab, 0x0fe58660, 0x78eea5ee, 0x4f53a37f, 0x0fb09608, 0xa26e0b71, 0xd84d4629, 0x14ec2129, 0x23ccccc2, 0x149ad7cd, 0xc6aa53d8, 0xf08b234e, 0xd3f58aa5, 0x0e5c0084, 0x188ea9f7, 0x7791365b, 0x7f92c798, 0x6be69ae7, 0xe8e909a3, 0xc4b93ee3, 0xc7b6a7b8, 0x5a8bce38, 0x8bb0f354, 0xb73fae73, 0x05012ff4, 0xb8a33104, 0xa6b0f24f, 0x19f46f75, 0xd52c10de, 0xeced14ea, 0x5051abe3, 0x3d151279, 0xcbc03acd, 0xda9fc0d8, 0x89174f3e, 0x27f005e7, 0x6a07c36d, 0x2687a825, 0x1a233009, 0x52d9286e, 0x8d2015ad, 0xed0c7b8a, 0x55d51010, 0x8fef932d, 0xc360a9df, 0x8f007cbd, 0x3ccb44be, 0xda686dde, 0x555ad4b1, 0xce37db50, 0x81bb4257, 0x85d3164a, 0x6e60674a, 0xab43dcd3, 0xa8341164, 0x16de2172, 0x97224c52, 0x778f5559, 0x7605d3d1, 0xa15c6d9d, 0xcaa0200e, 0x06902836, 0x3fac59b4, 0xcba8a180, 0x2f2f7a78, 0xdc438226, 0x1daa4498, 0x3974aa61, 0x05469092, 0x4b473a8f, 0x34ee34ed, 0x5145b37b, 0x25291574, 0xf02c2721, 0x99b4b110, 0x4f43fe09, 0x8d55f1ab, 0x26d6603d, 0x3303f9c8, 0xf8fae429, 0x83f80b85, 0x20810258, 0xfdd67075, 0xe38811e5, 0xe8a8b3a6, 0x22f57ec4, 0x43726f48, 0x1e6c73c3, 0xdfc504a3, 0xd04ea9bd, 0xec0e396e, 0x35dcfbe2, 0x85164ca6, 0x4bf45b75, 0xfbc0f3ca, 0xaab81cd3, 0x964d9414, 0xf7d21636, 0x4b627c1f, 0xdc97d5e4, 0x7a933863, 0x76410327, 0x409946a8, 0x41324627, 0x23130a7c, 0xe826df81, 0xc618fad6, 0x375f62f4, 0x0c912cf4, 0x646f7ad2, 0x0bbd6752, 0x2405f42e, 0x070197be, 0xdc55379b, 0x57f0b741, 0x8b63f9eb, 0x9e76886f, 0xfd682154, 0xf2c2711e, 0xcae0f7c5, 0xed03dd5d, 0x15492f07, 0xe3f50bf6, 0xcb5a31c9, 0x2e867858, 0xca10e510, 0x159e3c0e, 0xcdae2c8b, 0x04b4f7d7, 0xdb172fee, 0xdddab09c, 0xdc90eca5, 0x9a5cfcc7, 0x70c6ecfc, 0xbd1f1a4d, 0x4914b0bc, 0x1128cbf1, 0xa00f5c44, 0x70cb9994, 0xfb28bdf7, 0xfe7c93ee, 0xe929d9b3, 0x9d42ea8f, 0x62e0e37f, 0xbbd40ca8, 0x098c92be, 0xa6eced43, 0x1a61a2be, 0x4da054a9, 0xd76a9529, 0x1871617c, 0xf06b0911, 0x4ea2fdf1, 0x50a9c9b7, 0xcb4aed8b, 0x3b9d41b3, 0xd747cee2, 0x34e4a3ec, 0x3f0fa067, 0x99cdbfa6, 0x60b5a155, 0xcfcae90e, 0x72f947c2, 0xbfba2b0d, 0x83e596cc, 0xd31fcf9c, 0x2d768c61, 0x29f351b2, 0x9a00c11e, 0x4811842f, 0x1931e60a, 0x9c067101, 0x904d9e56, 0xd1502475, 0x3e7bce38, 0xecc03237, 0x42db7228, 0xfd586c9b, 0xead94185, 0x29be336e, 0x37c424a9, 0xad927b88, 0x158b8e1b, 0x8cbabce8, 0x0802ade5, 0x50d52c8d, 0xe4d8a7df, 0xe3a40592, 0xb7737909, 0xf0d8ef62, 0xf32d5272, 0xaa2bbc07, 0x968cb2d2, 0xf05f888b, 0x9a0a859f, 0x83860060, 0x1500b453, 0x65c546aa, 0x8bbb8005, 0x9da9e57f, 0x6facacf2, 0x1b9a51cb, 0x8a52d9f6, 0xeb2dfd09, 0xe78a02ac, 0xb0910d21, 0xec342576, 0xc478b97a, 0x6c3068cd, 0xb41067e1, 0x2b0070d9, 0x5b72a78d, 0x7d3b5b7d, 0xfcc5547f, 0xb100c85e, 0xafaf7230, 0x9ece429b, 0xf11e3d44, 0xa3791f44, 0x0bbd1c73, 0xd088f680, 0x8d5c21b0, 0x93b563f8, 0x62923899, 0xeaddadf1, 0xb4dc4317, 0x530e70f8, 0x80d72757, 0xfded56c4, 0xe815ebe3, 0xd58c2080, 0x688744af, 0x7ad27228, 0xedff37f9, 0xa54d829c, 0x861c6bc9, 0x1f21f82c, 0x73004223, 0x5583f50f, 0xcedb3c94, 0xc9fea982, 0x3983f37b, 0xabd3927b, 0x28270555, 0x6f81335e, 0x93cad8a4, 0x0813924c, 0xc5b3f764, 0xe997540e, 0xb7ab9677, 0x2d7da0aa, 0x78f5bb10, 0x6844bb3d, 0x48948f88, 0x274070e3, 0x9b3eab56, 0x8c1d1618, 0x5520ef07, 0x74838929, 0xb2654d85, 0x762dc6ed, 0x4093c773, 0x728c9bb3, 0x8c0adedd, 0xb5db1128, 0xb0c5d177, 0x71e00fdd, 0x3c64d16a, 0x99323e0f, 0x5ba35f78, 0xe858e840, 0xc27a2473, 0xcebddf2f, 0x2fefda33, 0x2da74420, 0x50c0ac12, 0x6f213fba, 0x00765262, 0x4374b474, 0xd8414925, 0x4a9f6d87, 0x4df520e1, 0x188bb6f3, 0x6e21748b, 0x823f7238, 0x9c1b85b2, 0x1b0410b2, 0x7ff2bc3f, 0xcc74b844, 0xbb37360f, 0xf88a2143, 0x8b90293f, 0x299ab72a, 0x617ab6f2, 0xdac13c88, 0xc04f53d7, 0x846fce8a, 0xd1ee56cb, 0xe3b6c390, 0x0b566f48, 0x26220c68, 0x9c5df85a, 0xe13d30c4, 0x8599a530, 0xefe675ad, 0x164285dd, 0x2fcad8a0, 0x3dc42d36, 0x5b0f254c, 0x21b1d72d, 0x25a99c59, 0x60a34a2f, 0x2d7937b9, 0x0eb99da7, 0xce51dd79, 0x3c2fa20b, 0x3f6d7c7c, 0x6599d471, 0x4eca091f, 0x0d9b9ef6, 0x36c54c6f, 0x250376ff, 0x209ad9fe, 0x01609477, 0x0af08c34, 0x1cb5b175, 0x50a5111b, 0x24176660, 0x058c6784, 0xc0ceea85, 0x0c6c32ec, 0xc6e0e171, 0x6c5cb49f, 0xa123fea2, 0xbb47b842, 0x7f047a85, 0x1361536d, 0x0ca8ca90, 0x6d07af4e, 0x05f1fe74, 0x6130ebda, 0x5ead6eee, 0x1ee6c267, 0x31d7fb2a, 0x276b8311, 0xef09c222, 0x063bda6c, 0x6323ed6c, 0x661dc4f9, 0x4dfdfcb5, 0x584644e5, 0x2f436e17, 0x4c329091, 0xc3e2efc7, 0x455953f1, 0x27e1e0d6, 0x60ab2e1d, 0x7ab66ea6, 0x6789d2c9, 0x601f1cd5, 0xdb18c082, 0x69c7d79c, 0xdd82e314, 0x59a27df8, 0x8acbd77d, 0x7a1f8be2, 0x392df067, 0xf0fdd543, 0xc77f3335, 0x4674e487, 0xc2e057de, 0x793deca5, 0xc02f4967, 0x3cf38c02, 0x35adc436, 0x34177e11, 0xe0757b0b, 0xebafa4fb, 0x1e66c721, 0x10d167aa, 0x445169c8, 0x885a9350, 0x6b1deae6, 0x049e77d1, 0x3e779dbd, 0x39ac151f, 0x81e80d00, 0x46eb09b6, 0x905ee460, 0x74664584, 0x1c668bcf, 0x23aa7757, 0xe7a8de4e, 0x1dad13a0, 0xd555a2eb, 0xaa840f75, 0x373e7844, 0x806411c8, 0x22280e95, 0xea798173, 0x37be07b4, 0xc9c65753, 0xbb4b417b, 0xb466d36b, 0xf75a1acb, 0x725410ca, 0x36ccf2b9, 0x636f387a, 0x491951cf, 0x5aa8476f, 0x925a2164, 0xa45aa275, 0xe14ba1d3, 0xce092e11, 0xdee6473e, 0x30bc2dcd, 0x3b907d72, 0xad51a4c8, 0x4ad69b7d, 0xcdf179db, 0x0995a628, 0x3cdb094b, 0xa6eaef22, 0x04bbe7e3, 0x7605cc67, 0x1d37fe4b, 0xe1fdb734, 0xc4c95107, 0x50ec521b, 0xa1a5129f, 0x3bfecc56, 0x9c70c0f8, 0x2245828d, 0x22f93af1, 0x549b0087, 0x86b8fa03, 0x03420171, 0xbe31c4e2, 0x42a3abcd, 0xfdafb7d5, 0xd05ae3fa, 0x5577683a, 0xfbb54bca, 0x2b31e2d4, 0x5f3798b3, 0xb47de1da, 0xe9beb9d8, 0x3a97df14, 0xb563584f, 0xd12cdf20, 0x2a0a8053, 0x56fd3c7d, 0x750e0995, 0x9714667f, 0xf304fea9, 0xc5329fda, 0x59b7ffd5, 0xdeb09692, 0x4e4dc1be, 0x5cfb4d98, 0x12e9c5bb, 0xcabd99b8, 0x8e90145a, 0xbbe4db5a, 0xc5a240b8, 0xd23c2373, 0x48a2949a, 0xaf19981b, 0x8c2e99cd, 0x899a6cd9, 0xf8d4bf8d, 0xd839510b, 0x91570f09, 0x998a5d14, 0x2a71c6ec, 0x6e026e77, 0xc8bfdf32, 0x29f7e42f, 0x2558bcca, 0xc82ffd0f, 0x640115d6, 0x22feab97, 0xdc3175b1, 0x1805d50f, 0xeb5a3e20, 0xf74e8510, 0x45ffe225, 0xd7dd7a2d, 0x7278c074, 0x2b67a539, 0xbb8a8a4d, 0xab02f5e8, 0xd13878bb, 0xfe660fd6, 0xd160174e, 0xb0ec0055, 0x92b158fd, 0xd6a1d0f3, 0xaa1966f1, 0x70d9fefd, 0x60961f62, 0x2f68e81c, 0xf26450f0, 0x43bb1160, 0x141a66c6, 0x2d690508, 0xfe6d3e04, 0xad1a097e, 0xfbb595fe, 0xd8921368, 0xfd34d4b0, 0x10cad09c, 0xaf3ad32d, 0x3b139d5d, 0xb02d74c1, 0x5ee3f50a, 0x8c327b0e, 0x71cffc75, 0x215a04f4, 0x29ce8aec, 0x42df96d2, 0xa3288f79, 0xe30eb5e0, 0xfa6aace1, 0xb01067bf, 0xf5dec1bf, 0x708e203a, ], external_mu: [ 0xb007f182, 0x605a1141, 0x93369bfc, 0x9a6b8a50, 0x457ed4d8, 0x52e7291b, 0x1161e463, 0xb2d04ca3, 0x02efe87e, 0x5da85bc9, 0xc03e9b9e, 0x4f522d92, 0xf81643a5, 0x71fd0f9f, 0xea0cd0f3, 0x3bfcf86f, ], signature: [ 0xd1476e71, 0xe540e209, 0x6f507b9c, 0x085ca49f, 0xbf9e8671, 0x14c85d6c, 0x62e11e2d, 0x7c9e1104, 0x1564289f, 0x3dbfb579, 0x0a6a796d, 0x514baee7, 0xd8dab167, 0x7614a9d2, 0x479c8508, 0x52a7c1aa, 0xb0d53384, 0x7c83e34d, 0x49c185a6, 0x171d1ecf, 0x3d221a19, 0xa1a6dc94, 0x2be97791, 0x1d0754ef, 0xfc3d6a99, 0x20073b11, 0xdf3164bf, 0xe3e94a4f, 0xced8b19a, 0xd3a7be27, 0x624eb472, 0xab7cb030, 0xff322000, 0xf95e1eb6, 0x47aabcad, 0xb641f29c, 0x1cf768a7, 0xa4833d0f, 0x69f1a772, 0xff99d8d2, 0x71ed0454, 0xbef2030f, 0xb52ff8a6, 0xb61e8054, 0x5d5a9d09, 0xfddb1e2f, 0xf61b730a, 0xa50b7a0b, 0x968c464f, 0x2239509b, 0x72ab216c, 0x87d17acc, 0x922f61f1, 0x99b91619, 0x11cef6d2, 0xbb5e4a0f, 0x73c27ad5, 0x6b65bfeb, 0xa2c18b5f, 0xc3d205b2, 0x438f3f1d, 0x18a2069e, 0x52a75439, 0x78481f86, 0x191555f4, 0x27eb32ff, 0xc7b8392f, 0xfbe3009d, 0xba64d03e, 0xd9ac0b10, 0x8c422f18, 0xa3f6be30, 0xf5ffc0ea, 0x7335aa5b, 0x28513f91, 0x27331158, 0x1c2f08fd, 0xae378aa9, 0xad8970f9, 0x435f3115, 0x9b4629eb, 0x3e589fc9, 0x602cfb22, 0xc82c5917, 0xd9e9f7cf, 0x7c40c717, 0x2b9d56cf, 0x7fd4c3d5, 0x2beeebb1, 0xaa595ccb, 0x5aa8d387, 0xfdc712ac, 0x9e764710, 0xef812998, 0x60073cc1, 0x78b0d6d7, 0x0309c6b3, 0x1dabe820, 0xd0251d83, 0x5d1c1d25, 0x96d5cb12, 0xebdbf6de, 0x088c7ab1, 0x7d1a93ab, 0xf968a1ad, 0x15aa96e9, 0x157e3c60, 0x8d70ab83, 0x64ab4e45, 0x8d834eae, 0xfaf5e219, 0x34053a96, 0x3d2a192d, 0xba7b8288, 0xfa5d679d, 0x2c9614dc, 0xf596870a, 0x22327f29, 0x893a23f7, 0xf96f3c7b, 0xd5359101, 0xdb972eee, 0xac4793be, 0xe9d37258, 0xca9f72ae, 0x64f08df5, 0xd6a6eaa3, 0xf1ab7fa2, 0xea67018f, 0x6d27abac, 0xdd05c929, 0x280b3e17, 0xb98919a8, 0x8c177e0f, 0xd87ad086, 0xea3ab8fc, 0x2fd247f9, 0x46deb8a3, 0x1a441421, 0x457b698f, 0xf2d99fee, 0xdff5aec4, 0x6330935d, 0xb037fa8a, 0x87aa9c95, 0x7b195b58, 0x5c662bfb, 0x22fba96f, 0xc5161b24, 0x54c76d9b, 0xb2f07726, 0xee11f1a2, 0xd72bd48b, 0xf76c593a, 0x275b687c, 0xe81457f3, 0xc8ca5173, 0x212ec41c, 0x42a027e0, 0x5b5737b1, 0xfad4b26d, 0x756d4934, 0x83b2dc8d, 0x37c68f67, 0xce30b0f5, 0x7ee72d37, 0xa9a03ea6, 0x208eecaf, 0x821d6ee8, 0xfe7a809a, 0xba2c5683, 0x174bcbba, 0xd21e9a7e, 0xe687eb9a, 0xa5247a26, 0x3885622b, 0x051a281e, 0xf2a17817, 0x38b48396, 0x2e0a81d8, 0xa9cc20f8, 0xeea094d8, 0x244a79ad, 0x7743dfde, 0x7def2383, 0xce157521, 0x63e3e1e2, 0x45c1cd8e, 0x3b802787, 0x1300f275, 0x6fbffa6e, 0x68a69cec, 0x3c1dc66a, 0xc5a541f2, 0xa664c169, 0xc18b5c1f, 0x1fd12e4c, 0x6c364de7, 0x39c4c2ad, 0x89b41125, 0xc3d1f30c, 0xb1df20c8, 0xc391d355, 0x0e2c7e7f, 0x9d469bbb, 0x271ae745, 0x1dd7fe2b, 0x0bebefba, 0xa4eec71b, 0xaf684405, 0x5667bca7, 0x394d174b, 0xab6c1e7d, 0x22ad9d0f, 0x28ff808b, 0x67db03e9, 0xfc68b0ff, 0x6cbf19c1, 0x08b3a9b3, 0xba897fed, 0xcbe1e6a8, 0xd6657138, 0x39a867c9, 0x23fbda57, 0x30181912, 0xfd6922e6, 0x2de738d2, 0xf3e896c1, 0x47bdc3c2, 0xd6c4ee6d, 0x3435d738, 0x7bd5ec47, 0xcd2133d4, 0xb08978d3, 0x49ba5418, 0x002186b8, 0x5e864f38, 0x81f86378, 0x8bf33e48, 0xf69f4f94, 0xdcdcf325, 0x6624ed86, 0x04967421, 0x0632d587, 0x4374042f, 0x5a8d62bf, 0xb6916d69, 0x7375be21, 0x26cca817, 0x5ec7c575, 0x508c0c84, 0x2e55231e, 0x76d19d19, 0x1d181a4a, 0xac514f2c, 0x12b616f4, 0x5ab27d01, 0x769da6c0, 0xc2f8689f, 0xd7c7c6e8, 0x06a6591d, 0x9d9c00ea, 0xa0d8ebb1, 0x13bf1c60, 0x5dbb01d0, 0x3ba3f19f, 0x0b0b189c, 0xac37732e, 0xc010c203, 0x31865af8, 0xc86be617, 0xd95da317, 0x0fa45a6e, 0x0ef83892, 0x851a8b42, 0x612d307f, 0x00525f48, 0xa1d261fb, 0xb288d6dc, 0x670194ff, 0xf92cac1a, 0xbc58b617, 0xee9ff570, 0x21a0807c, 0x4a8f5f47, 0xbeb77b33, 0xf762faee, 0xe51f51a2, 0xa01c6629, 0xa41c6e49, 0xc82dec5a, 0x216c592d, 0x633839a3, 0x8065b344, 0xc9338356, 0x01e7d7b6, 0x0d0c0748, 0xa70ba77a, 0x0c397e22, 0xbf4a1266, 0xf23eacaf, 0x29972b6b, 0x570bd120, 0x80c50403, 0x0b7c64eb, 0xe1a2c60e, 0x5f15084e, 0xd75190eb, 0x15f9e877, 0xc048420d, 0x4dcd78c4, 0x4a8af446, 0xd0ec614c, 0x6b8c5f4f, 0x56aded83, 0xda50e9d8, 0x293a0305, 0x081fbca5, 0x87aded27, 0xe8939071, 0x2ebc29ba, 0xb7e5baeb, 0x06fa3850, 0x4655bf52, 0x6b395a89, 0xfaea1fb2, 0x208af1ea, 0xaec08614, 0xde174060, 0x8087eb2d, 0xdbe5175d, 0x7c3df14f, 0x49f7d0f8, 0x640baf6f, 0x857f5112, 0x956aa0cb, 0xf8f491f9, 0x99eaaea5, 0x673367d8, 0x72d4ab26, 0xe7986b38, 0xc40eb3fd, 0x9b7a6a8f, 0x15bf53f9, 0x8a9efa70, 0x71f76f25, 0x54e61eda, 0xfe5d102c, 0x62e6d235, 0x03720b1d, 0x40432e6d, 0xa32ad988, 0x5b913801, 0x7fab9d90, 0x79d2279b, 0xb9e5fbfa, 0x01848bd2, 0x552ae89b, 0x92262428, 0x07f8449a, 0x98e60d55, 0xd61101d4, 0x0e07e33c, 0xeaae6cfd, 0x812616fc, 0x83a1e6a3, 0x8ad5b388, 0x1b06d6a9, 0x672162f1, 0x6a009f46, 0x41762b61, 0x069041f8, 0xaee86862, 0x2916d21e, 0xeeb5edf9, 0xeb722f6b, 0xe61c7dd7, 0x5085e24a, 0x72bab09d, 0x88cb3b85, 0xabb5272f, 0x277bb498, 0xdd8b772d, 0xf7758b66, 0x5264ded1, 0x2138668e, 0x623164e5, 0x9879a822, 0xa8be6351, 0x339286ec, 0x9966ee94, 0x83d553f5, 0x8e83bb42, 0x9a679b93, 0xdba891f4, 0xa2fe1295, 0x01c0e644, 0xe0830b21, 0xcf3afbe7,
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
true
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/keyvault_tests.rs
drivers/test-fw/src/bin/keyvault_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: keyvault_tests.rs Abstract: File contains test cases for Key-Vault API --*/ #![no_std] #![no_main] use caliptra_drivers::{KeyId, KeyUsage, KeyVault}; use caliptra_registers::kv::KvReg; use caliptra_test_harness::test_suite; const KEY_IDS: [KeyId; 24] = [ KeyId::KeyId0, KeyId::KeyId1, KeyId::KeyId2, KeyId::KeyId3, KeyId::KeyId4, KeyId::KeyId5, KeyId::KeyId6, KeyId::KeyId7, KeyId::KeyId8, KeyId::KeyId9, KeyId::KeyId10, KeyId::KeyId11, KeyId::KeyId12, KeyId::KeyId13, KeyId::KeyId14, KeyId::KeyId15, KeyId::KeyId16, KeyId::KeyId17, KeyId::KeyId18, KeyId::KeyId19, KeyId::KeyId20, KeyId::KeyId21, KeyId::KeyId22, KeyId::KeyId23, ]; fn test_write_lock_and_erase_keys() { let mut vault = unsafe { KeyVault::new(KvReg::new()) }; for key_id in KEY_IDS { assert!(vault.erase_key(key_id).is_ok()); // Set write lock. assert!(!vault.key_write_lock(key_id)); vault.set_key_write_lock(key_id); assert!(vault.key_write_lock(key_id)); // Test erasing key. This should fail. assert!(vault.erase_key(key_id).is_err()); } } fn test_erase_all_keys() { let mut vault = unsafe { KeyVault::new(KvReg::new()) }; vault.erase_all_keys(); } fn test_read_key_usage() { let mut vault = unsafe { KeyVault::new(KvReg::new()) }; for key_id in KEY_IDS { assert_eq!(vault.key_usage(key_id), KeyUsage(0)); } } fn test_use_lock() { let mut vault = unsafe { KeyVault::new(KvReg::new()) }; for key_id in KEY_IDS { assert!(!vault.key_use_lock(key_id)); vault.set_key_use_lock(key_id); assert!(vault.key_use_lock(key_id)); } } fn test_write_protection_stickiness() { let mut vault = unsafe { KeyVault::new(KvReg::new()) }; for key_id in KEY_IDS { assert!(vault.key_write_lock(key_id)); vault.clear_key_write_lock(key_id); assert!(vault.key_write_lock(key_id)); } } fn test_use_protection_stickiness() { let mut vault = unsafe { KeyVault::new(KvReg::new()) }; for key_id in KEY_IDS { assert!(vault.key_use_lock(key_id)); vault.clear_key_use_lock(key_id); assert!(vault.key_use_lock(key_id)); } } // Maintain the order of the tests. test_suite! { test_write_lock_and_erase_keys, test_erase_all_keys, test_read_key_usage, test_use_lock, test_write_protection_stickiness, test_use_protection_stickiness, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/sha512_tests.rs
drivers/test-fw/src/bin/sha512_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: sha512_tests.rs Abstract: File contains test cases for SHA-512 API --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::sha2_512_384::Sha2DigestOpTrait; use caliptra_drivers::{Array4x16, Sha2_512_384}; use caliptra_kat::Sha512Kat; use caliptra_registers::sha512::Sha512Reg; use caliptra_test_harness::test_suite; fn test_digest0() { let mut sha2 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected = Array4x16::new([ 0xcf83e135, 0x7eefb8bd, 0xf1542850, 0xd66d8007, 0xd620e405, 0x0b5715dc, 0x83f4a921, 0xd36ce9ce, 0x47d0d13c, 0x5d85f2b0, 0xff8318d2, 0x877eec2f, 0x63b931bd, 0x47417a81, 0xa538327a, 0xf927da3e, ]); let data = &[]; let digest = sha2.sha512_digest(data).unwrap(); assert_eq!(digest, expected); } fn test_digest1() { let mut sha2 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected = Array4x16::new([ 0xddaf35a1, 0x93617aba, 0xcc417349, 0xae204131, 0x12e6fa4e, 0x89a97ea2, 0x0a9eeee6, 0x4b55d39a, 0x2192992a, 0x274fc1a8, 0x36ba3c23, 0xa3feebbd, 0x454d4423, 0x643ce80e, 0x2a9ac94f, 0xa54ca49f, ]); let data = "abc".as_bytes(); let digest = sha2.sha512_digest(data.into()).unwrap(); assert_eq!(digest, expected); } fn test_digest2() { let mut sha2 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected = Array4x16::new([ 0x204a8fc6, 0xdda82f0a, 0x0ced7beb, 0x8e08a416, 0x57c16ef4, 0x68b228a8, 0x279be331, 0xa703c335, 0x96fd15c1, 0x3b1b07f9, 0xaa1d3bea, 0x57789ca0, 0x31ad85c7, 0xa71dd703, 0x54ec6312, 0x38ca3445, ]); let data = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".as_bytes(); let digest = sha2.sha512_digest(data.into()).unwrap(); assert_eq!(digest, expected); } fn test_digest3() { let mut sha2 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected = Array4x16::new([ 0x8e959b75, 0xdae313da, 0x8cf4f728, 0x14fc143f, 0x8f7779c6, 0xeb9f7fa1, 0x7299aead, 0xb6889018, 0x501d289e, 0x4900f7e4, 0x331b99de, 0xc4b5433a, 0xc7d329ee, 0xb6dd2654, 0x5e96e55b, 0x874be909, ]); let data = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".as_bytes(); let digest = sha2.sha512_digest(data.into()).unwrap(); assert_eq!(digest, expected); } fn test_op0() { let mut sha2 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected = Array4x16::new([ 0xcf83e135, 0x7eefb8bd, 0xf1542850, 0xd66d8007, 0xd620e405, 0x0b5715dc, 0x83f4a921, 0xd36ce9ce, 0x47d0d13c, 0x5d85f2b0, 0xff8318d2, 0x877eec2f, 0x63b931bd, 0x47417a81, 0xa538327a, 0xf927da3e, ]); let mut digest = Array4x16::default(); let digest_op = sha2.sha512_digest_init().unwrap(); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, expected); } fn test_op1() { let mut sha2 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected = Array4x16::new([ 0xddaf35a1, 0x93617aba, 0xcc417349, 0xae204131, 0x12e6fa4e, 0x89a97ea2, 0x0a9eeee6, 0x4b55d39a, 0x2192992a, 0x274fc1a8, 0x36ba3c23, 0xa3feebbd, 0x454d4423, 0x643ce80e, 0x2a9ac94f, 0xa54ca49f, ]); let data = "abc".as_bytes(); let mut digest = Array4x16::default(); let mut digest_op = sha2.sha512_digest_init().unwrap(); assert!(digest_op.update(data).is_ok()); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, expected); } fn test_op2() { let mut sha2 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected = Array4x16::new([ 0x204a8fc6, 0xdda82f0a, 0x0ced7beb, 0x8e08a416, 0x57c16ef4, 0x68b228a8, 0x279be331, 0xa703c335, 0x96fd15c1, 0x3b1b07f9, 0xaa1d3bea, 0x57789ca0, 0x31ad85c7, 0xa71dd703, 0x54ec6312, 0x38ca3445, ]); let data = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".as_bytes(); let mut digest = Array4x16::default(); let mut digest_op = sha2.sha512_digest_init().unwrap(); assert!(digest_op.update(data).is_ok()); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, expected); } fn test_op3() { let mut sha2 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; let expected = Array4x16::new([ 0x8e959b75, 0xdae313da, 0x8cf4f728, 0x14fc143f, 0x8f7779c6, 0xeb9f7fa1, 0x7299aead, 0xb6889018, 0x501d289e, 0x4900f7e4, 0x331b99de, 0xc4b5433a, 0xc7d329ee, 0xb6dd2654, 0x5e96e55b, 0x874be909, ]); let data = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".as_bytes(); let mut digest = Array4x16::default(); let mut digest_op = sha2.sha512_digest_init().unwrap(); assert!(digest_op.update(data).is_ok()); let actual = digest_op.finalize(&mut digest); assert!(actual.is_ok()); assert_eq!(digest, expected); } fn test_kat() { // Init CFI CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut sha512 = unsafe { Sha2_512_384::new(Sha512Reg::new()) }; assert!(Sha512Kat::default().execute(&mut sha512).is_ok()); } test_suite! { test_kat, test_digest0, test_digest1, test_digest2, test_digest3, test_op0, test_op1, test_op2, test_op3, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/ocp_lock_warm_reset_test.rs
drivers/test-fw/src/bin/ocp_lock_warm_reset_test.rs
/*++ Licensed under the Apache-2.0 license. File Name: ocp_lock_warm_reset_test.rs Abstract: File contains test cases for OCP LOCK after a warm reset. --*/ #![no_std] #![no_main] use caliptra_cfi_lib::CfiCounter; use caliptra_drivers::{ hmac_kdf, HmacKey, HmacMode, HmacTag, KeyId, KeyReadArgs, KeyUsage, KeyWriteArgs, LEArray4x16, ResetReason, }; use caliptra_drivers_test_bin::{ kv_release, populate_slot, TestRegisters, ENCRYPTED_MEK, OCP_LOCK_WARM_RESET_MAGIC_BOOT_STATUS, }; use caliptra_registers::soc_ifc::SocIfcReg; use caliptra_test_harness::test_suite; test_suite! { test_ocp_lock_warm_reset, } fn test_ocp_lock_warm_reset() { CfiCounter::reset(&mut || Ok((0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef))); let mut test_regs = TestRegisters::default(); assert!(test_regs.soc.ocp_lock_enabled()); let reason = test_regs.soc.reset_reason(); match reason { ResetReason::ColdReset => { cold_reset_flow(&mut test_regs); } ResetReason::WarmReset => { warm_reset_flow(&mut test_regs); } _ => panic!("Unexpected reset reason"), } } fn warm_reset_flow(test_regs: &mut TestRegisters) { assert!(test_regs.soc.ocp_lock_get_lock_in_progress()); let fuse_bank = test_regs.soc.fuse_bank().ocp_hek_seed(); // Check hard coded hek seed from test MCU ROM. assert_eq!(fuse_bank, [0xABDE_FC82u32; 8].into()); // Write lock should be lost on warm reset assert!(!test_regs.kv.key_write_lock(KeyId::KeyId16)); assert!(!test_regs.kv.key_write_lock(KeyId::KeyId22)); // MDK & HEK should still be in KVs. test_regs .aes .aes_256_ecb_decrypt_kv(&LEArray4x16::from(ENCRYPTED_MEK)) .unwrap(); // Check that we still derive the same MEK kv_release(test_regs); // Need to release model test_regs.soc.set_mcu_firmware_ready(); } fn cold_reset_flow(test_regs: &mut TestRegisters) -> ! { ocp_lock_flow(test_regs); let mut soc_ifc = unsafe { SocIfcReg::new() }; // Signal test harness we are ready for reset loop { soc_ifc .regs_mut() .cptra_boot_status() .write(|_| OCP_LOCK_WARM_RESET_MAGIC_BOOT_STATUS); } } fn ocp_lock_flow(test_regs: &mut TestRegisters) { let cdi_slot = HmacKey::Key(KeyReadArgs::new(KeyId::KeyId3)); let mdk_slot = HmacTag::Key(KeyWriteArgs::from(KeyWriteArgs::new( KeyId::KeyId16, KeyUsage::default().set_aes_key_en(), ))); populate_slot( &mut test_regs.hmac, &mut test_regs.trng, KeyId::KeyId3, // CDI Slot KeyUsage::default().set_hmac_key_en(), ) .unwrap(); hmac_kdf( &mut test_regs.hmac, cdi_slot, b"OCP_LOCK_MDK", None, &mut test_regs.trng, mdk_slot, HmacMode::Hmac512, ) .unwrap(); test_regs.kv.set_key_write_lock(KeyId::KeyId16); test_regs.kv.set_key_write_lock(KeyId::KeyId22); let fuse_bank = test_regs.soc.fuse_bank().ocp_hek_seed(); assert_eq!(fuse_bank, [0xABDE_FC82u32; 8].into()); test_regs.soc.ocp_lock_set_lock_in_progress(); assert!(test_regs.soc.ocp_lock_get_lock_in_progress()); test_regs .aes .aes_256_ecb_decrypt_kv(&LEArray4x16::from(ENCRYPTED_MEK)) .unwrap(); kv_release(test_regs); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/persistent_tests.rs
drivers/test-fw/src/bin/persistent_tests.rs
// Licensed under the Apache-2.0 license #![no_std] #![no_main] use caliptra_drivers::{PersistentData, PersistentDataAccessor}; use caliptra_test_harness::test_suite; fn test_persistent_data_layout() { PersistentData::assert_matches_layout(); } fn test_read_write() { { let mut accessor = unsafe { PersistentDataAccessor::new() }; accessor.get_mut().rom.fht.fht_marker = 0xfe9cd1c0; } { let accessor = unsafe { PersistentDataAccessor::new() }; assert_eq!(accessor.get().rom.fht.fht_marker, 0xfe9cd1c0); } } test_suite! { test_persistent_data_layout, test_read_write, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/lms_24_tests.rs
drivers/test-fw/src/bin/lms_24_tests.rs
/*++ Licensed under the Apache-2.0 license. File Name: lms_24_tests.rs Abstract: File contains test cases for LMS signature verification using SHA256/192. --*/ #![no_std] #![no_main] use caliptra_drivers::{get_lms_parameters, HashValue, Lms, LmsResult, Sha256}; use caliptra_error::CaliptraError; use caliptra_lms_types::{ bytes_to_words_6, LmotsAlgorithmType, LmotsSignature, LmsAlgorithmType, LmsIdentifier, LmsPublicKey, LmsSignature, }; use caliptra_registers::sha256::Sha256Reg; use caliptra_test_harness::test_suite; use zerocopy::{BigEndian, LittleEndian, U32}; fn test_get_lms_parameters() { // Full size SHA256 hashes let (width, height) = get_lms_parameters(LmsAlgorithmType::LmsSha256N32H5).unwrap(); assert_eq!(32, width); assert_eq!(5, height); let (width, height) = get_lms_parameters(LmsAlgorithmType::LmsSha256N32H10).unwrap(); assert_eq!(32, width); assert_eq!(10, height); let (width, height) = get_lms_parameters(LmsAlgorithmType::LmsSha256N32H15).unwrap(); assert_eq!(32, width); assert_eq!(15, height); let (width, height) = get_lms_parameters(LmsAlgorithmType::LmsSha256N32H20).unwrap(); assert_eq!(32, width); assert_eq!(20, height); let (width, height) = get_lms_parameters(LmsAlgorithmType::LmsSha256N32H25).unwrap(); assert_eq!(32, width); assert_eq!(25, height); // Truncated 192 bit SHA256 hashes let (width, height) = get_lms_parameters(LmsAlgorithmType::LmsSha256N24H5).unwrap(); assert_eq!(24, width); assert_eq!(5, height); let (width, height) = get_lms_parameters(LmsAlgorithmType::LmsSha256N24H10).unwrap(); assert_eq!(24, width); assert_eq!(10, height); let (width, height) = get_lms_parameters(LmsAlgorithmType::LmsSha256N24H15).unwrap(); assert_eq!(24, width); assert_eq!(15, height); let (width, height) = get_lms_parameters(LmsAlgorithmType::LmsSha256N24H20).unwrap(); assert_eq!(24, width); assert_eq!(20, height); let (width, height) = get_lms_parameters(LmsAlgorithmType::LmsSha256N24H25).unwrap(); assert_eq!(24, width); assert_eq!(25, height); } // test case from https://datatracker.ietf.org/doc/html/rfc8554#section-3.1.3 fn test_coefficient() { let input_value = [0x12u8, 0x34u8]; let result = Lms::default().coefficient(&input_value, 7, 1).unwrap(); assert_eq!(result, 0); let result = Lms::default().coefficient(&input_value, 0, 4).unwrap(); assert_eq!(result, 1); } fn test_hash_message_24() { let mut sha256 = unsafe { Sha256::new(Sha256Reg::new()) }; let message: [u8; 33] = [ 116, 104, 105, 115, 32, 105, 115, 32, 116, 104, 101, 32, 109, 101, 115, 115, 97, 103, 101, 32, 73, 32, 119, 97, 110, 116, 32, 115, 105, 103, 110, 101, 100, ]; let lms_identifier: LmsIdentifier = [ 102, 40, 233, 90, 126, 166, 161, 73, 107, 57, 114, 28, 121, 57, 28, 123, ]; let nonce: [U32<LittleEndian>; 6] = bytes_to_words_6([ 108, 201, 169, 93, 130, 206, 214, 173, 223, 138, 178, 150, 192, 86, 115, 139, 157, 213, 182, 55, 196, 22, 212, 216, ]); let q: u32 = 0; let q_str = q.to_be_bytes(); let expected_hash = HashValue::from([ 175, 160, 9, 71, 29, 26, 61, 20, 90, 217, 142, 152, 112, 68, 51, 17, 154, 191, 74, 150, 161, 238, 102, 161, ]); let hash = Lms::default() .hash_message(&mut sha256, &message, &lms_identifier, &q_str, &nonce) .unwrap(); assert_eq!(expected_hash, hash); } fn test_lms_24_height_15() { let mut sha256 = unsafe { Sha256::new(Sha256Reg::new()) }; const MESSAGE: [u8; 33] = [ 116, 104, 105, 115, 32, 105, 115, 32, 116, 104, 101, 32, 109, 101, 115, 115, 97, 103, 101, 32, 73, 32, 119, 97, 110, 116, 32, 115, 105, 103, 110, 101, 100, ]; const LMS_IDENTIFIER: LmsIdentifier = [ 158, 20, 249, 74, 242, 177, 66, 175, 101, 91, 176, 36, 80, 31, 240, 7, ]; const Q: U32<BigEndian> = U32::ZERO; const LMOTS_TYPE: LmotsAlgorithmType = LmotsAlgorithmType::LmotsSha256N24W4; const LMS_TYPE: LmsAlgorithmType = LmsAlgorithmType::LmsSha256N24H15; const LMS_PUBLIC_HASH: [U32<LittleEndian>; 6] = bytes_to_words_6([ 0x03, 0x2a, 0xa2, 0xbd, 0x9b, 0x31, 0xe9, 0xbd, 0x33, 0x4b, 0x46, 0x2e, 0x27, 0x79, 0x20, 0x75, 0xbd, 0xad, 0xdd, 0xae, 0xf9, 0xed, 0xb1, 0x24, ]); const NONCE: [U32<LittleEndian>; 6] = bytes_to_words_6([ 0xb4, 0x24, 0x09, 0xdb, 0xdd, 0x4a, 0x1c, 0x49, 0xfc, 0x79, 0x37, 0x94, 0x75, 0xe9, 0xc7, 0x67, 0x1c, 0x7f, 0x51, 0x53, 0xf7, 0x53, 0x5a, 0xc4, ]); const Y: [[U32<LittleEndian>; 6]; 51] = [ bytes_to_words_6([ 0x72, 0x53, 0xaf, 0x69, 0xc8, 0x5a, 0x5b, 0x96, 0x10, 0x55, 0xcc, 0x03, 0xb7, 0xe1, 0xee, 0x83, 0xab, 0xb0, 0x32, 0xb3, 0x14, 0x58, 0xfa, 0x69, ]), bytes_to_words_6([ 0x00, 0xd4, 0xf4, 0xfc, 0xda, 0x35, 0x7d, 0xc9, 0xa9, 0x44, 0x10, 0x23, 0x3d, 0x4b, 0x00, 0xb4, 0xb9, 0x2c, 0xa8, 0x6e, 0xf0, 0xf8, 0xfd, 0x13, ]), bytes_to_words_6([ 0xd2, 0xad, 0x7e, 0x03, 0xec, 0x32, 0xc0, 0x59, 0x8f, 0x9b, 0x64, 0xfd, 0x8c, 0x6f, 0x82, 0x79, 0xf7, 0x8e, 0x88, 0xe7, 0x7b, 0x4c, 0xdb, 0x89, ]), bytes_to_words_6([ 0x6c, 0xe4, 0x9e, 0x66, 0x3b, 0x32, 0x6b, 0x29, 0x1d, 0xe5, 0xc9, 0xdb, 0xdf, 0xab, 0x05, 0x68, 0x1d, 0xb5, 0x86, 0x68, 0x1e, 0x80, 0xe6, 0xaf, ]), bytes_to_words_6([ 0xba, 0x95, 0x8f, 0xbe, 0x1c, 0x83, 0xbe, 0x4e, 0x1a, 0xd2, 0x3f, 0x0e, 0x0e, 0x97, 0xa6, 0xb0, 0xe8, 0x00, 0xf3, 0xce, 0x97, 0xb5, 0xfc, 0xb0, ]), bytes_to_words_6([ 0x94, 0x9e, 0x57, 0xed, 0x65, 0xb9, 0x5c, 0x2c, 0xb9, 0xbb, 0x4c, 0x84, 0x4e, 0x4e, 0x4c, 0xe3, 0x1f, 0x63, 0xf1, 0x2b, 0x01, 0x5d, 0x35, 0xbc, ]), bytes_to_words_6([ 0xad, 0xef, 0xb1, 0xee, 0x3a, 0xb2, 0xc4, 0x6d, 0x0c, 0x3b, 0x52, 0x4d, 0x92, 0x40, 0xed, 0xf1, 0xcc, 0xc7, 0x09, 0xa7, 0xf9, 0x78, 0x55, 0x13, ]), bytes_to_words_6([ 0xf7, 0x8c, 0xf3, 0xcc, 0x15, 0xe1, 0xb9, 0xb1, 0x71, 0xa9, 0x2f, 0x26, 0x33, 0x47, 0x59, 0x5c, 0x24, 0xf2, 0xd5, 0xbe, 0xae, 0xa6, 0x97, 0x93, ]), bytes_to_words_6([ 0x4a, 0x52, 0x99, 0xfe, 0x4c, 0x7e, 0x6c, 0x83, 0x30, 0x9f, 0x98, 0xc0, 0x5e, 0xc3, 0xd6, 0x27, 0x9d, 0x33, 0x50, 0x81, 0xef, 0xa7, 0x48, 0x31, ]), bytes_to_words_6([ 0x6b, 0x34, 0x75, 0x7d, 0xf9, 0x1a, 0x72, 0x39, 0xaf, 0xf2, 0x6b, 0x46, 0x5e, 0xc4, 0x80, 0x9e, 0x22, 0x22, 0x9b, 0xee, 0x79, 0xac, 0x90, 0x11, ]), bytes_to_words_6([ 0xac, 0xb3, 0xee, 0xa6, 0x42, 0x30, 0xb3, 0xd4, 0xeb, 0x54, 0x1a, 0xad, 0xa7, 0xb5, 0x6d, 0x44, 0x15, 0x93, 0x81, 0x7a, 0x1c, 0x0a, 0x47, 0x3b, ]), bytes_to_words_6([ 0x02, 0x02, 0x95, 0xb8, 0x60, 0x41, 0x64, 0xb9, 0xbe, 0xdb, 0x11, 0xef, 0xb0, 0x39, 0x43, 0x9e, 0x88, 0xa3, 0x0e, 0x5d, 0x9a, 0xf4, 0x80, 0x69, ]), bytes_to_words_6([ 0x16, 0xca, 0xa9, 0x22, 0xec, 0x5d, 0x33, 0x0b, 0x09, 0x54, 0xa3, 0x17, 0x8d, 0x1c, 0xd8, 0xbd, 0xd2, 0x8c, 0x64, 0xfc, 0x07, 0x9e, 0xd8, 0x23, ]), bytes_to_words_6([ 0xbc, 0x7a, 0xbb, 0x42, 0x76, 0xda, 0x10, 0x58, 0xa2, 0x3c, 0xf4, 0x00, 0x08, 0x63, 0xea, 0x20, 0x04, 0x5b, 0xe2, 0xf2, 0xb8, 0xdc, 0x7e, 0xcf, ]), bytes_to_words_6([ 0x0b, 0x30, 0xc2, 0x12, 0x8e, 0xa5, 0x37, 0xb9, 0x0e, 0x76, 0x4b, 0x3a, 0x49, 0x79, 0xd6, 0x6d, 0x67, 0x30, 0x71, 0x90, 0x90, 0xdb, 0x89, 0x5b, ]), bytes_to_words_6([ 0x61, 0xbb, 0xc3, 0x6a, 0x85, 0x37, 0x69, 0x4c, 0x23, 0x4f, 0x5a, 0x11, 0xe5, 0xc3, 0x0d, 0xa5, 0x39, 0x7b, 0x7f, 0x7c, 0x87, 0xf4, 0xec, 0xdc, ]), bytes_to_words_6([ 0xd6, 0x63, 0x57, 0xdb, 0xa0, 0x08, 0xa1, 0x87, 0x8a, 0x89, 0x2a, 0x58, 0x0c, 0x5a, 0x72, 0x7a, 0xf2, 0x03, 0x16, 0x1c, 0x13, 0x54, 0x14, 0xc9, ]), bytes_to_words_6([ 0x3e, 0xe0, 0xf7, 0xa9, 0x34, 0xc5, 0xd2, 0x2b, 0xf5, 0x93, 0x05, 0x03, 0xaa, 0xd9, 0xb8, 0x6d, 0x79, 0x7e, 0xf9, 0xea, 0xce, 0x0d, 0x39, 0x9e, ]), bytes_to_words_6([ 0x6f, 0x80, 0xb7, 0x3e, 0x9a, 0x46, 0xa9, 0x23, 0x11, 0x09, 0xa1, 0x54, 0x1d, 0xf7, 0x21, 0x36, 0x13, 0x87, 0x3f, 0x73, 0xb6, 0xb9, 0xb8, 0xca, ]), bytes_to_words_6([ 0x7e, 0x66, 0xc4, 0x94, 0x75, 0xd8, 0xc1, 0x7e, 0xea, 0xf4, 0xa2, 0x2b, 0x1e, 0x9c, 0x0f, 0x74, 0xfc, 0x5a, 0xb0, 0xe2, 0x16, 0xba, 0x54, 0x75, ]), bytes_to_words_6([ 0xb0, 0x82, 0x56, 0x96, 0x36, 0xdc, 0xbf, 0xfd, 0xd8, 0xea, 0x96, 0x55, 0xb7, 0x8b, 0x3a, 0x99, 0x1d, 0x32, 0xd7, 0xf2, 0x96, 0x7a, 0xd8, 0x74, ]), bytes_to_words_6([ 0xd5, 0x39, 0x88, 0x92, 0xfb, 0xd4, 0x5d, 0xba, 0x66, 0xa7, 0xc5, 0x01, 0x46, 0xf2, 0x29, 0x7c, 0x3c, 0x27, 0xac, 0xd8, 0x8c, 0xe0, 0x10, 0x8b, ]), bytes_to_words_6([ 0xd1, 0x50, 0x2d, 0x6a, 0x79, 0xb4, 0x93, 0xc5, 0x35, 0x00, 0xc2, 0x36, 0xba, 0x26, 0xab, 0xad, 0x8f, 0x57, 0x91, 0x23, 0xe6, 0xc1, 0x0e, 0xc9, ]), bytes_to_words_6([ 0xf4, 0xa0, 0x60, 0xd3, 0xe2, 0x85, 0x2b, 0x9a, 0xd9, 0x7f, 0xe4, 0xb4, 0x58, 0x70, 0x33, 0x8a, 0x3f, 0xcc, 0x47, 0xb1, 0xf1, 0xd1, 0x0c, 0xd2, ]), bytes_to_words_6([ 0xfd, 0x28, 0x15, 0xbd, 0x21, 0xdd, 0x0a, 0xea, 0x78, 0xac, 0x0b, 0xe6, 0xd9, 0xb1, 0x34, 0xe0, 0xc2, 0x50, 0x73, 0xd9, 0x42, 0x5b, 0xea, 0x4e, ]), bytes_to_words_6([ 0x8e, 0x2d, 0x99, 0x28, 0xf2, 0x3e, 0x8b, 0xf3, 0xed, 0x62, 0x8f, 0xf8, 0x88, 0x39, 0x6e, 0x74, 0x9e, 0x55, 0xae, 0x66, 0xf5, 0x9a, 0x84, 0x6c, ]), bytes_to_words_6([ 0x7f, 0xc4, 0x7b, 0x8b, 0x66, 0xd5, 0xd3, 0xdc, 0x47, 0xac, 0x7f, 0x28, 0x58, 0xb9, 0x3b, 0xa0, 0x46, 0xa4, 0x6e, 0x82, 0x6b, 0x8f, 0x3a, 0xa9, ]), bytes_to_words_6([ 0x6a, 0x9b, 0x98, 0x75, 0x46, 0x04, 0xea, 0x7c, 0xbc, 0xc8, 0xb9, 0xb4, 0xba, 0xb9, 0x43, 0xda, 0xcf, 0x60, 0x21, 0x9c, 0xb1, 0xd4, 0xed, 0x67, ]), bytes_to_words_6([ 0x1c, 0x32, 0x0a, 0xf7, 0xae, 0x84, 0x83, 0x75, 0xeb, 0x9c, 0xc7, 0xb0, 0xec, 0x30, 0x45, 0xbe, 0x79, 0xfd, 0x11, 0x7c, 0xcd, 0x26, 0x97, 0x5e, ]), bytes_to_words_6([ 0x3c, 0x2d, 0x4a, 0x35, 0x2e, 0x10, 0x3c, 0x3d, 0x76, 0x89, 0xb3, 0xac, 0xf2, 0xcc, 0x56, 0xd0, 0xed, 0x7a, 0x6f, 0x58, 0x76, 0xec, 0x40, 0x96, ]), bytes_to_words_6([ 0x1a, 0x5a, 0xad, 0x8c, 0xe1, 0x08, 0xa7, 0xcb, 0x3b, 0xf1, 0x1b, 0x01, 0x1c, 0xb6, 0x0e, 0x47, 0xf3, 0x45, 0x87, 0xf3, 0xf7, 0x95, 0x47, 0x72, ]), bytes_to_words_6([ 0x86, 0xe5, 0x24, 0xa6, 0x0d, 0xfa, 0xef, 0x82, 0xfc, 0x6c, 0x8d, 0xa1, 0x81, 0x95, 0x85, 0x58, 0x93, 0x27, 0xf6, 0x29, 0x69, 0xc9, 0x77, 0xb7, ]), bytes_to_words_6([ 0xe9, 0x4a, 0xe9, 0xbf, 0xae, 0x42, 0x14, 0x93, 0xfc, 0xb7, 0x14, 0x38, 0x47, 0x2f, 0x0d, 0x03, 0x7c, 0x82, 0x43, 0xe1, 0x6e, 0x29, 0x75, 0x3f, ]), bytes_to_words_6([ 0xd4, 0x9c, 0xc3, 0xdd, 0xc5, 0x59, 0x7b, 0x23, 0x87, 0xe7, 0x03, 0xa9, 0x9a, 0xc9, 0x97, 0x73, 0x13, 0xfa, 0xa7, 0x19, 0x5b, 0x41, 0xda, 0x72, ]), bytes_to_words_6([ 0x6c, 0xe0, 0x02, 0xa4, 0xe9, 0x27, 0x72, 0xf4, 0xea, 0x74, 0xf4, 0xe9, 0x09, 0xbf, 0x80, 0x28, 0xfd, 0xd7, 0x7f, 0x8a, 0x09, 0xc0, 0x60, 0x51, ]), bytes_to_words_6([ 0x19, 0xc7, 0xb9, 0x88, 0x70, 0x58, 0xd5, 0x45, 0x6b, 0xba, 0x3c, 0x62, 0x80, 0x27, 0xc8, 0x8d, 0xf7, 0xa8, 0xf7, 0xa9, 0xfe, 0xf5, 0xa6, 0x41, ]), bytes_to_words_6([ 0x9a, 0x5b, 0x69, 0xed, 0xc4, 0xac, 0x81, 0x98, 0x1f, 0xeb, 0x40, 0xb8, 0xc7, 0xa9, 0xa7, 0x6d, 0x1c, 0x5a, 0x81, 0x72, 0x17, 0xcb, 0xa8, 0xf8, ]), bytes_to_words_6([ 0x5c, 0x67, 0xb8, 0x99, 0x6f, 0x89, 0xda, 0x71, 0x20, 0xae, 0x5e, 0xe6, 0x2c, 0x16, 0xab, 0x59, 0x1c, 0x81, 0xb5, 0x82, 0xc6, 0x88, 0x6f, 0x6e, ]), bytes_to_words_6([ 0x7f, 0xca, 0xf9, 0x20, 0xad, 0xd6, 0xe6, 0x0d, 0x89, 0xb9, 0xf9, 0xa1, 0x32, 0xcf, 0x69, 0xbb, 0xf8, 0x73, 0xf5, 0x80, 0xc9, 0x69, 0x63, 0xf4, ]), bytes_to_words_6([ 0x01, 0x9d, 0x0d, 0x47, 0x23, 0xdd, 0xc6, 0x64, 0xd7, 0x7d, 0xcc, 0x4d, 0x5f, 0x5b, 0x6d, 0x14, 0xa6, 0x9a, 0xe2, 0x2b, 0x36, 0x3c, 0x61, 0x48, ]), bytes_to_words_6([ 0x7f, 0xe2, 0xb3, 0xcb, 0xa1, 0x23, 0x2b, 0x2f, 0x94, 0x2e, 0x0e, 0x33, 0x04, 0x40, 0xd4, 0xd3, 0x1b, 0x68, 0xdc, 0xe4, 0x83, 0x4a, 0xd7, 0x28, ]), bytes_to_words_6([ 0xf0, 0x45, 0xa8, 0x69, 0x91, 0x8c, 0x0f, 0x7f, 0x11, 0x6c, 0x06, 0xf7, 0x03, 0xcb, 0x76, 0x9b, 0x6a, 0x6c, 0x36, 0x20, 0x77, 0xcf, 0xf4, 0x4f, ]), bytes_to_words_6([ 0x81, 0x03, 0xed, 0xe3, 0x52, 0x13, 0xcb, 0x73, 0x98, 0x0e, 0x15, 0xd9, 0xa6, 0x32, 0xdb, 0xcd, 0xaa, 0x77, 0xa8, 0xdb, 0x71, 0xc4, 0x63, 0xd7, ]), bytes_to_words_6([ 0xb5, 0x1f, 0x08, 0xcb, 0x63, 0x81, 0x18, 0x3e, 0xa1, 0x35, 0x13, 0xbe, 0xea, 0x35, 0x6a, 0xcd, 0x5a, 0x35, 0xc4, 0x4f, 0x57, 0x82, 0xdc, 0xbf, ]), bytes_to_words_6([ 0xd2, 0xf2, 0x32, 0x3b, 0xbb, 0x5c, 0x57, 0x71, 0x72, 0xfd, 0x27, 0xf3, 0x70, 0x96, 0x9d, 0xf5, 0x91, 0x0a, 0x9e, 0x0e, 0xb9, 0x9c, 0xd0, 0x29, ]), bytes_to_words_6([ 0x3b, 0xae, 0x2c, 0x0d, 0xeb, 0x53, 0x95, 0x20, 0x71, 0xc7, 0x0d, 0xd5, 0x19, 0x46, 0x9f, 0x55, 0x24, 0xec, 0x52, 0xde, 0x83, 0xe1, 0x0d, 0x28, ]), bytes_to_words_6([ 0x5a, 0x60, 0x9b, 0xcb, 0x30, 0x30, 0xe7, 0xdd, 0xdc, 0x50, 0x30, 0xb6, 0x68, 0xe3, 0xfb, 0x84, 0x41, 0x90, 0x18, 0x3f, 0xd5, 0xa1, 0x1e, 0xe4, ]), bytes_to_words_6([ 0xb4, 0xce, 0x3e, 0x30, 0xb6, 0x24, 0xae, 0x97, 0x70, 0x5f, 0xac, 0x89, 0x1c, 0x7e, 0x22, 0x6e, 0x2e, 0x0d, 0xfd, 0xd3, 0x12, 0x7e, 0xfe, 0x7d, ]), bytes_to_words_6([ 0x80, 0x51, 0x45, 0x80, 0x62, 0xfd, 0xa1, 0xff, 0x6e, 0x81, 0x70, 0x39, 0x43, 0xf5, 0xb7, 0xd2, 0x39, 0xa2, 0xfc, 0xee, 0x1d, 0xd2, 0xc0, 0x4f, ]), bytes_to_words_6([ 0x43, 0x72, 0xfd, 0x39, 0xf2, 0xaa, 0x8b, 0x76, 0xda, 0x11, 0x2a, 0xb7, 0x28, 0x4e, 0xc2, 0xff, 0xce, 0xde, 0x59, 0x5e, 0x87, 0xd8, 0x42, 0x1a, ]), bytes_to_words_6([ 0x3f, 0xbe, 0x60, 0x0b, 0x2f, 0x2a, 0x0f, 0x44, 0x12, 0xde, 0xcf, 0x64, 0xb7, 0x97, 0xb7, 0x1d, 0xb2, 0x46, 0xfc, 0xdd, 0x46, 0xca, 0xf9, 0x11, ]), ]; const PATH: [[U32<LittleEndian>; 6]; 15] = [ bytes_to_words_6([ 0xbe, 0x59, 0x73, 0xbc, 0xe7, 0x93, 0x5f, 0x53, 0x40, 0xe9, 0x26, 0xa9, 0xfc, 0xb3, 0xcb, 0x9d, 0x2d, 0x29, 0x22, 0x19, 0x28, 0xd3, 0x77, 0x01, ]), bytes_to_words_6([ 0xac, 0xca, 0x20, 0x2f, 0x08, 0x49, 0x75, 0x99, 0xf8, 0x3e, 0xd4, 0x24, 0xff, 0x25, 0xd2, 0xa8, 0xb6, 0x16, 0xf1, 0xe2, 0x48, 0xf0, 0xf1, 0xba, ]), bytes_to_words_6([ 0xcd, 0xd8, 0x16, 0x9b, 0x7e, 0x86, 0xba, 0x21, 0xd1, 0x59, 0xaa, 0x85, 0x62, 0x2e, 0x9d, 0x21, 0x7c, 0x74, 0x76, 0xd5, 0xf3, 0xa7, 0xcd, 0xfb, ]), bytes_to_words_6([ 0xeb, 0x44, 0x55, 0x41, 0xa7, 0xa5, 0xa3, 0xab, 0x78, 0x92, 0xb3, 0x71, 0x81, 0x43, 0x94, 0x6e, 0xa0, 0xc1, 0xe4, 0xff, 0x83, 0x7f, 0xb0, 0xf3, ]), bytes_to_words_6([ 0x68, 0xfe, 0xed, 0x20, 0xc9, 0x09, 0x01, 0xc1, 0xda, 0xcd, 0xf3, 0x0b, 0x90, 0xd3, 0x3f, 0x6f, 0x4b, 0x17, 0x93, 0xa5, 0x57, 0x06, 0xc5, 0x43, ]), bytes_to_words_6([ 0x3a, 0x01, 0x82, 0x46, 0xba, 0xe1, 0x03, 0xe7, 0x97, 0x94, 0xfc, 0x1f, 0xa5, 0xc2, 0x03, 0xfd, 0x8b, 0xf0, 0xc7, 0x77, 0xb4, 0x07, 0xaa, 0xde, ]), bytes_to_words_6([ 0xa1, 0x63, 0x82, 0xeb, 0x04, 0x9d, 0x45, 0x83, 0x62, 0xf7, 0xb6, 0x3e, 0x30, 0x04, 0xf9, 0x2c, 0x92, 0x66, 0x0e, 0x63, 0x17, 0x18, 0xf7, 0x60, ]), bytes_to_words_6([ 0x08, 0x42, 0x49, 0x45, 0x57, 0xac, 0x9b, 0x94, 0x7a, 0x21, 0x46, 0xb1, 0x22, 0xd2, 0xe7, 0x5f, 0x3a, 0x3d, 0x75, 0x9e, 0x5a, 0xba, 0xee, 0x58, ]), bytes_to_words_6([ 0x1c, 0xbb, 0xea, 0x87, 0xbc, 0x7a, 0xf8, 0xfe, 0x78, 0xc7, 0x0c, 0x66, 0x00, 0x41, 0xc5, 0x3e, 0xda, 0xcf, 0x17, 0x3d, 0x95, 0x7a, 0x2c, 0xe1, ]), bytes_to_words_6([ 0xaa, 0x37, 0x7c, 0x8c, 0x02, 0x5b, 0xb4, 0x98, 0xc7, 0x6d, 0x96, 0x07, 0x21, 0x44, 0x82, 0x06, 0x7d, 0xe2, 0xb5, 0x4a, 0x0e, 0xf4, 0xec, 0xec, ]), bytes_to_words_6([ 0x50, 0x86, 0x6a, 0x67, 0x69, 0xe6, 0xef, 0xb3, 0x9d, 0xaf, 0x9e, 0xc4, 0xaf, 0x6c, 0xe9, 0x3b, 0xe8, 0x72, 0x3d, 0x8c, 0xa5, 0xd8, 0x98, 0x07, ]), bytes_to_words_6([ 0x4b, 0xe3, 0x74, 0xde, 0xa1, 0x9a, 0x32, 0x52, 0xf9, 0xc5, 0xbe, 0x94, 0x37, 0x97, 0xf7, 0xa1, 0x01, 0xb7, 0x43, 0x68, 0xe6, 0x6f, 0x2f, 0x55, ]), bytes_to_words_6([ 0x1e, 0xec, 0xde, 0xb6, 0xde, 0xcb, 0x87, 0x2d, 0x70, 0x47, 0x59, 0x93, 0x50, 0xc2, 0x06, 0xaf, 0x36, 0xb2, 0x09, 0x63, 0xb9, 0x7e, 0xc6, 0x87, ]), bytes_to_words_6([ 0x25, 0xf0, 0x11, 0x78, 0x5c, 0x1f, 0xe2, 0x2d, 0xee, 0x81, 0xe8, 0x1f, 0x60, 0x8a, 0x76, 0xb7, 0xac, 0x8b, 0xb9, 0xc3, 0xf1, 0xac, 0x68, 0x4f, ]), bytes_to_words_6([ 0x73, 0xd6, 0x27, 0xd5, 0x6a, 0xf2, 0x6e, 0x31, 0x2d, 0xbf, 0xf6, 0x7f, 0x94, 0x0a, 0x83, 0x0a, 0xd5, 0x38, 0x67, 0x4b, 0xc5, 0x9b, 0x4e, 0x39, ]), ]; const LMS_SIG: LmsSignature<6, 51, 15> = LmsSignature { q: Q, ots: LmotsSignature { ots_type: LMOTS_TYPE, nonce: NONCE, y: Y, }, tree_type: LMS_TYPE, tree_path: PATH, }; const LMS_PUBLIC_KEY: LmsPublicKey<6> = LmsPublicKey { id: LMS_IDENTIFIER, digest: LMS_PUBLIC_HASH, tree_type: LMS_TYPE, otstype: LMOTS_TYPE, }; let result = Lms::default() .verify_lms_signature(&mut sha256, &MESSAGE, &LMS_PUBLIC_KEY, &LMS_SIG) .unwrap(); assert_eq!(result, LmsResult::Success); let candidate_key = Lms::default() .verify_lms_signature_cfi(&mut sha256, &MESSAGE, &LMS_PUBLIC_KEY, &LMS_SIG) .unwrap(); assert_eq!(candidate_key, HashValue::from(LMS_PUBLIC_KEY.digest)); // add a test that uses an invalid q value // in this case we are using the maximum value for q let invalid_q_sig = LmsSignature { q: <U32<BigEndian>>::from(32767u32), ..LMS_SIG }; let result = Lms::default() .verify_lms_signature(&mut sha256, &MESSAGE, &LMS_PUBLIC_KEY, &invalid_q_sig) .unwrap(); assert_eq!(result, LmsResult::SigVerifyFailed); // add a test that uses an invalid p value // in this case we are using one greater than the maximum value for Q // this should result in an invalid p value error (meaning the path is invalid) let invalid_q_sig = LmsSignature { q: <U32<BigEndian>>::from(32768u32), ..LMS_SIG }; let result = Lms::default().verify_lms_signature(&mut sha256, &MESSAGE, &LMS_PUBLIC_KEY, &invalid_q_sig); assert_eq!(result, Err(CaliptraError::DRIVER_LMS_INVALID_Q_VALUE)); } test_suite! { test_coefficient, test_get_lms_parameters, test_hash_message_24, test_lms_24_height_15, }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/drivers/test-fw/src/bin/mailbox_driver_negative_tests.rs
drivers/test-fw/src/bin/mailbox_driver_negative_tests.rs
// Licensed under the Apache-2.0 license //! A very simple program that uses the driver to send mailbox messages #![no_main] #![no_std] use caliptra_registers::mbox::MboxCsr; // Needed to bring in startup code #[allow(unused)] use caliptra_test_harness::{self, println}; use caliptra_drivers::{self, Mailbox}; #[panic_handler] pub fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} } fn mbox_fsm_error() -> bool { let mbox = unsafe { MboxCsr::new() }; mbox.regs().status().read().mbox_fsm_ps().mbox_error() } #[no_mangle] extern "C" fn main() { // 0 byte request // The SoC will try to corrupt the CMD opcode and the Dlen field. loop { let mut mbox = unsafe { Mailbox::new(MboxCsr::new()) }; let mut txn = mbox.try_start_send_txn().unwrap(); txn.send_request(0xa000_0000, b"").unwrap(); // TODO: get rid of mbox_fsm_error() and make the driver handle this correctly (see #718) while !txn.is_response_ready() && !mbox_fsm_error() {} txn.complete().unwrap(); drop(txn); drop(mbox); // Clear any error states // TODO: This should probably be done in the driver let mut reg = unsafe { MboxCsr::new() }; reg.regs_mut().unlock().write(|w| w.unlock(true)); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/zero_bin/build.rs
zero_bin/build.rs
// Licensed under the Apache-2.0 license fn main() { cfg_if::cfg_if! { if #[cfg(not(feature = "std"))] { use std::env; use std::fs; use std::path::PathBuf; use caliptra_gen_linker_scripts::gen_memory_x; let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); cfg_if::cfg_if! { if #[cfg(feature = "fmc")] { fs::write(out_dir.join("memory.x"),gen_memory_x(caliptra_common::FMC_ORG, caliptra_common::FMC_SIZE) .as_bytes()) .expect("Unable to generate memory.x"); } else { fs::write(out_dir.join("memory.x"),gen_memory_x(caliptra_common::RUNTIME_ORG, caliptra_common::RUNTIME_SIZE) .as_bytes()) .expect("Unable to generate memory.x"); } } fs::write(out_dir.join("link.x"), include_bytes!("src/link.x")).unwrap(); let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); println!("cargo:rustc-link-search={}", out_dir.display()); println!("cargo:rerun-if-changed=memory.x"); println!("cargo:rustc-link-arg=-Tmemory.x"); println!("cargo:rerun-if-changed=link.x"); println!("cargo:rustc-link-arg=-Tlink.x"); println!("cargo:rerun-if-changed=build.rs"); } } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/zero_bin/src/main.rs
zero_bin/src/main.rs
// Licensed under the Apache-2.0 license #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_main)] #[cfg(target_arch = "riscv32")] core::arch::global_asm!(include_str!("zeros.S")); #[cfg(feature = "std")] pub fn main() {} // Should not be linked #[cfg(not(feature = "std"))] #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { loop {} }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/zero_bin/tests/test_zeros.rs
zero_bin/tests/test_zeros.rs
// Licensed under the Apache-2.0 license use caliptra_api::soc_mgr::SocManager; use caliptra_builder::{ firmware::{APP_ZEROS, FMC_ZEROS}, ImageOptions, }; use caliptra_drivers::memory_layout::ICCM_ORG; use caliptra_error::CaliptraError; use caliptra_hw_model::{BootParams, HwModel, InitParams}; #[test] fn test_zeros() { let rom = caliptra_builder::rom_for_fw_integration_tests().unwrap(); let init_params = InitParams { rom: &rom, ..Default::default() }; let image = caliptra_builder::build_and_sign_image(&FMC_ZEROS, &APP_ZEROS, ImageOptions::default()) .unwrap(); let mut model = caliptra_hw_model::new( init_params, BootParams { fw_image: Some(&image.to_bytes().unwrap()), ..Default::default() }, ) .unwrap(); // 0 is an ilegal instruction in risc-v. Image should immediately NMI. model.step_until(|m| m.soc_ifc().cptra_fw_error_fatal().read() != 0); assert_eq!( model.soc_ifc().cptra_fw_error_fatal().read(), u32::from(CaliptraError::ROM_GLOBAL_EXCEPTION) ); let ext_info = model.soc_ifc().cptra_fw_extended_error_info().read(); let mcause = ext_info[0]; let mepc = ext_info[2]; // Invalid Instruction error assert_eq!(mcause, 2); assert_eq!(mepc, ICCM_ORG); }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/registers/src/lib.rs
registers/src/lib.rs
// Licensed under the Apache-2.0 license // #![no_std] pub use caliptra_registers_latest::*;
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
chipsalliance/caliptra-sw
https://github.com/chipsalliance/caliptra-sw/blob/d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c/registers/bin/generator/src/main.rs
registers/bin/generator/src/main.rs
// Licensed under the Apache-2.0 license. use std::collections::HashMap; use std::fmt::Write; use std::path::PathBuf; use std::process::Stdio; use std::rc::Rc; use std::{error::Error, path::Path, process::Command}; use quote::__private::TokenStream; use quote::{format_ident, quote}; use ureg_schema::{Enum, EnumVariant, Register, RegisterBlock, RegisterBlockInstance}; static HEADER_PREFIX: &str = r"/* Licensed under the Apache-2.0 license. "; static HEADER_SUFFIX: &str = r" */ "; static CALIPTRA_RDL_FILES: &[&str] = &[ "src/axi/rtl/axi_dma_reg.rdl", "src/pcrvault/rtl/pv_def.rdl", "src/pcrvault/rtl/pv_reg.rdl", "src/datavault/rtl/dv_reg.rdl", "src/libs/rtl/interrupt_regs.rdl", "src/keyvault/rtl/kv_def.rdl", "src/aes/data/aes.rdl", "src/aes/rtl/aes_clp_reg.rdl", "src/keyvault/rtl/kv_reg.rdl", "src/doe/rtl/doe_reg.rdl", "src/ecc/rtl/ecc_reg.rdl", "src/hmac/rtl/hmac_reg.rdl", "src/csrng/data/csrng.rdl", "src/entropy_src/data/entropy_src.rdl", "src/sha256/rtl/sha256_reg.rdl", "src/sha3/rtl/sha3_reg.rdl", "src/sha512/rtl/sha512_reg.rdl", "src/spi_host/data/spi_host.rdl", "src/soc_ifc/rtl/mbox_csr.rdl", "src/soc_ifc/rtl/soc_ifc_reg.rdl", "src/soc_ifc/rtl/sha512_acc_csr.rdl", "src/uart/data/uart.rdl", "src/sha3/rtl/kmac_reg.rdl", ]; static CALIPTRA_INTEGRATION_RDL_FILE: &str = "src/integration/rtl/caliptra_reg.rdl"; static I3C_CORE_RDL_FILES: &[&str] = &["src/rdl/registers.rdl"]; static CALIPTRA_SS_RDL_FILES: &[&str] = &[ "src/fuse_ctrl/rtl/otp_ctrl.rdl", "src/lc_ctrl/rtl/lc_ctrl.rdl", "src/mci/rtl/mci_reg.rdl", "src/mci/rtl/mcu_mbox_csr.rdl", "src/mci/rtl/trace_buffer_csr.rdl", "src/mci/rtl/mci_top.rdl", ]; static ADAMSBRIDGE_RDL_FILES: &[&str] = &["src/abr_top/rtl/abr_reg.rdl"]; static CALIPTRA_EXTRA_RDL_FILES: &[&str] = &["el2_pic_ctrl.rdl"]; fn run_cmd_stdout(cmd: &mut Command, input: Option<&[u8]>) -> Result<String, Box<dyn Error>> { cmd.stdin(Stdio::piped()); cmd.stdout(Stdio::piped()); let mut child = cmd.spawn()?; if let (Some(mut stdin), Some(input)) = (child.stdin.take(), input) { std::io::Write::write_all(&mut stdin, input)?; } let out = child.wait_with_output()?; if out.status.success() { Ok(String::from_utf8_lossy(&out.stdout).into()) } else { Err(format!( "Process {:?} {:?} exited with status code {:?} stderr {}", cmd.get_program(), cmd.get_args(), out.status.code(), String::from_utf8_lossy(&out.stderr) ) .into()) } } fn remove_reg_prefixes(registers: &mut [Rc<Register>], prefix: &str) { for reg in registers.iter_mut() { if reg.name.to_ascii_lowercase().starts_with(prefix) { let reg = Rc::make_mut(reg); reg.name = reg.name[prefix.len()..].to_string(); } } } fn rustfmt(code: &str) -> Result<String, Box<dyn Error>> { run_cmd_stdout( Command::new("rustfmt") .arg("--emit=stdout") .arg("--config=normalize_comments=true,normalize_doc_attributes=true"), Some(code.as_bytes()), ) } fn write_file(dest_file: &Path, contents: &str) -> Result<(), Box<dyn Error>> { println!("Writing to {dest_file:?}"); std::fs::write(dest_file, contents)?; Ok(()) } fn file_check_contents(dest_file: &Path, expected_contents: &str) -> Result<(), Box<dyn Error>> { println!("Checking file {dest_file:?}"); let actual_contents = std::fs::read(dest_file)?; if actual_contents != expected_contents.as_bytes() { return Err(format!( "{dest_file:?} does not match the generator output. If this is \ unexpected, ensure that the caliptra-rtl submodule is pointing to \ the correct commit and/or run \"git submodule update\". Otherwise, \ run registers/update.sh to update this file." ) .into()); } Ok(()) } fn real_main() -> Result<(), Box<dyn Error>> { let mut args: Vec<String> = std::env::args().collect(); let file_action = if args.get(1).map(String::as_str) == Some("--check") { args.remove(1); file_check_contents } else { write_file }; if args.len() < 6 { Err( "Usage: codegen [--check] <caliptra_rtl_dir> <extra_rdl_dir> <dest_i3c> <caliptra_ss_dir> <dir_core_dir>", )?; } let rtl_dir = Path::new(&args[1]); let mut rdl_files: Vec<PathBuf> = CALIPTRA_RDL_FILES .iter() .map(|p| rtl_dir.join(p)) .filter(|p| p.exists()) .collect(); let adamsbridge_rdl_dir = rtl_dir.join("submodules").join("adams-bridge"); let mut adamsbridge_rdl_files: Vec<PathBuf> = ADAMSBRIDGE_RDL_FILES .iter() .map(|p| adamsbridge_rdl_dir.join(p)) .filter(|p| p.exists()) .collect(); rdl_files.append(&mut adamsbridge_rdl_files); let i3c_core_rdl_dir = Path::new(&args[3]); let mut i3c_core_rdl_files: Vec<PathBuf> = I3C_CORE_RDL_FILES .iter() .map(|p| i3c_core_rdl_dir.join(p)) .filter(|p| p.exists()) .collect(); rdl_files.append(&mut i3c_core_rdl_files); let caliptra_ss_dir = Path::new(&args[4]); let mut caliptra_ss_files: Vec<PathBuf> = CALIPTRA_SS_RDL_FILES .iter() .map(|p| caliptra_ss_dir.join(p)) .filter(|p| p.exists()) .collect(); rdl_files.append(&mut caliptra_ss_files); let integration_rdl_file = rtl_dir.join(CALIPTRA_INTEGRATION_RDL_FILE); if integration_rdl_file.exists() { rdl_files.push(integration_rdl_file); } let extra_rdl_dir = Path::new(&args[2]); let mut extra_rdl_files: Vec<PathBuf> = CALIPTRA_EXTRA_RDL_FILES .iter() .map(|p| extra_rdl_dir.join(p)) .filter(|p| p.exists()) .collect(); rdl_files.append(&mut extra_rdl_files); // eliminate duplicate type names let patches = vec![ ( i3c_core_rdl_dir.join("src/rdl/target_transaction_interface.rdl"), "QUEUE_THLD_CTRL", "TTI_QUEUE_THLD_CTRL", ), ( i3c_core_rdl_dir.join("src/rdl/target_transaction_interface.rdl"), "QUEUE_SIZE", "TTI_QUEUE_SIZE", ), ( i3c_core_rdl_dir.join("src/rdl/target_transaction_interface.rdl"), "IBI_PORT", "TTI_IBI_PORT", ), ( i3c_core_rdl_dir.join("src/rdl/target_transaction_interface.rdl"), "DATA_BUFFER_THLD_CTRL", "TTI_DATA_BUFFER_THLD_CTRL", ), ( i3c_core_rdl_dir.join("src/rdl/target_transaction_interface.rdl"), "RESET_CONTROL", "TTI_RESET_CONTROL", ), // The way the memory is configured mixes up the offsets. Set them directly. ( caliptra_ss_dir.join("src/mci/rtl/mcu_mbox_csr.rdl"), "} MBOX_SRAM;", "} MBOX_SRAM @0x0000_0000;", ), ( caliptra_ss_dir.join("src/mci/rtl/mcu_mbox_csr.rdl"), "} mbox_lock;", "} mbox_lock @0x0020_0000;", ), // Remove includes which ureg isn't able to handle correctly. ( caliptra_ss_dir.join("src/mci/rtl/mci_top.rdl"), r#" `ifndef MCI_TOP_RDL `define MCI_TOP_RDL `include "mci_reg.rdl" `include "trace_buffer_csr.rdl" `include "mcu_mbox_csr.rdl""#, "", ), ( caliptra_ss_dir.join("src/mci/rtl/mci_top.rdl"), "`endif // mci_top.rdl", "", ), ]; let rtl_commit_id = run_cmd_stdout( Command::new("git") .current_dir(rtl_dir) .arg("rev-parse") .arg("HEAD"), None, )?; let rtl_git_status = run_cmd_stdout( Command::new("git") .current_dir(rtl_dir) .arg("status") .arg("--porcelain"), None, )?; let mut header = HEADER_PREFIX.to_string(); write!( &mut header, "\n generated by caliptra_registers_generator with caliptra-rtl repo at {rtl_commit_id}" )?; if !rtl_git_status.is_empty() { write!( &mut header, "\n\nWarning: rtl-caliptra was dirty:{rtl_git_status}" )?; } header.push_str(HEADER_SUFFIX); let dest_dir = Path::new(&args[args.len() - 1]); let file_source = caliptra_systemrdl::FsFileSource::new(); for patch in patches { file_source.add_patch(&patch.0, patch.1, patch.2); } let scope = caliptra_systemrdl::Scope::parse_root(&file_source, &rdl_files) .map_err(|s| s.to_string())?; let scope = scope.as_parent(); // These are types like kv_read_ctrl_reg that are used by multiple crates let root_block = RegisterBlock { declared_register_types: ureg_systemrdl::translate_types(scope)?, ..Default::default() }; let mut root_block = root_block.validate_and_dedup()?; let mut extern_types = HashMap::new(); ureg_codegen::build_extern_types(&root_block, quote! { crate }, &mut extern_types); let addrmap_tops = vec!["clp", "clp2", "mci_top"]; let mut blocks = Vec::<RegisterBlock>::new(); for top in addrmap_tops { let mut block = ureg_systemrdl::translate_addrmap(scope.lookup_typedef(top).unwrap())?; blocks.append(&mut block); } let mut validated_blocks = vec![]; for mut block in blocks { if block.name.ends_with("_reg") || block.name.ends_with("_csr") { block.name = block.name[0..block.name.len() - 4].to_string(); } if block.name == "hmac" { remove_reg_prefixes(&mut block.registers, "hmac384_"); } else { remove_reg_prefixes( &mut block.registers, &format!("{}_", block.name.to_ascii_lowercase()), ); } if block.name == "soc_ifc" { block.rename_enum_variants(&[ ("DEVICE_UNPROVISIONED", "UNPROVISIONED"), ("DEVICE_MANUFACTURING", "MANUFACTURING"), ("DEVICE_PRODUCTION", "PRODUCTION"), ]); // Move the TRNG retrieval registers into an independent block; // these need to be owned by a separate driver than the rest of // soc_ifc. let mut trng_block = RegisterBlock { name: "soc_ifc_trng".into(), instances: vec![RegisterBlockInstance { name: "soc_ifc_trng_reg".into(), address: block.instances[0].address, }], ..Default::default() }; block.registers.retain(|field| { if matches!(field.name.as_str(), "CPTRA_TRNG_DATA" | "CPTRA_TRNG_STATUS") { trng_block.registers.push(field.clone()); false // remove field from soc_ifc } else { true // keep field } }); let trng_block = trng_block.validate_and_dedup()?; validated_blocks.push(trng_block); } let mut block = block.validate_and_dedup()?; if block.block().name == "ecc" { block.transform(|t| { // [TODO]: Put this enumeration into the RDL and remove this hack t.set_register_enum( "CTRL", "CTRL", Rc::new(Enum { name: Some("Ctrl".into()), variants: vec![ EnumVariant { name: "NONE".into(), value: 0, }, EnumVariant { name: "KEYGEN".into(), value: 1, }, EnumVariant { name: "SIGNING".into(), value: 2, }, EnumVariant { name: "VERIFYING".into(), value: 3, }, ], bit_width: 2, }), ); }); } if block.block().name == "mldsa" { block.transform(|t| { // [TODO]: Put this enumeration into the RDL and remove this hack t.set_register_enum( "CTRL", "CTRL", Rc::new(Enum { name: Some("Ctrl".into()), variants: vec![ EnumVariant { name: "NONE".into(), value: 0, }, EnumVariant { name: "KEYGEN".into(), value: 1, }, EnumVariant { name: "SIGNING".into(), value: 2, }, EnumVariant { name: "VERIFYING".into(), value: 3, }, EnumVariant { name: "KEYGEN_SIGN".into(), value: 4, }, ], bit_width: 3, }), ); }); } let module_ident = format_ident!("{}", block.block().name); ureg_codegen::build_extern_types( &block, quote! { crate::#module_ident }, &mut extern_types, ); validated_blocks.push(block); } let mut root_submod_tokens = TokenStream::new(); let mut all_blocks: Vec<_> = std::iter::once(&mut root_block) .chain(validated_blocks.iter_mut()) .collect(); ureg_schema::filter_unused_types(&mut all_blocks); for block in validated_blocks { // rust expects modules and files in lowercase naming let block_name = block.block().name.to_lowercase(); let module_ident = format_ident!("{}", block_name); let dest_file = dest_dir.join(format!("{}.rs", block_name)); let tokens = ureg_codegen::generate_code( &block, ureg_codegen::Options { extern_types: extern_types.clone(), module: quote! { #module_ident }, }, ); root_submod_tokens.extend(quote! { pub mod #module_ident; }); file_action( &dest_file, &rustfmt(&(header.clone() + &tokens.to_string()))?, )?; } let root_type_tokens = ureg_codegen::generate_code( &root_block, ureg_codegen::Options { extern_types: extern_types.clone(), ..Default::default() }, ); let root_tokens = quote! { #root_type_tokens #root_submod_tokens }; file_action( &dest_dir.join("lib.rs"), &rustfmt(&(header.clone() + &root_tokens.to_string()))?, )?; Ok(()) } fn main() { if let Err(err) = real_main() { eprintln!("{}", err); std::process::exit(1); } }
rust
Apache-2.0
d6e4f6fae9e4966ec1f5a52167a60c87fafecf1c
2026-01-04T20:21:36.839730Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/exhentai.rs
src/exhentai.rs
use crate::utils::{download_to_temp, HOST}; use crate::xpath::parse_html; use crate::{CONFIG, DB}; use anyhow::{Context, Result}; use futures::executor::block_on; use futures::prelude::*; use once_cell::sync::Lazy; use reqwest::header::{self, HeaderMap, HeaderValue}; use reqwest::{redirect::Policy, Client, Proxy, Response}; use telegraph_rs::Telegraph; use tokio::task::block_in_place; use tokio::time::sleep; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::Arc; use std::time::Duration; macro_rules! set_header { ($($k:ident => $v:expr), *) => {{ let mut headers = HeaderMap::new(); $(headers.insert(header::$k, HeaderValue::from_static($v));)* headers }}; } macro_rules! send { ($e:expr) => { $e.send().await.and_then(Response::error_for_status) }; } pub static EXHENTAI: Lazy<ExHentai> = Lazy::new(|| block_on(CONFIG.init_exhentai()).expect("登陆失败")); static REFERER: Lazy<String> = Lazy::new(|| format!("https://{}/", *HOST)); static HEADERS: Lazy<HeaderMap> = Lazy::new(|| { set_header! { ACCEPT => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", ACCEPT_ENCODING => "gzip, deflate, br", ACCEPT_LANGUAGE => "zh-CN,en-US;q=0.7,en;q=0.3", CACHE_CONTROL => "max-age=0", CONNECTION => "keep-alive", HOST => *HOST, REFERER => &*REFERER, UPGRADE_INSECURE_REQUESTS => "1", USER_AGENT => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0" } }); // TODO: 通过调整搜索页面展示的信息将 tag 移到这里来 /// 基本画廊信息 #[derive(Debug, Clone)] pub struct BasicGalleryInfo<'a> { client: &'a Client, /// 画廊标题 pub title: String, /// 画廊地址 pub url: String, /// 是否限制图片数量 pub limit: bool, /// 封面图片序号 pub cover_index: usize, } impl<'a> BasicGalleryInfo<'a> { /// 获取画廊的完整信息 pub async fn into_full_info(self) -> Result<FullGalleryInfo<'a>> { debug!("获取画廊信息: {}", self.url); let response = send!(self.client.get(&self.url))?; let mut html = parse_html(response.text().await?)?; // 英文标题和日文标题 let title = html.xpath_text(r#"//h1[@id="gn"]/text()"#)?.swap_remove(0); let title_jp = html .xpath_text(r#"//h1[@id="gj"]/text()"#) .map(|mut n| n.swap_remove(0)) .ok(); // 父画廊 let parent = html .xpath_text(r#"//tr[contains(./td[1]/text(), "Parent:")]/td[2]/a/@href"#) .ok() .map(|mut v| v.swap_remove(0)); debug!("父画廊:{:?}", parent); // 标签 let mut tags = vec![]; for ele in html .xpath_elem(r#"//div[@id="taglist"]//tr"#) .unwrap_or_default() { let tag_set_name = ele.xpath_text(r#"./td[1]/text()"#)?[0] .trim_matches(':') .to_owned(); let tag = ele.xpath_text(r#"./td[2]/div/a/text()"#)?; tags.push((tag_set_name, tag)); } debug!("tags: {:?}", tags); // 评分 let rating = html.xpath_text(r#"//td[@id="rating_label"]/text()"#)?[0] .split(' ') .nth(1) .context("找不到评分")? .to_owned(); debug!("评分: {}", rating); // 收藏 let fav_cnt = html.xpath_text(r#"//td[@id="favcount"]/text()"#)?[0] .split(' ') .next() .context("找不到收藏数")? .to_owned(); debug!("收藏数: {}", fav_cnt); // 图片页面 let mut img_pages = html.xpath_text(r#"//div[@id="gdt"]//a/@href"#)?; // 继续翻页 (如果有 while let Ok(next_page) = html.xpath_text(r#"//table[@class="ptt"]//td[last()]/a/@href"#) { debug!("下一页: {:?}", next_page); // TODO: 干掉此处的 block_on let text = block_in_place(|| { block_on(async { send!(self.client.get(&next_page[0]))?.text().await }) })?; html = parse_html(text)?; img_pages.extend(html.xpath_text(r#"//div[@id="gdt"]//a/@href"#)?); } debug!("页数:{}", img_pages.len()); Ok(FullGalleryInfo { client: self.client, url: self.url.clone(), limit: self.limit, parent, title, title_jp, rating, fav_cnt, img_pages, tags, }) } } /// 画廊信息 #[derive(Debug)] pub struct FullGalleryInfo<'a> { client: &'a Client, /// 画廊标题 pub title: String, /// 画廊日文标题 pub title_jp: Option<String>, /// 画廊地址 pub url: String, /// 父画廊地址 pub parent: Option<String>, /// 评分 pub rating: String, /// 收藏次数 pub fav_cnt: String, /// 标签 pub tags: Vec<(String, Vec<String>)>, /// 图片 URL pub img_pages: Vec<String>, /// 是否限制图片数量 pub limit: bool, } impl<'a> FullGalleryInfo<'a> { /// 返回调整数量后的图片页面链接 pub fn get_image_lists(&self) -> &[String] { if !self.limit { return &self.img_pages; } let limit = CONFIG.exhentai.max_img_cnt; let img_cnt = self.img_pages.len().min(limit); info!("保留图片数量: {}", img_cnt); &self.img_pages[..img_cnt] } /// 将画廊里的图片上传至 telegraph,返回上传后的图片链接 pub async fn upload_images_to_telegraph(&self) -> Result<Vec<String>> { let img_pages = self.get_image_lists(); let img_cnt = img_pages.len(); let idx = Arc::new(AtomicU32::new(0)); let update_progress = || { let now = idx.load(Ordering::SeqCst); idx.store(now + 1, Ordering::SeqCst); info!("第 {} / {} 张图片", now + 1, img_cnt); }; let mut client_builder = Client::builder().timeout(Duration::from_secs(30)); if let Some(proxy) = &CONFIG.telegraph.proxy { client_builder = client_builder.proxy(Proxy::custom(move |url| { (url.host_str() == Some("api.telegra.ph")).then(|| proxy.clone()) })); } let client = client_builder.build()?; let client_ref = &client; // TODO: 避免一次 clone? let get_url = |url: String| async move { update_progress(); let mut err = None; for _ in 0..5i32 { match self.upload_image(&url, client_ref).await { Ok(v) => return Ok(v), Err(e) => { error!("获取图片地址失败:{}", e); err = Some(e); } } sleep(Duration::from_secs(10)).await; } Err(err.unwrap().context("无法获取图片地址")) }; // TODO: 能不能 iter(img_pages) let mut f = vec![]; for url in img_pages.iter() { f.push(get_url(url.to_owned())); } let ret = futures::stream::iter(f) .buffered(CONFIG.threads_num) .try_collect::<Vec<_>>() .await?; Ok(ret) } /// 上传指定的图片并返回上传后的地址 pub async fn upload_image(&self, page_url: &str, client: &Client) -> Result<String> { debug!("获取图片真实地址中:{}", page_url); // 第一次查询,查询 image_hash if let Ok(url) = DB.query_image_by_hash(page_url) { trace!("找到缓存!"); return Ok(url); } let response = send!(self.client.get(page_url))?; let url = parse_html(response.text().await?)? .xpath_text(r#"//img[@id="img"]/@src"#)? .swap_remove(0); // 第二次查询,查询 images,此为历史遗留问题 // 一段时间后应该可以移除 images 表 if let Ok(url) = DB.query_image_by_fileindex(&url) { DB.insert_image(page_url, &url)?; trace!("找到缓存!"); return Ok(url); } debug!("下载图片中:{}", &url); let file = download_to_temp(client, &url).await?; let file = file.path(); // telegraph 对图片的体积 & 大小有要求 if file.metadata()?.len() > 5 * 1024 * 1024 { return Ok("".to_owned()); } let (width, height) = image::io::Reader::open(file)?.into_dimensions()?; if height * 10 <= width || width * 20 <= height { return Ok("".to_owned()); } debug!("上传图片中..."); let mut result = Telegraph::upload_with(&[file], client) .await .context("上传 Telegraph 失败")?; let ret = result.swap_remove(0).src; debug!("记录缓存..."); DB.insert_image(page_url, &ret)?; Ok(ret) } pub fn title(&self) -> &str { self.title_jp.as_ref().unwrap_or(&self.title) } } #[derive(Debug)] pub struct ExHentai { client: Client, } impl ExHentai { /// 登录 E-Hentai (能够访问 ExHentai 的前置条件 pub async fn new() -> Result<Self> { // 此处手动设置重定向, 因为 reqwest 的默认重定向处理策略会把相同 URL 直接判定为无限循环 // 然而其实 COOKIE 变了, 所以不会无限循环 let custom = Policy::custom(|attempt| { if attempt.previous().len() > 3 { attempt.error("too many redirects") } else { attempt.follow() } }); let mut client = Client::builder() .redirect(custom) .cookie_store(true) .timeout(Duration::from_secs(15)) .default_headers(HEADERS.clone()); if let Some(proxy) = &CONFIG.exhentai.proxy { client = client.proxy(Proxy::all(proxy)?) } let client = client.build()?; info!("登录表站..."); // 登录表站, 获得 cookie let _response = send!(client .post("https://forums.e-hentai.org/index.php") .query(&[("act", "Login"), ("CODE", "01")]) .form(&[ ("CookieDate", "1"), ("b", "d"), ("bt", "1-6"), ("UserName", &CONFIG.exhentai.username), ("PassWord", &CONFIG.exhentai.password), ("ipb_login_submit", "Login!"), ]))?; info!("登录里站..."); // 访问里站, 取得必要的 cookie let _response = send!(client.get(format!("https://{}", *HOST)))?; // 获得过滤设置相关的 cookie ? let _response = send!(client.get(format!("https://{}/uconfig.php", *HOST)))?; let _response = send!(client.get(format!("https://{}/mytags", *HOST)))?; info!("登录成功!"); Ok(Self { client }) } /// 直接通过 cookie 登录 pub async fn from_cookie() -> Result<Self> { let mut headers = HEADERS.clone(); headers.insert( header::COOKIE, HeaderValue::from_str(CONFIG.exhentai.cookie.as_ref().unwrap())?, ); let mut client = Client::builder() .cookie_store(true) .timeout(Duration::from_secs(15)) .default_headers(headers); if let Some(proxy) = &CONFIG.exhentai.proxy { client = client.proxy(Proxy::all(proxy)?) } let client = client.build()?; info!("Cookie 登陆中……"); let _response = send!(client.get(format!("https://{}/uconfig.php", *HOST)))?; let _response = send!(client.get(format!("https://{}/mytags", *HOST)))?; info!("登录成功!"); Ok(Self { client }) } /// 搜索指定关键字 pub async fn search(&self, page: i32) -> Result<Vec<BasicGalleryInfo>> { debug!("搜索第 {} 页", page); let response = send!(self .client .get(CONFIG.exhentai.search_url.clone()) .query(&CONFIG.exhentai.search_params) .query(&[("page", &page.to_string())]))?; debug!("状态码: {}", response.status()); let text = response.text().await?; debug!("返回: {}", &text[..100.min(text.len())]); let html = parse_html(text)?; let gallery_list = html.xpath_elem(r#"//table[@class="itg gltc"]/tr[position() > 1]"#)?; debug!("数量: {}", gallery_list.len()); let mut ret = vec![]; for gallery in gallery_list { let title = gallery .xpath_text(r#".//td[@class="gl3c glname"]/a/div/text()"#)? .swap_remove(0); debug!("标题: {}", title); let url = gallery .xpath_text(r#".//td[@class="gl3c glname"]/a/@href"#)? .swap_remove(0); debug!("地址: {}", url); ret.push(BasicGalleryInfo { client: &self.client, title, url, limit: true, cover_index: 0, }) } Ok(ret) } pub async fn search_n_pages(&self, n: i32) -> Result<Vec<BasicGalleryInfo>> { info!("搜索前 {} 页本子", n); let mut result = vec![]; for page in 0..n { match self.search(page).await { Ok(v) => result.extend(v), Err(e) => error!("{}", e), } } info!("找到 {} 本", result.len()); Ok(result) } pub async fn get_gallery_by_url<S: Into<String>>(&self, url: S) -> Result<BasicGalleryInfo> { let url = url.into(); info!("获取本子信息: {}", url); let response = send!(self.client.get(&url))?; let html = parse_html(response.text().await?)?; let title = html.xpath_text(r#"//h1[@id="gn"]/text()"#)?.swap_remove(0); Ok(BasicGalleryInfo { client: &self.client, title, url, limit: true, cover_index: 0, }) } } #[cfg(test)] mod tests { #[test] fn test_login() {} }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/config.rs
src/config.rs
use anyhow::Error; use reqwest::{Client, Proxy}; use serde::Deserialize; use std::time::Duration; use std::{fs::File, io::Read, path::Path}; use teloxide::types::{ChatId, Recipient}; use url::Url; #[derive(Debug, Deserialize)] pub struct Config { pub log_level: String, pub threads_num: usize, pub interval: u64, pub database_url: String, pub exhentai: ExHentai, pub telegraph: Telegraph, pub telegram: Telegram, } #[derive(Debug, Deserialize)] pub struct ExHentai { pub username: String, pub password: String, pub cookie: Option<String>, pub search_url: Url, pub search_params: Vec<(String, String)>, pub max_pages: i32, pub max_img_cnt: usize, pub outdate: Option<i64>, pub proxy: Option<String>, } #[derive(Debug, Deserialize)] pub struct Telegraph { pub access_token: String, pub author_name: String, pub author_url: String, pub proxy: Option<String>, } #[derive(Debug, Deserialize)] pub struct Telegram { pub channel_id: Recipient, pub bot_id: String, pub token: String, pub group_id: ChatId, pub trusted_users: Vec<String>, } impl Config { pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, Error> { let mut file = File::open(path)?; let mut str = String::new(); file.read_to_string(&mut str)?; Ok(toml::from_str(&str)?) } pub async fn init_telegraph(&self) -> Result<telegraph_rs::Telegraph, Error> { let telegraph = &self.telegraph; let mut client_builder = Client::builder().timeout(Duration::from_secs(30)); if let Some(proxy) = &self.telegraph.proxy { client_builder = client_builder.proxy(Proxy::all(proxy)?); } let client = client_builder.build()?; Ok(telegraph_rs::Telegraph::new(&telegraph.author_name) .author_url(&telegraph.author_url) .access_token(&telegraph.access_token) .client(client) .create() .await?) } pub async fn init_exhentai(&self) -> Result<crate::exhentai::ExHentai, Error> { if self.exhentai.cookie.is_some() { crate::exhentai::ExHentai::from_cookie().await } else { crate::exhentai::ExHentai::new().await } } } #[cfg(test)] mod tests { use crate::config::Config; #[test] fn test() { let config = Config::new("config.toml"); println!("{:?}", config); } }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/trans.rs
src/trans.rs
use once_cell::sync::Lazy; use serde::Deserialize; use std::collections::HashMap; use std::fs::read_to_string; pub static TRANS: Lazy<Database> = Lazy::new(Database::new); #[derive(Deserialize)] pub struct Database { // head: (), // version: u8, // repo: String, data: Vec<Data>, } #[derive(Deserialize)] pub struct Data { namespace: String, // count: i32, data: HashMap<String, Info>, } #[derive(Deserialize)] pub struct Info { name: String, // intro: String, // links: String, } impl Database { fn new() -> Self { let text = read_to_string("db.text.json").expect("Cannot open db.text.json"); serde_json::from_slice(text.as_bytes()).expect("Cannot parse translation database") } pub fn trans<'a>(&'a self, namespace: &'a str, name: &'a str) -> &'a str { for data in &self.data { if data.namespace == namespace { return data.trans(name); } } for data in &self.data { let trans = data.trans(name); if trans != name { return trans; } } name } } impl Data { pub fn trans<'a>(&'a self, name: &'a str) -> &'a str { self.data .get(name) .map(|info| info.name.as_str()) .unwrap_or(name) } } #[cfg(test)] mod test { use super::*; #[test] fn test() { let database: Database = serde_json::from_slice(include_bytes!("../db.text.json")).unwrap(); println!("{:?}", database.trans("female", "lolicon")); println!("{:?}", database.trans("female", "foobar")); } }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/database.rs
src/database.rs
use crate::exhentai::*; use crate::schema::*; use crate::utils::*; use anyhow::{Context, Result}; use chrono::prelude::*; use diesel::dsl::sql; use diesel::prelude::*; use diesel::r2d2::{ConnectionManager, Pool}; use diesel::sqlite::Sqlite; use std::env; embed_migrations!("migrations"); #[derive(Queryable, Insertable, PartialEq, Debug, Clone)] #[table_name = "gallery"] pub struct Gallery { pub message_id: i32, pub gallery_id: i32, pub token: String, pub title: String, pub tags: String, pub telegraph: String, pub upload_images: i16, pub publish_date: NaiveDate, pub poll_id: String, pub score: f32, pub votes: String, } #[derive(Queryable, Insertable)] #[table_name = "images"] pub struct Image { pub fileindex: i32, pub url: String, } #[derive(Queryable, Insertable)] #[table_name = "image_hash"] pub struct ImageHash { pub hash: String, pub url: String, } pub struct DataBase { pool: Pool<ConnectionManager<SqliteConnection>>, } impl DataBase { pub fn init() -> Result<Self> { info!("数据库初始化中……"); let url = env::var("DATABASE_URL").expect("请设置 DATABASE_URL"); let manager = ConnectionManager::new(url); let pool = Pool::builder() .max_size(16) .build(manager) .expect("连接池建立失败"); embedded_migrations::run_with_output(&pool.get()?, &mut std::io::stdout())?; Ok(Self { pool }) } pub fn insert_image(&self, image_url: &str, uploaded_url: &str) -> Result<()> { let hash = get_hash_from_image(image_url).context("图片哈希提取失败")?; let img = ImageHash { hash: hash.to_owned(), url: uploaded_url.to_owned(), }; diesel::insert_or_ignore_into(image_hash::table) .values(&img) .execute(&self.pool.get()?)?; Ok(()) } pub fn query_image_by_hash(&self, image_url: &str) -> Result<String> { let hash = get_hash_from_image(image_url).context("无法提取图片 hash")?; Ok(image_hash::table .filter(image_hash::hash.eq(hash)) .get_result::<ImageHash>(&self.pool.get()?)? .url) } pub fn query_image_by_fileindex(&self, image_url: &str) -> Result<String> { let fileindex = get_id_from_image(image_url).context("无法提取图片 fileindex")?; Ok(images::table .filter(images::fileindex.eq(fileindex)) .get_result::<Image>(&self.pool.get()?)? .url) } pub fn insert_gallery( &self, message_id: i32, info: &FullGalleryInfo, telegraph: String, ) -> Result<()> { debug!("添加新画廊"); let (gallery_id, token) = get_id_from_gallery(&info.url); let gallery = Gallery { title: info.title.to_owned(), tags: serde_json::to_string(&info.tags)?, publish_date: Utc::today().naive_utc(), score: 0.0, votes: "[]".to_string(), upload_images: info.get_image_lists().len() as i16, poll_id: "".to_string(), telegraph, gallery_id, token, message_id, }; diesel::insert_into(gallery::table) .values(&gallery) .execute(&self.pool.get()?)?; Ok(()) } // TODO: 根据 grep.app 上的代码优化一下自己的代码 /// 更新旧画廊信息 pub fn update_gallery( &self, message_id: i32, info: &FullGalleryInfo, telegraph: &str, upload_images: usize, ) -> Result<()> { debug!("更新画廊数据"); let (gallery_id, token) = get_id_from_gallery(&info.url); diesel::update(gallery::table) .filter(gallery::message_id.eq(message_id)) .set(( gallery::gallery_id.eq(gallery_id), gallery::title.eq(&info.title), gallery::token.eq(token), gallery::telegraph.eq(telegraph), gallery::tags.eq(serde_json::to_string(&info.tags)?), gallery::upload_images.eq(upload_images as i16), )) .execute(&self.pool.get()?)?; Ok(()) } /// 根据消息 id 删除画廊,并不会实际删除,否则又会在定时更新时被上传 pub fn delete_gallery(&self, message_id: i32) -> Result<()> { diesel::update(gallery::table) .filter(gallery::message_id.eq(message_id)) .set(gallery::score.eq(-1.0)) .execute(&self.pool.get()?)?; Ok(()) } /// 根据消息 id 删除画廊,这是真的删除 pub fn real_delete_gallery(&self, message_id: i32) -> Result<()> { diesel::delete(gallery::table) .filter(gallery::message_id.eq(message_id)) .execute(&self.pool.get()?)?; Ok(()) } /// 查询自指定日期以来分数大于指定分数的 20 本本子 /// offset 为 1 表示正序,-1 表示逆序 pub fn query_best( &self, from: NaiveDate, to: NaiveDate, mut offset: i64, ) -> Result<Vec<Gallery>> { let ordering: Box<dyn BoxableExpression<gallery::table, Sqlite, SqlType = ()>> = if offset > 0 { Box::new(gallery::score.desc()) } else { offset = -offset; Box::new(gallery::score.asc()) }; Ok(gallery::table .filter( gallery::publish_date .ge(to) .and(gallery::publish_date.le(from)) .and(gallery::score.ne(-1.0)) .and(gallery::poll_id.ne("")), ) .order_by((ordering, gallery::publish_date.desc())) .group_by(gallery::poll_id) .offset(offset - 1) .limit(20) .load::<Gallery>(&self.pool.get()?)?) } pub fn get_rank(&self, score: f32) -> Result<f32> { Ok(gallery::table .filter(gallery::poll_id.ne("").and(gallery::score.ge(0.0))) .select(sql(&format!( "sum(IIF(score >= {}, 1., 0.)) / count(*)", score ))) .get_result::<f32>(&self.pool.get()?)?) } pub fn update_poll_id(&self, message_id: i32, poll_id: &str) -> Result<()> { diesel::update(gallery::table) .filter(gallery::message_id.eq(message_id)) .set(gallery::poll_id.eq(poll_id)) .execute(&self.pool.get()?)?; Ok(()) } pub fn query_poll_id(&self, message_id: i32) -> Result<String> { Ok(gallery::table .filter(gallery::message_id.eq(message_id)) .select(gallery::poll_id) .get_result::<String>(&self.pool.get()?)?) } pub fn insert_vote(&self, user_id: u64, poll_id: i32, option: i32) -> Result<()> { diesel::replace_into(user_vote::table) .values(&vec![( user_vote::user_id.eq(user_id as i64), user_vote::poll_id.eq(poll_id), user_vote::option.eq(option), user_vote::vote_time.eq(Utc::now().naive_utc()), )]) .execute(&*self.pool.get()?)?; Ok(()) } pub fn query_vote(&self, poll_id: i32) -> Result<[i32; 5]> { let mut ret = [0; 5]; let options = user_vote::table .select(user_vote::option) .filter(user_vote::poll_id.eq(poll_id)) .load::<i32>(&self.pool.get()?)?; for i in options { ret[i as usize - 1] += 1 } Ok(ret) } pub fn update_score<S: AsRef<str>>(&self, poll_id: &str, score: f32, votes: S) -> Result<()> { diesel::update(gallery::table) .filter(gallery::poll_id.eq(poll_id)) .set((gallery::score.eq(score), gallery::votes.eq(votes.as_ref()))) .execute(&self.pool.get()?)?; Ok(()) } pub fn query_gallery_by_url(&self, url: &str) -> Result<Gallery> { let (id, _) = get_id_from_gallery(url); Ok(gallery::table .filter(gallery::gallery_id.eq(id)) .order_by(gallery::publish_date.desc()) .limit(1) .get_result::<Gallery>(&self.pool.get()?)?) } pub fn query_gallery(&self, message_id: i32) -> Result<Gallery> { Ok(gallery::table .filter(gallery::message_id.eq(message_id)) .get_result::<Gallery>(&self.pool.get()?)?) } } impl Gallery { pub fn get_url(&self) -> String { format!("https://{}/g/{}/{}/", *HOST, self.gallery_id, self.token) } }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/schema.rs
src/schema.rs
table! { gallery (message_id) { message_id -> Integer, gallery_id -> Integer, token -> Text, title -> Text, tags -> Text, telegraph -> Text, upload_images -> SmallInt, publish_date -> Date, poll_id -> Text, score -> Float, votes -> Text, } } table! { image_hash (hash) { hash -> Text, url -> Text, } } table! { images (fileindex) { fileindex -> Integer, url -> Text, } } table! { user_vote (user_id, poll_id) { user_id -> BigInt, poll_id -> Integer, option -> Integer, vote_time -> Timestamp, } } allow_tables_to_appear_in_same_query!(gallery, image_hash, images, user_vote,);
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/utils.rs
src/utils.rs
use crate::trans::TRANS; use crate::CONFIG; use anyhow::Context; use futures::TryFutureExt; use once_cell::sync::Lazy; use regex::Regex; use reqwest::header::*; use reqwest::{Client, Response}; use std::borrow::Cow; use std::io::Write; use std::time::SystemTime; use tempfile::NamedTempFile; pub static HOST: Lazy<&'static str> = Lazy::new(|| { CONFIG .exhentai .search_url .host_str() .expect("failed to extract host from search_url") }); /// 将图片地址格式化为 html pub fn img_urls_to_html(img_urls: &[String]) -> String { img_urls .iter() .filter(|s| !s.is_empty()) .map(|s| format!(r#"<img src="{}">"#, s)) .collect::<Vec<_>>() .join("") } /// 左填充空格 fn pad_left(s: &str, len: usize) -> Cow<str> { let width = unicode_width::UnicodeWidthStr::width(s); if width >= len { Cow::Borrowed(s) } else { Cow::Owned(" ".repeat(len - width) + s) } } /// 将 tag 转换为可以直接发送至 tg 的文本格式 pub fn tags_to_string(tags: &[(String, Vec<String>)]) -> String { let replace_table = vec![ (" ", "_"), ("_|_", " #"), ("-", "_"), ("/", "_"), ("·", "_"), ]; let trans = |namespace: &str, string: &str| -> String { // 形如 "usashiro mani | mani" 的 tag 只需要取第一部分翻译 let to_translate = string.split(" | ").next().unwrap(); let mut result = TRANS.trans(namespace, to_translate).to_owned(); // 没有翻译的话,还是使用原始字符串 if result == to_translate { result = string.to_owned(); } for (from, to) in replace_table.iter() { result = result.replace(from, to); } format!("#{}", result) }; let mut ret = vec![]; for (k, v) in tags { let v = v.iter().map(|s| trans(k, s)).collect::<Vec<_>>().join(" "); ret.push(format!( "<code>{}</code>: {}", pad_left(TRANS.trans("rows", k), 6), v )) } ret.join("\n") } /// 从 e 站 url 中获取数字格式的 id,第二项为 token pub fn get_id_from_gallery(url: &str) -> (i32, String) { let url = url.split('/').collect::<Vec<_>>(); (url[4].parse::<i32>().unwrap(), url[5].to_owned()) } /// 从图片 url 中获取数字格式的 id,第一个为 id,第二个为图片序号 /// 图片格式示例: /// https://bhoxhym.oddgxmtpzgse.hath.network/h/33f789fab8ecb4667521e6b1ad3b201936a96415-382043-1280-1817-jpg/keystamp=1619024700-fff70cfa32;fileindex=91876552;xres=2400/00000000.jpg pub fn get_id_from_image(url: &str) -> Option<i32> { static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"fileindex=(\d+)").unwrap()); let caps = RE.captures(url)?; caps.get(1).and_then(|s| s.as_str().parse::<i32>().ok()) } /// 提取图片哈希,此处为原图哈希的前十位 /// 链接示例:https://exhentai.org/s/03af734602/1932743-1 pub fn get_hash_from_image(url: &str) -> Option<&str> { static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"/s/([0-9a-f]+)/").unwrap()); let caps = RE.captures(url)?; caps.get(1).map(|s| s.as_str()) } /// 根据消息 id 生成当前频道的消息直链 pub fn get_message_url(id: i32) -> String { format!("https://t.me/{}/{}", CONFIG.telegram.channel_id, id) .replace("/-100", "/") .replace('@', "") } pub fn get_timestamp() -> u64 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .expect("您穿越了?") .as_secs() } pub fn extract_telegraph_path(s: &str) -> &str { s.split('/') .last() .and_then(|s| s.split('?').next()) .unwrap() } pub async fn download_to_temp(client: &Client, url: &str) -> anyhow::Result<NamedTempFile> { let bytes = client .get(url) .header(CONNECTION, "keep-alive") .header(REFERER, "https://exhentai.org/") .send() .and_then(Response::bytes) .await?; let suffix = String::from(".") + url.rsplit_once('.').context("找不到图片后缀")?.1; let mut tmp = tempfile::Builder::new() .prefix("exloli_") .suffix(&suffix) .rand_bytes(5) .tempfile()?; tmp.write_all(bytes.as_ref())?; Ok(tmp) }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/xpath.rs
src/xpath.rs
use anyhow::{Context, Error}; use libxml::parser::Parser; use libxml::tree::{self, Document, NodeType}; use libxml::xpath::Context as XContext; use std::{fmt, ops::Deref, rc::Rc}; #[derive(Debug)] pub enum Value { Element(Vec<Node>), Text(Vec<String>), None, } impl Value { pub fn into_element(self) -> Option<Vec<Node>> { match self { Value::Element(v) => Some(v), _ => None, } } pub fn into_text(self) -> Option<Vec<String>> { match self { Value::Text(v) => Some(v), _ => None, } } } pub struct Node { document: Rc<Document>, context: Rc<XContext>, node: tree::Node, } impl fmt::Debug for Node { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.get_type() { Some(NodeType::ElementNode) => { write!(f, "<Element {} at {:p}>", self.get_name(), self.node_ptr()) } Some(NodeType::AttributeNode) | Some(NodeType::TextNode) => { write!(f, "{:?}", self.get_content()) } _ => unimplemented!(), } } } impl Node { pub fn xpath_text(&self, xpath: &str) -> Result<Vec<String>, Error> { match self.xpath(xpath)?.into_text() { Some(v) => Ok(v), None => Err(anyhow!("not found: {}", xpath)), } } pub fn xpath_elem(&self, xpath: &str) -> Result<Vec<Node>, Error> { match self.xpath(xpath)?.into_element() { Some(v) => Ok(v), None => Err(anyhow!("not found: {}", xpath)), } } pub fn xpath(&self, xpath: &str) -> Result<Value, Error> { let nodes = self .context .node_evaluate(xpath, &self.node) .map_err(|_| anyhow!("failed to evaluate xpath: {}", xpath))? .get_nodes_as_vec(); let result = match nodes.get(0) { Some(node) => match node.get_type() { Some(NodeType::ElementNode) => Value::Element( nodes .into_iter() .map(|node| Node { document: self.document.clone(), context: self.context.clone(), node, }) .collect(), ), Some(NodeType::AttributeNode) | Some(NodeType::TextNode) => { Value::Text(nodes.into_iter().map(|node| node.get_content()).collect()) } _ => unimplemented!(), }, None => Value::None, }; Ok(result) } } impl Deref for Node { type Target = tree::Node; fn deref(&self) -> &Self::Target { &self.node } } pub fn parse_html<S: AsRef<str>>(html: S) -> Result<Node, Error> { let parser = Parser::default_html(); let document = parser .parse_string(html.as_ref()) .context("failed to parse html")?; let context = XContext::new(&document).map_err(|_| anyhow!("failed to new context"))?; let root = document.get_root_element().context("no root element")?; Ok(Node { document: Rc::new(document), context: Rc::new(context), node: root, }) } #[cfg(test)] mod tests { use crate::xpath::parse_html; #[test] fn find_nodes() { let html = r#" <!doctype html> <html lang="zh-CN" dir="ltr"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' resource: chrome:; connect-src https:; img-src https: data: blob:; style-src 'unsafe-inline';"> <title>新标签页</title> <link rel="icon" type="image/png" href="chrome://branding/content/icon32.png"/> <link rel="stylesheet" href="chrome://browser/content/contentSearchUI.css" /> <link rel="stylesheet" href="resource://activity-stream/css/activity-stream.css" /> </head> <body class="activity-stream"> <div id="root"><!-- Regular React Rendering --></div> <div id="snippets-container"> <div id="snippets"></div> </div> <table id="wow" class="lol"> <tr class="head"> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr class="body"> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr class="body"> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> </body> </html> "#; let node = parse_html(html).unwrap(); println!("{:?}", node.xpath(r#"//table"#)); println!("{:?}", node.xpath(r#"//table/@class"#)); println!("{:?}", node.xpath(r#"//table//tr"#)); println!("{:?}", node.xpath(r#"//table//th/text()"#)); for td in node.xpath("//td").unwrap().into_element().unwrap() { println!("{:?}", td.xpath(".//text()")); } } }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/exloli.rs
src/exloli.rs
use crate::database::Gallery; use crate::exhentai::*; use crate::utils::*; use crate::{BOT, CONFIG, DB}; use anyhow::Result; use chrono::{Datelike, Duration, Timelike, Utc}; use futures::TryFutureExt; use telegraph_rs::{html_to_node, Page, Telegraph}; use teloxide::prelude::*; use teloxide::types::{MessageId, ParseMode}; use v_htmlescape::escape; pub struct ExLoli { telegraph: Telegraph, } impl ExLoli { pub async fn new() -> Result<Self> { let telegraph = CONFIG.init_telegraph().await?; Ok(ExLoli { telegraph }) } /// 根据配置文件自动扫描并上传本子 pub async fn scan_and_upload(&self) -> Result<()> { // 筛选最新本子 let page_limit = CONFIG.exhentai.max_pages; let galleries = EXHENTAI.search_n_pages(page_limit).await?; // 从后往前爬, 保持顺序 for gallery in galleries.into_iter().rev() { info!("检测中:{}", gallery.url); match DB.query_gallery_by_url(&gallery.url) { Ok(g) => { self.update_gallery_tag(g, gallery) .await .log_on_error() .await; } _ => { self.upload_gallery(gallery).await.log_on_error().await; } } } Ok(()) } /// 更新画廊信息 async fn update_gallery_tag<'a>( &'a self, g: Gallery, gallery: BasicGalleryInfo<'a>, ) -> Result<()> { let now = Utc::now(); let duration = Utc::today().naive_utc() - g.publish_date; // 已删除画廊不更新 if (g.score - -1.0).abs() < f32::EPSILON // 7 天前的本子,如果是同一 weekday 发的则更新 || (duration.num_days() > 7 && !(now.weekday() == g.publish_date.weekday() && now.hour() % 8 == 0)) // 两天前的本子,每 4 小时更新一次 || (duration.num_days() > 2 && !(now.hour() % 4 == 0)) { debug!("跳过更新:{}", g.publish_date); return Ok(()); } // 检测是否需要更新 tag // TODO: 将 tags 塞到 BasicInfo 里 let info = gallery.into_full_info().await?; let new_tags = serde_json::to_string(&info.tags)?; if new_tags != g.tags { info!("tag 有更新,同步中..."); info!("画廊名称: {}", info.title); info!("画廊地址: {}", info.url); self.update_tag(&g, Some(&info)).await?; } Ok(()) } /// 上传指定 URL 的画廊 pub async fn upload_gallery_by_url(&self, url: &str) -> Result<()> { let gallery = match url.split_once('#') { Some((url, cover_index)) => { let mut gallery = EXHENTAI.get_gallery_by_url(url).await?; gallery.limit = false; gallery.cover_index = cover_index.parse()?; gallery } _ => { let mut gallery = EXHENTAI.get_gallery_by_url(url).await?; gallery.limit = false; gallery } }; self.upload_gallery(gallery).await } /// 将画廊上传到 telegram async fn upload_gallery<'a>(&'a self, basic_info: BasicGalleryInfo<'a>) -> Result<()> { info!("上传中,画廊名称: {}", basic_info.title); let mut gallery = basic_info.clone().into_full_info().await?; // 判断是否上传过历史版本 let old_gallery = Self::get_history_upload(&gallery).await; match &old_gallery { Ok(g) => { // 上传量已经达到限制的,不做更新 if g.upload_images as usize == CONFIG.exhentai.max_img_cnt && gallery.limit { return Err(anyhow::anyhow!("NoNeedToUpdate")); } // outdate 天以内上传过的,不重复发,在原消息的基础上更新 // 没有图片增删的,也不重复发送 let outdate = CONFIG.exhentai.outdate.unwrap_or(7); let not_outdated = g.publish_date + Duration::days(outdate) > Utc::today().naive_utc(); let not_bigupdate = gallery.img_pages.len() == g.upload_images as usize; // FIXME: 当前判断方法可能会误判,而且修改最大图片数量以后会失效 // 如果曾经更新过完整版,则继续上传完整版 if g.upload_images as usize > CONFIG.exhentai.max_img_cnt { gallery.limit = false; } // 如果没有过期或者没有图片修改,则直接更新历史消息 if not_outdated || not_bigupdate { info!("找到历史上传:{}", g.message_id); return self.update_gallery(g, Some(gallery), false).await; } else { info!("历史上传已过期:{}", g.message_id); } } Err(e) => warn!("没有找到历史上传:{}", e), } let mut img_urls = gallery.upload_images_to_telegraph().await?; img_urls.swap(0, basic_info.cover_index); // 上传到 telegraph let title = gallery.title(); let content = Self::get_article_string( &img_urls, gallery.img_pages.len(), old_gallery.as_ref().ok().map(|g| g.upload_images as usize), ); let page = self.publish_to_telegraph(title, &content).await?; info!("文章地址: {}", page.url); // 不需要原地更新的旧本子,发布新消息 let message = self.publish_to_telegram(&gallery, &page.url).await?; // 生成 poll_id,仅当旧画廊使用的新格式 poll_id 的情况下才会继承 let poll_id = old_gallery .and_then(|g| g.poll_id.parse::<i32>().map_err(anyhow::Error::new)) .unwrap_or(message.id.0); DB.insert_gallery(message.id.0, &gallery, page.url)?; DB.update_poll_id(message.id.0, &poll_id.to_string()) } /// 原地更新画廊,若 gallery 为 None 则原地更新为原画廊的完整版 pub async fn update_gallery<'a>( &self, ogallery: &Gallery, gallery: Option<FullGalleryInfo<'a>>, republish: bool, ) -> Result<()> { info!("更新画廊:{}", ogallery.get_url()); let gallery = match gallery { Some(v) => v, None => { let mut gallery: FullGalleryInfo = EXHENTAI .get_gallery_by_url(ogallery.get_url()) .and_then(|g| g.into_full_info()) .await?; gallery.limit = false; gallery } }; let img_urls = gallery.upload_images_to_telegraph().await?; let title = gallery.title(); let content = Self::get_article_string( &img_urls, gallery.img_pages.len(), (ogallery.upload_images != 0).then_some(ogallery.upload_images as usize), ); let page = if republish { self.publish_to_telegraph(title, &content).await? } else { self.edit_telegraph(extract_telegraph_path(&ogallery.telegraph), title, &content) .await? }; let url = format!("{}?_={}", page.url, get_timestamp()); self.update_message(ogallery.message_id, &gallery, &url, img_urls.len()) .await } /// 更新 tag,可选手动传入 new_gallery 避免重复请求 pub async fn update_tag<'a>( &self, old_gallery: &Gallery, new_gallery: Option<&FullGalleryInfo<'a>>, ) -> Result<()> { let url = old_gallery.get_url(); let mut _g = None; let new_gallery = match new_gallery { Some(v) => v, None => { // fuck lifetime _g = Some( EXHENTAI .get_gallery_by_url(&url) .and_then(|g| g.into_full_info()) .await?, ); _g.as_ref().unwrap() } }; // 更新 telegraph let path = extract_telegraph_path(&old_gallery.telegraph); let old_page = Telegraph::get_page(path, true).await?; let new_page = self .telegraph .edit_page( &old_page.path, new_gallery.title_jp.as_ref().unwrap_or(&new_gallery.title), &serde_json::to_string(&old_page.content)?, false, ) .await?; let upload_images = old_gallery.upload_images as usize; let message_id = old_gallery.message_id; self.update_message(message_id, new_gallery, &new_page.url, upload_images) .await } /// 更新旧消息并同时更新数据库 async fn update_message<'a>( &self, message_id: i32, gallery: &FullGalleryInfo<'a>, article: &str, upload_images: usize, ) -> Result<()> { info!("更新 Telegram 频道消息"); let text = Self::get_message_string(gallery, article); BOT.edit_message_text( CONFIG.telegram.channel_id.clone(), MessageId(message_id), &text, ) .parse_mode(ParseMode::Html) .await?; DB.update_gallery(message_id, gallery, article, upload_images) } /// 将画廊内容上传至 telegraph async fn publish_to_telegraph<'a>(&self, title: &str, content: &str) -> Result<Page> { info!("上传到 Telegraph"); let text = html_to_node(content); trace!("{}", text); Ok(self.telegraph.create_page(title, &text, false).await?) } /// 修改已有的 telegraph 文章 async fn edit_telegraph<'a>(&self, path: &str, title: &str, content: &str) -> Result<Page> { info!("更新 Telegraph: {}", path); let text = html_to_node(content); trace!("{}", text); Ok(self.telegraph.edit_page(path, title, &text, false).await?) } /// 将画廊内容上传至 telegraph async fn publish_to_telegram<'a>( &self, gallery: &FullGalleryInfo<'a>, article: &str, ) -> Result<Message> { info!("发布到 Telegram 频道"); let text = Self::get_message_string(gallery, article); Ok(BOT .send_message(CONFIG.telegram.channel_id.clone(), &text) .parse_mode(ParseMode::Html) .await?) } /// 生成用于发送消息的字符串 fn get_message_string<'a>(gallery: &FullGalleryInfo<'a>, article: &str) -> String { let mut tags = tags_to_string(&gallery.tags); tags.push_str(&format!( "\n<code> 预览</code>: <a href=\"{}\">{}</a>", article, escape(&gallery.title) )); tags.push_str(&format!("\n<code>原始地址</code>: {} ", gallery.url)); tags } /// 生成 telegraph 文章内容 fn get_article_string( image_urls: &[String], total_image: usize, last_uploaded: Option<usize>, ) -> String { let mut content = img_urls_to_html(image_urls); if last_uploaded.is_some() || image_urls.len() != total_image { content.push_str("<p>"); content.push_str(&format!("已上传 {}/{}", image_urls.len(), total_image,)); if let Some(v) = last_uploaded { content.push_str(&format!(",上次上传到 {}", v)); } if image_urls.len() != total_image { content.push_str(",完整版请前往 E 站观看"); } content.push_str("</p>"); } content } } impl ExLoli { /// 获取画廊的历史上传 pub async fn get_history_upload<'a>(gallery: &FullGalleryInfo<'a>) -> Result<Gallery> { let mut gallery_url = Some(gallery.url.clone()); while let Some(url) = &gallery_url { match DB.query_gallery_by_url(url) { Ok(v) => return Ok(v), _ => { let gallery = EXHENTAI.get_gallery_by_url(url).await?; let parent = gallery.into_full_info().await?; gallery_url = parent.parent; } } } Err(anyhow!("Not Found")) } }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/main.rs
src/main.rs
#[macro_use] extern crate log; #[macro_use] extern crate diesel; #[macro_use] extern crate diesel_migrations; #[macro_use] extern crate anyhow; use crate::config::Config; use crate::database::DataBase; use crate::exloli::ExLoli; use anyhow::Error; use futures::executor::block_on; use once_cell::sync::Lazy; use teloxide::prelude::*; use tokio::time::sleep; use std::env; use std::str::FromStr; use std::time; mod bot; mod config; mod database; //mod ehentai; mod exhentai; mod exloli; mod schema; mod trans; mod utils; mod xpath; static CONFIG: Lazy<Config> = Lazy::new(|| { let config_file = std::env::var("EXLOLI_CONFIG"); let config_file = config_file.as_deref().unwrap_or("config.toml"); Config::new(config_file).expect("配置文件解析失败") }); static BOT: Lazy<Bot> = Lazy::new(|| teloxide::Bot::new(&CONFIG.telegram.token)); static DB: Lazy<DataBase> = Lazy::new(|| DataBase::init().expect("数据库初始化失败")); static EXLOLI: Lazy<ExLoli> = Lazy::new(|| block_on(ExLoli::new()).expect("登录失败")); #[tokio::main] async fn main() { env_logger::builder() .format_timestamp_secs() .write_style(env_logger::WriteStyle::Auto) .filter(Some("teloxide"), log::LevelFilter::Error) .filter( Some("exloli"), log::LevelFilter::from_str(&CONFIG.log_level).expect("LOG 等级设置错误"), ) .init(); env::set_var("DATABASE_URL", &CONFIG.database_url); if let Err(e) = run().await { error!("{}", e); } } fn init_args() -> getopts::Matches { let args = env::args().collect::<Vec<_>>(); let mut opts = getopts::Options::new(); opts.optflag("", "debug", "调试模式,不自动爬本"); opts.optflag("h", "help", "打印帮助"); let matches = match opts.parse(&args[1..]) { Ok(v) => v, Err(e) => panic!("{}", e), }; if matches.opt_present("h") { let brief = format!("Usage: {} [options]", args[0]); print!("{}", opts.usage(&brief)); std::process::exit(0); } matches } async fn run() -> Result<(), Error> { let matches = init_args(); env::var("DATABASE_URL").expect("请设置 DATABASE_URL"); let debug_mode = matches.opt_present("debug"); tokio::spawn(async move { sleep(time::Duration::from_secs(10)).await; bot::start_bot(BOT.clone()).await }); loop { if !debug_mode { info!("定时更新开始"); let result = EXLOLI.scan_and_upload().await; if let Err(e) = result { error!("定时更新出错:{}", e); } else { info!("定时更新完成"); } } info!("休眠中,预计 {} 分钟后开始工作", CONFIG.interval / 60); sleep(time::Duration::from_secs(CONFIG.interval)).await; } }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/bot/command.rs
src/bot/command.rs
use crate::bot::utils::*; use crate::database::Gallery; use crate::exhentai::EXHENTAI; use crate::*; use futures::TryFutureExt; use std::convert::TryInto; use std::fmt::{self, Debug, Formatter}; use std::str::FromStr; use teloxide::types::Message; pub enum CommandError { /// 命令解析错误 WrongCommand(&'static str), /// 不是自己的命令 NotACommand, } #[derive(PartialEq)] pub enum InputGallery { ExHentaiUrl(String), Gallery(Gallery), } impl InputGallery { /// 转换为 `Gallery`,会自动请求历史画廊 pub async fn to_gallery(&self) -> anyhow::Result<Gallery> { match &self { Self::Gallery(g) => Ok(g.clone()), Self::ExHentaiUrl(s) => match DB.query_gallery_by_url(s) { Err(_) => { let gallery = EXHENTAI .get_gallery_by_url(s) .and_then(|g| g.into_full_info()) .await?; Ok(ExLoli::get_history_upload(&gallery).await?) } v => v, }, } } } impl Debug for InputGallery { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Self::ExHentaiUrl(s) => f.debug_tuple("Url").field(&s).finish(), Self::Gallery(g) => f.debug_tuple("Message").field(&g.message_id).finish(), } } } #[derive(PartialEq, Debug)] pub enum RuaCommand { // 上传指定画廊 Upload(Vec<String>), // 查询指定画廊 Query(Vec<InputGallery>), // Ping bot Ping, // 用该命令回复一条画廊以将其删除 Delete, // 这是真的删除,彻底删除 RealDelete, // 按评分高低查询一段时间内的本子,格式 /best 最少几天前 最多几天前 多少本 Best([i64; 2]), // 用该命令回复一条画廊以上传其完整版本 Full(Vec<InputGallery>), // 用该命令回复一条画廊以重新上传 ReUpload(InputGallery), // 更新 tag UpdateTag(Vec<InputGallery>), } impl RuaCommand { /// 将消息解析为命令 pub async fn parse(bot: Bot, message: &Message, bot_id: &str) -> Result<Self, CommandError> { use CommandError::*; let text = message.text().unwrap_or(""); if !text.starts_with('/') { return Err(NotACommand); } let (cmd, args) = text .split_once(|c| c == ' ' || c == '\n') .unwrap_or((text, "")); let (cmd, bot_name) = cmd.split_once('@').unwrap_or((cmd, "")); // remove leading `/` let cmd = &cmd[1..]; if !bot_name.is_empty() && bot_name != bot_id { return Err(NotACommand); } debug!("收到命令:/{} {}", cmd, args); let (is_admin, trusted) = check_is_channel_admin(bot, message).await; match (cmd, is_admin, trusted) { ("ping", _, _) => Ok(Self::Ping), ("full", _, true) => { let arg = get_input_gallery(message, args); match arg.is_empty() { false => Ok(Self::Full(arg)), true => Err(WrongCommand("用法:/full [回复|画廊地址|消息地址]...")), } } ("uptag", _, true) => { let arg = get_input_gallery(message, args); match arg.is_empty() { false => Ok(Self::UpdateTag(arg)), true => Err(WrongCommand("用法:/uptag [回复|画廊地址|消息地址]...")), } } ("reupload", true, _) => { let reply_to = message.reply_to_gallery(); match reply_to { Some(g) => Ok(Self::ReUpload(InputGallery::Gallery(g))), None => Err(WrongCommand( "用法:请回复一个需要替换的画廊,并附上新画廊地址", )), } } ("delete", true, _) => { if message.reply_to_gallery().is_none() { return Err(WrongCommand("用法:请回复一个需要删除的画廊")); } Ok(Self::Delete) } ("real_delete", true, _) => { if message.reply_to_gallery().is_none() { return Err(WrongCommand("用法:请回复一个需要彻底删除的画廊")); } Ok(Self::RealDelete) } ("upload", _, true) => { let urls = get_exhentai_urls(message.text().unwrap_or_default()); if urls.is_empty() { Err(WrongCommand("用法:/upload 画廊地址...")) } else { Ok(Self::Upload(urls)) } } ("best", _, _) => match parse_command_best(args) { Some(mut v) => { v[0] = v[0].min(3650); v[1] = v[1].min(3650); Ok(RuaCommand::Best(v)) } _ => Err(WrongCommand("用法:/best 起始时间 终止时间")), }, ("query", _, _) => { let arg = get_input_gallery(message, args); match arg.is_empty() { false => Ok(Self::Query(arg)), true => Err(WrongCommand("用法:/query [回复|画廊地址|消息地址]...")), } } _ => { if bot_name == bot_id { Err(WrongCommand("")) } else { Err(NotACommand) } } } } } /// 将字符串解析为三个数字 fn parse_command_best(input: &str) -> Option<[i64; 2]> { let v = input .split_ascii_whitespace() .map(i64::from_str) .collect::<Result<Vec<_>, _>>() .ok(); if let Some(v) = v.and_then(|v| TryInto::<[i64; 2]>::try_into(v).ok()) { return Some(v); } None } /// 提取字符串中的 e 站地址 fn get_exhentai_urls(s: &str) -> Vec<String> { EXHENTAI_URL .captures_iter(s) .filter_map(|c| c.get(0).map(|m| m.as_str().to_owned())) .collect::<Vec<_>>() } fn get_input_gallery(message: &Message, s: &str) -> Vec<InputGallery> { let i1 = MESSAGE_URL.captures_iter(s).filter_map(|c| { c.get(1) .and_then(|s| s.as_str().parse::<i32>().ok()) .and_then(|n| DB.query_gallery(n).ok()) .map(InputGallery::Gallery) }); let i2 = EXHENTAI_URL.captures_iter(s).filter_map(|c| { c.get(0) .map(|s| InputGallery::ExHentaiUrl(s.as_str().to_owned())) }); let mut ret = i1.chain(i2).collect::<Vec<_>>(); if let (true, Some(g)) = (ret.is_empty(), message.reply_to_gallery()) { ret.push(InputGallery::Gallery(g)); } ret }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/bot/utils.rs
src/bot/utils.rs
use crate::database::Gallery; use crate::{CONFIG, DB}; use dashmap::DashMap; use once_cell::sync::Lazy; use regex::Regex; use std::collections::VecDeque; use std::fmt::Debug; use std::hash::Hash; use std::ops::Deref; use std::time::{Duration, Instant}; use teloxide::prelude::*; use teloxide::types::*; use uuid::Uuid; pub static EXHENTAI_URL: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://e.hentai\.org/g/\d+/[0-9a-f]+/?(#\d+)?").unwrap()); pub static MESSAGE_URL: Lazy<Regex> = Lazy::new(|| { let channel_id = &CONFIG.telegram.channel_id; Regex::new( &format!(r"https://t.me/{}/(\d+)", channel_id) .replace("/-100", "/") .replace('@', ""), ) .unwrap() }); pub trait MessageExt { fn is_from_my_group(&self) -> bool; fn from_username(&self) -> Option<&String>; fn reply_to_user(&self) -> Option<&User>; fn reply_to_gallery(&self) -> Option<Gallery>; } impl MessageExt for Message { // 判断消息来源是否是指定群组 fn is_from_my_group(&self) -> bool { CONFIG.telegram.group_id == self.chat.id } fn from_username(&self) -> Option<&String> { if let Some(User { username, .. }) = self.from() { return username.as_ref(); } None } fn reply_to_user(&self) -> Option<&User> { if let Some(reply) = self.reply_to_message() { return reply.from(); } None } fn reply_to_gallery(&self) -> Option<Gallery> { self.reply_to_message() .and_then(|message| message.forward_from_message_id()) .and_then(|mess_id| DB.query_gallery(mess_id).ok()) } } // TODO: 缓存 /// 获取管理员列表 async fn get_admins(bot: Bot) -> Option<Vec<User>> { let mut admins = bot .get_chat_administrators(CONFIG.telegram.channel_id.clone()) .await .ok()?; admins.extend( bot.get_chat_administrators(CONFIG.telegram.group_id) .await .ok()?, ); Some(admins.into_iter().map(|member| member.user).collect()) } // 检测是否是指定频道的管理员 pub async fn check_is_channel_admin(bot: Bot, message: &Message) -> (bool, bool) { // 先检测是否为匿名管理员 let from_user = message.from(); if from_user .map(|u| u.username == Some("GroupAnonymousBot".into())) .unwrap_or(false) && message.is_from_my_group() { return (true, true); } let admins = get_admins(bot).await.unwrap_or_default(); let is_admin = message .from() .map(|user| admins.iter().map(|admin| admin == user).any(|x| x)) .unwrap_or(false); let trusted = is_admin || CONFIG .telegram .trusted_users .contains(message.from_username().unwrap_or(&String::new())); (is_admin, trusted) } pub fn inline_article<S1, S2>(title: S1, content: S2) -> InlineQueryResultArticle where S1: Into<String>, S2: Into<String>, { let content = content.into(); let uuid = Uuid::new_v3( &Uuid::from_bytes(b"EXLOLIINLINEQURY".to_owned()), content.as_bytes(), ); InlineQueryResultArticle::new( uuid.to_string(), title.into(), InputMessageContent::Text(InputMessageContentText::new(content)), ) } pub fn poll_keyboard(poll_id: i32, votes: &[i32; 5]) -> InlineKeyboardMarkup { let sum = votes.iter().sum::<i32>(); let votes: Box<dyn Iterator<Item = f32>> = if sum == 0 { Box::new([0.].iter().cloned().cycle()) } else { Box::new(votes.iter().map(|&i| i as f32 / sum as f32 * 100.)) }; let options = ["我瞎了", "不咋样", "还行吧", "不错哦", "太棒了"] .iter() .zip(votes) .enumerate() .map(|(idx, (name, vote))| { vec![InlineKeyboardButton::new( format!("{:.0}% {}", vote, name), InlineKeyboardButtonKind::CallbackData(format!("vote {} {}", poll_id, idx + 1)), )] }) .collect::<Vec<_>>(); InlineKeyboardMarkup::new(options) } pub fn query_best_keyboard(from: i64, to: i64, offset: i64) -> InlineKeyboardMarkup { InlineKeyboardMarkup::new(vec![["<<", "<", ">", ">>"] .iter() .map(|&s| { InlineKeyboardButton::new( s, InlineKeyboardButtonKind::CallbackData(format!("{} {} {} {}", s, from, to, offset)), ) }) .collect::<Vec<_>>()]) } pub struct Vote([i32; 5]); impl Vote { pub fn new(vote: [i32; 5]) -> Self { Self(vote) } pub fn score(&self) -> f32 { Self::wilson_score(&self.0) } /// 威尔逊得分 /// 基于:https://www.jianshu.com/p/4d2b45918958 pub fn wilson_score(votes: &[i32]) -> f32 { let base = [0., 0.25, 0.5, 0.75, 1.]; let count = votes.iter().sum::<i32>() as f32; if count == 0. { return 0.; } let mean = Iterator::zip(votes.iter(), base.iter()) .map(|(&a, &b)| a as f32 * b) .sum::<f32>() / count; let var = Iterator::zip(votes.iter(), base.iter()) .map(|(&a, &b)| (mean - b).powi(2) * a as f32) .sum::<f32>() / count; // 80% 置信度 let z = 1.281f32; (mean + z.powi(2) / (2. * count) - ((z / (2. * count)) * (4. * count * var + z.powi(2)).sqrt())) / (1. + z.powi(2) / count) } /// 给用户展示的信息 pub fn info(&self) -> String { let cnt = self.0.iter().sum::<i32>(); let score = self.score(); format!("当前 {} 人投票,{:.2} 分", cnt, score * 100.) } } impl Deref for Vote { type Target = [i32; 5]; fn deref(&self) -> &[i32; 5] { &self.0 } } /// 一个用于限制请求频率的数据结构 #[derive(Debug)] pub struct RateLimiter<T: Hash + Eq> { interval: Duration, limit: usize, data: DashMap<T, VecDeque<Instant>>, } impl<T: Hash + Eq> RateLimiter<T> { pub fn new(interval: Duration, limit: usize) -> Self { assert_ne!(limit, 0); Self { interval, limit, data: Default::default(), } } /// 插入数据,正常情况下返回 None,如果达到了限制则返回需要等待的时间 pub fn insert(&self, key: T) -> Option<Duration> { let mut entry = self.data.entry(key).or_insert_with(VecDeque::new); let entry = entry.value_mut(); // 插入时,先去掉已经过期的元素 while let Some(first) = entry.front() { if first.elapsed() > self.interval { entry.pop_front(); } else { break; } } if entry.len() == self.limit { return entry.front().cloned().map(|d| self.interval - d.elapsed()); } entry.push_back(Instant::now()); None } }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/bot/mod.rs
src/bot/mod.rs
mod command; mod handler; mod utils; use handler::*; use teloxide::prelude::*; pub async fn start_bot(bot: Bot) { info!("BOT 启动"); let handler = dptree::entry() .branch(Update::filter_message().branch(Message::filter_text().endpoint(message_handler))) .branch(Update::filter_poll().endpoint(poll_handler)) .branch(Update::filter_inline_query().endpoint(inline_handler)) .branch(Update::filter_callback_query().endpoint(callback_handler)); Dispatcher::builder(bot, handler) .enable_ctrlc_handler() .build() .dispatch() .await; }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/bot/handler.rs
src/bot/handler.rs
use super::utils::*; use crate::bot::command::*; use crate::database::Gallery; use crate::utils::get_message_url; use crate::*; use anyhow::{Context, Result}; use chrono::{Duration, Utc}; use futures::{FutureExt, TryFutureExt}; use std::convert::TryInto; use std::future::Future; use teloxide::types::*; use teloxide::{ApiError, RequestError}; macro_rules! reply_to { ($b:expr, $m:expr, $t:expr) => { $b.send_message($m.chat.id, $t).reply_to_message_id($m.id) }; } static LIMIT: Lazy<RateLimiter<u64>> = Lazy::new(|| RateLimiter::new(std::time::Duration::from_secs(60), 10)); // async fn on_new_gallery(bot: Bot, message: &Message) -> Result<()> { info!("频道消息更新,发送投票"); // 辣鸡 tg 安卓客户端在置顶消息过多时似乎在进群时会卡住 bot.unpin_chat_message(message.chat.id) .message_id(message.id) .await?; let message_id = message.forward_from_message_id().unwrap(); let poll_id = DB.query_poll_id(message_id)?.parse::<i32>()?; let votes = Vote::new(DB.query_vote(poll_id)?); let options = poll_keyboard(poll_id, &votes); reply_to!(bot, message, votes.info()) .reply_markup(options) .await?; Ok(()) } // async fn cmd_delete(bot: Bot, message: &Message, real: bool) -> Result<Message> { info!("执行命令: delete_{} {:?}", real, message.id); let to_del = message.reply_to_message().context("找不到回复")?; let channel = to_del.forward_from_chat().context("获取来源对话失败")?; let msg_id = to_del .forward_from_message_id() .context("获取转发来源失败")?; bot.delete_message(to_del.chat.id, to_del.id).await?; bot.delete_message(channel.id, MessageId(msg_id)).await?; let gallery = DB.query_gallery(msg_id)?; match real { false => DB.delete_gallery(msg_id)?, _ => DB.real_delete_gallery(msg_id)?, } let text = format!("画廊 {} 已删除", gallery.get_url()); Ok(bot.send_message(message.chat.id, text).await?) } async fn do_chain_action<T, F, Fut>( bot: Bot, message: &Message, input: &[T], action: F, ) -> Result<Message> where F: Fn(&T) -> Fut, Fut: Future<Output = Result<Option<()>>>, { let mut text = "收到命令,执行中……".to_owned(); let mut reply_message = reply_to!(bot, message, &text).await?; let mut fail_cnt = 0; for (idx, entry) in input.iter().enumerate() { let message = match action(entry).await { Ok(Some(_)) => format!("\n第 {} 本 - 成功", idx + 1), Ok(None) => format!("\n第 {} 本 - 无上传记录", idx + 1), Err(e) => { let source = e.source().map(|e| e.to_string()).unwrap_or_default(); fail_cnt += 1; format!("\n第 {} 本 - 失败:{} => {}", idx + 1, e, source) } }; text.push_str(&message); reply_message = bot .edit_message_text(reply_message.chat.id, reply_message.id, &text) .await?; } text.push_str("\n执行完毕"); if fail_cnt > 0 { text.push_str(&format!( ",失败 {} 个<a href=\"tg://user?id={}\">\u{200b}</a>", fail_cnt, message.from().map(|u| u.id.0).unwrap_or_default() )); } Ok(bot .edit_message_text(reply_message.chat.id, reply_message.id, text) .parse_mode(ParseMode::Html) .await?) } async fn cmd_upload(bot: Bot, message: &Message, urls: &[String]) -> Result<Message> { info!("执行命令: upload {:?}", urls); do_chain_action(bot, message, urls, |url| { let url = url.clone(); async move { EXLOLI.upload_gallery_by_url(&url).await.map(Some) }.boxed() }) .await } async fn cmd_reupload(bot: Bot, message: &Message, old_gallery: &InputGallery) -> Result<Message> { info!("执行命令: reupload {:?}", old_gallery); let mut text = "收到命令,执行中……".to_owned(); let reply_message = reply_to!(bot, message, &text).await?; let gallery = old_gallery.to_gallery().await?; EXLOLI.update_gallery(&gallery, None, true).await?; text.push_str("\n执行完毕"); Ok(bot .edit_message_text(reply_message.chat.id, reply_message.id, text) .parse_mode(ParseMode::Html) .await?) } async fn cmd_full(bot: Bot, message: &Message, galleries: &[InputGallery]) -> Result<Message> { info!("执行命令: full {:?}", galleries); do_chain_action(bot, message, galleries, |gallery| { let gallery = match block_on(gallery.to_gallery()) { Ok(v) => v, _ => return async { Ok(None) }.boxed(), }; async move { EXLOLI.update_gallery(&gallery, None, false).await.map(Some) }.boxed() }) .await } async fn cmd_update_tag( bot: Bot, message: &Message, galleries: &[InputGallery], ) -> Result<Message> { info!("执行命令: uptag {:?}", galleries); do_chain_action(bot, message, galleries, |gallery| { // TODO: 为啥要 block let gallery = match block_on(gallery.to_gallery()) { Ok(v) => v, _ => return async { Ok(None) }.boxed(), }; async move { EXLOLI.update_tag(&gallery, None).await.map(Some) }.boxed() }) .await } fn query_best_text(from: i64, to: i64, offset: i64) -> Result<String> { let (from_d, to_d) = ( Utc::today().naive_utc() - Duration::days(from), Utc::today().naive_utc() - Duration::days(to), ); let galleries = DB.query_best(from_d, to_d, offset)?; let list = galleries .iter() .map(|g| { format!( r#"<code>{:.2}</code> - <a href="{}">{}</a>"#, g.score * 100., get_message_url(g.message_id), g.title ) }) .collect::<Vec<_>>() .join("\n"); let mut text = format!("最近 {} - {} 天的本子排名({}):\n", from, to, offset); text.push_str(&list); Ok(text) } async fn cmd_best(bot: Bot, message: &Message, from: i64, to: i64) -> Result<Message> { info!("执行命令: best {} {}", from, to); let text = query_best_text(from, to, 1)?; let reply_markup = query_best_keyboard(from, to, 1); Ok(reply_to!(bot, message, text) .reply_markup(reply_markup) .parse_mode(ParseMode::Html) .await?) } /// 查询画廊,若失败则返回失败消息,成功则直接发送 async fn cmd_query(bot: Bot, message: &Message, galleries: &[InputGallery]) -> Result<Message> { info!("执行命令: query {:?}", galleries); let text = match galleries.len() { 1 => galleries[0] .to_gallery() .await .and_then(|g| cmd_query_rank(&g)) .unwrap_or_else(|_| "未找到!".to_owned()), _ => futures::future::join_all(galleries.iter().map(|g| { g.to_gallery() .and_then(|g| async move { Ok(get_message_url(g.message_id)) }) .unwrap_or_else(|_| "未找到!".to_owned()) })) .await .join("\n"), }; Ok(reply_to!(bot, message, text) .disable_web_page_preview(true) .await?) } fn cmd_query_rank(gallery: &Gallery) -> Result<String> { let rank = DB.get_rank(gallery.score)?; Ok(format!( "标题:{}\n消息:{}\n地址:{}\n评分:{:.2}\n位置:{:.2}%\n上传日期:{}", gallery.title, get_message_url(gallery.message_id), gallery.get_url(), gallery.score * 100., rank * 100., gallery.publish_date, )) } /// 判断是否是新本子的发布信息 fn is_new_gallery(message: &Message) -> bool { // 判断是否是由官方 bot 转发的 let user = match message.from() { Some(v) => v, _ => return false, }; if user.id.0 != 777000 { return false; } // 判断是否是新本子的发布信息 message .text() .map(|s| s.contains("原始地址")) .unwrap_or(false) } pub async fn message_handler(message: Message, bot: Bot) -> Result<()> { use RuaCommand::*; trace!("{:#?}", message); // 如果是新本子上传的消息,则回复投票并取消置顶 if is_new_gallery(&message) && message.is_from_my_group() { on_new_gallery(bot.clone(), &message) .await .log_on_error() .await; } // 其他命令 let mut to_delete = vec![message.id]; let cmd = RuaCommand::parse(bot.clone(), &message, &CONFIG.telegram.bot_id).await; match &cmd { Err(CommandError::WrongCommand(help)) => { warn!("错误的命令:{}", help); if !help.is_empty() { let msg = reply_to!(bot, message, *help).await?; to_delete.push(msg.id); } else { bot.delete_message(message.chat.id, message.id).await?; } } Ok(Ping) => { info!("执行命令:ping"); let msg = reply_to!(bot, message, "pong").await?; to_delete.push(msg.id); } Ok(Full(g)) => { to_delete.push(cmd_full(bot.clone(), &message, g).await?.id); } Ok(Delete) => { to_delete.push(cmd_delete(bot.clone(), &message, false).await?.id); } Ok(RealDelete) => { to_delete.push(cmd_delete(bot.clone(), &message, true).await?.id); } Ok(Upload(urls)) => { to_delete.push(cmd_upload(bot.clone(), &message, urls).await?.id); } Ok(UpdateTag(g)) => { to_delete.push(cmd_update_tag(bot.clone(), &message, g).await?.id); } Ok(Query(gs)) => { cmd_query(bot.clone(), &message, gs).await?; } Ok(Best([from, to])) => { to_delete.push(cmd_best(bot.clone(), &message, *from, *to).await?.id); } Ok(ReUpload(g)) => { to_delete.push(cmd_reupload(bot.clone(), &message, g).await?.id); } // 收到无效命令则立即返回 Err(CommandError::NotACommand) => return Ok(()), } // 对 query 和 best 命令的调用保留 if matches!(cmd, Ok(Query(_))) { to_delete.clear(); } // 没有直接回复画廊的 upload full update_tag 则保留 if matches!(cmd, Ok(Upload(_)) | Ok(Full(_)) | Ok(UpdateTag(_))) && message.reply_to_gallery().is_none() { to_delete.clear(); } // 定时删除群组内的 BOT 消息 if !to_delete.is_empty() && message.is_from_my_group() { let chat_id = message.chat.id; tokio::spawn(async move { sleep(time::Duration::from_secs(300)).await; for id in to_delete { info!("清除消息 {:?}", id); bot.delete_message(chat_id, id).await.log_on_error().await; } }); } Ok(()) } pub async fn poll_handler(poll: Poll, _bot: Bot) -> Result<()> { let options = poll.options; let votes = options.iter().map(|s| s.voter_count).collect::<Vec<_>>(); let score = Vote::wilson_score(&votes); let votes = serde_json::to_string(&votes)?; info!("收到投票:{} -> {}", poll.id, score); DB.update_score(&poll.id, score, votes) } pub async fn inline_handler(query: InlineQuery, bot: Bot) -> Result<()> { let text = query.query.trim(); info!("行内查询:{}", text); let mut answer = vec![]; if EXHENTAI_URL.is_match(text) { if let Ok(v) = DB.query_gallery_by_url(&query.query) { let content = cmd_query_rank(&v)?; answer.push(InlineQueryResult::Article(inline_article(v.title, content))); } } if answer.is_empty() { answer.push(InlineQueryResult::Article(inline_article( "未找到", "没有找到", ))); } bot.answer_inline_query(query.id, answer).await?; Ok(()) } fn split_vec<T: FromStr>(s: &str) -> std::result::Result<Vec<T>, T::Err> { s.split(' ') .map(T::from_str) .collect::<std::result::Result<Vec<_>, _>>() } async fn callback_change_page(bot: Bot, message: &Message, cmd: &str, data: &str) -> Result<()> { info!("翻页:{:?} {}", message.id, cmd); // vec![from, to, offset] let data = split_vec::<i64>(data)?; let [from, to, mut offset] = match TryInto::<[i64; 3]>::try_into(data) { Ok(v) => v, _ => return Ok(()), }; match cmd { ">" => offset += 20, "<" => offset -= 20, ">>" => offset = -1, "<<" => offset = 1, _ => (), }; let text = query_best_text(from, to, offset)?; let reply = query_best_keyboard(from, to, offset); bot.edit_message_text(message.chat.id, message.id, &text) .parse_mode(ParseMode::Html) .reply_markup(reply) .await?; Ok(()) } async fn callback_poll(bot: Bot, message: &Message, user_id: u64, data: &str) -> Result<()> { let data = split_vec::<i32>(data)?; let [poll_id, option] = match TryInto::<[i32; 2]>::try_into(data) { Ok(v) => v, _ => return Ok(()), }; DB.insert_vote(user_id, poll_id, option)?; let votes = Vote::new(DB.query_vote(poll_id)?); let reply = poll_keyboard(poll_id, &votes); let score = votes.score(); let ret = bot .edit_message_text(message.chat.id, message.id, votes.info()) .reply_markup(reply) .await; // 用户可能会点多次相同选项,此时会产生一个 MessageNotModified 的错误 match ret { Err(RequestError::Api(ApiError::MessageNotModified)) => Ok(()), _ => ret.map(|_| ()), }?; DB.update_score(&poll_id.to_string(), score, serde_json::to_string(&*votes)?)?; info!("收到投票:[{}] {} -> {}", user_id, poll_id, score); Ok(()) } pub async fn callback_handler(callback: CallbackQuery, bot: Bot) -> Result<()> { debug!("回调:{:?}", callback.data); if let Some(d) = LIMIT.insert(callback.from.id.0) { warn!("用户 {} 操作频率过高", callback.from.id.0); bot.answer_callback_query(callback.id) .text(format!("操作频率过高,请 {} 秒后再尝试", d.as_secs())) .show_alert(true) .await?; return Ok(()); } let (cmd, data) = match callback.data.as_ref().and_then(|v| v.split_once(' ')) { Some(v) => v, None => return Ok(()), }; let message = match callback.message { Some(v) => v, None => { bot.answer_callback_query(callback.id) .text("该消息过旧") .show_alert(true) .await?; return Ok(()); } }; tokio::spawn({ let id = callback.id; let bot = bot.clone(); async move { bot.answer_callback_query(id).await.log_on_error().await; } }); match cmd { "<<" | ">>" | "<" | ">" => { callback_change_page(bot, &message, cmd, data).await?; } "vote" => { callback_poll(bot, &message, callback.from.id.0, data).await?; } _ => warn!("未知指令:{}", cmd), }; Ok(()) }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/ehentai/client.rs
src/ehentai/client.rs
use anyhow::Result; use reqwest::header::*; use reqwest::{Client, Response}; use std::time::Duration; use crate::ehentai::types::Gallery; use crate::xpath::parse_html; macro_rules! send { ($e:expr) => { $e.send().await.and_then(Response::error_for_status) }; } const DEFAULT_HEADERS: [(HeaderName, &'static str); 9] = [ ( ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", ), (ACCEPT_ENCODING, "gzip, deflate, br"), (ACCEPT_LANGUAGE, "zh-CN,en-US;q=0.7,en;q=0.3"), (CACHE_CONTROL, "max-age=0"), (CONNECTION, "keep-alive"), // TODO: 支持 e-hentai (HOST, "exhentai.org"), (REFERER, "https://exhentai.org"), (UPGRADE_INSECURE_REQUESTS, "1"), ( USER_AGENT, "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0", ), ]; pub struct EHentaiClient { client: Client, } impl EHentaiClient { pub async fn new(cookie: String) -> Result<Self> { let mut headers = DEFAULT_HEADERS .iter() .map(|(k, v)| (k.clone(), v.parse().unwrap())) .collect::<HeaderMap>(); headers.insert(COOKIE, cookie.parse().unwrap()); let client = Client::builder() .cookie_store(true) .default_headers(headers) .timeout(Duration::from_secs(15)) .build()?; let _response = send!(client.get("https://exhentai.org/uconfig.php"))?; let _response = send!(client.get("https://exhentai.org/mytags"))?; Ok(Self { client }) } /// 使用指定参数查询符合要求的画廊列表 pub async fn search(&self, params: &[(&str, &str)], page: i32) -> Result<Vec<(String, String)>> { let resp = send!(self .client .get("https://exhentai.org") .query(params) .query(&[("page", &page.to_string())]))?; let text = resp.text().await?; let html = parse_html(text)?; let gl_list = html.xpath_elem(r#"//table[@class="itg gltc"]/tr[position() > 1]"#)?; let mut ret = vec![]; for gl in gl_list { let title = gl .xpath_text(r#".//td[@class="gl3c glname"]/a/div/text()"#)? .swap_remove(0); let url = gl .xpath_text(r#".//td[@class="gl3c glname"]/a/@href"#)? .swap_remove(0); ret.push((title, url)) } Ok(ret) } /// 根据画廊 URL 获取画廊的完整信息 pub async fn gallery(&self, url: &str) -> Result<Gallery> { let resp = send!(self.client.get(url))?; let mut html = parse_html(resp.text().await?)?; // 标题 let title = html.xpath_text(r#"//h1[@id="gn"]/text()"#)?.swap_remove(0); let title_jp = html .xpath_text(r#"//h1[@id="gj"]/text()"#) .map(|mut n| n.swap_remove(0)) .ok(); // 父画廊 let parent = html .xpath_text(r#"//tr[contains(./td[1]/text(), "Parent:")]/td[2]/a/@href"#) .ok() .map(|mut v| v.swap_remove(0)); // 标签 let mut tags = vec![]; for ele in html .xpath_elem(r#"//div[@id="taglist"]//tr"#) .unwrap_or_default() { let tag_set_name = ele.xpath_text(r#"./td[1]/text()"#)?[0] .trim_matches(':') .to_owned(); let tag = ele.xpath_text(r#"./td[2]/div/a/text()"#)?; tags.push((tag_set_name, tag)); } // 图片列表 let mut images = html.xpath_text(r#"//div[@id="gdt"]//a/@href"#)?; while let Ok(next_page) = html.xpath_text(r#"//table[@class="ptt"]//td[last()]/a/@href"#) { let resp = send!(self.client.get(&next_page[0]))?; html = parse_html(resp.text().await?)?; images.extend(html.xpath_text(r#"//div[@id="gdt"]//a/@href"#)?); } Ok(Gallery { title, title_jp, url: url.to_string(), parent, tags, images }) } /// 根据图片页面的 URL 解析出真实的图片地址 pub async fn image(&self, url: &str) -> Result<String> { let resp = send!(self.client.get(url))?; let url = parse_html(resp.text().await?)? .xpath_text(r#"//img[@id="img"]/@src"#)? .swap_remove(0); Ok(url) } }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/ehentai/types.rs
src/ehentai/types.rs
/// 画廊信息 #[derive(Debug)] pub struct Gallery { /// 画廊标题 pub title: String, /// 画廊日文标题 pub title_jp: Option<String>, /// 画廊地址 pub url: String, /// 父画廊地址 pub parent: Option<String>, /// 标签 pub tags: Vec<(String, Vec<String>)>, /// 图片页面的地址 pub images: Vec<String>, }
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
lolishinshi/exloli
https://github.com/lolishinshi/exloli/blob/c3d9604c8cf125eff15b45e7336a627a6f50b75c/src/ehentai/mod.rs
src/ehentai/mod.rs
mod client; mod types; pub use client::EHentaiClient;
rust
MIT
c3d9604c8cf125eff15b45e7336a627a6f50b75c
2026-01-04T20:23:19.139359Z
false
alexmoon/bluest
https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/corebluetooth.rs
src/corebluetooth.rs
#![allow(unexpected_cfgs)] use crate::Uuid; pub mod adapter; pub mod characteristic; pub mod descriptor; pub mod device; pub mod error; #[cfg(feature = "l2cap")] pub mod l2cap_channel; pub mod service; mod ad; pub(crate) mod delegates; pub(crate) mod dispatch; /// A platform-specific device identifier. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct DeviceId(Uuid); impl std::fmt::Display for DeviceId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.0, f) } }
rust
Apache-2.0
37e353d778b43d4892d2b7315cb5fba6cd5cb969
2026-01-04T20:23:19.181316Z
false
alexmoon/bluest
https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/descriptor.rs
src/descriptor.rs
use crate::{sys, Result, Uuid}; /// A Bluetooth GATT descriptor #[derive(Debug, Clone, PartialEq, Eq)] pub struct Descriptor(pub(crate) sys::descriptor::DescriptorImpl); impl Descriptor { /// The [`Uuid`] identifying the type of this GATT descriptor /// /// # Panics /// /// On Linux, this method will panic if there is a current Tokio runtime and it is single-threaded, if there is no /// current Tokio runtime and creating one fails, or if the underlying [`Descriptor::uuid_async()`] method /// fails. #[inline] pub fn uuid(&self) -> Uuid { self.0.uuid() } /// The [`Uuid`] identifying the type of this GATT descriptor #[inline] pub async fn uuid_async(&self) -> Result<Uuid> { self.0.uuid_async().await } /// The cached value of this descriptor /// /// If the value has not yet been read, this method may either return an error or perform a read of the value. #[inline] pub async fn value(&self) -> Result<Vec<u8>> { self.0.value().await } /// Read the value of this descriptor from the device #[inline] pub async fn read(&self) -> Result<Vec<u8>> { self.0.read().await } /// Write the value of this descriptor on the device to `value` #[inline] pub async fn write(&self, value: &[u8]) -> Result<()> { self.0.write(value).await } }
rust
Apache-2.0
37e353d778b43d4892d2b7315cb5fba6cd5cb969
2026-01-04T20:23:19.181316Z
false
alexmoon/bluest
https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/lib.rs
src/lib.rs
#![warn(missing_docs)] //! Bluest is a cross-platform [Bluetooth Low Energy] (BLE) library for [Rust]. It currently supports Windows (version //! 10 and later), MacOS/iOS, and Linux. Android support is planned. //! //! The goal of Bluest is to create a *thin* abstraction on top of the platform-specific Bluetooth APIs in order to //! provide safe, cross-platform access to Bluetooth LE devices. The crate currently supports the GAP Central and //! GATT Client roles. Peripheral and Server roles are not supported. //! //! [Rust]: https://www.rust-lang.org/ //! [Bluetooth Low Energy]: https://www.bluetooth.com/specifications/specs/ //! //! # Usage //! //! ```rust,no_run //!# use bluest::Adapter; //!# use futures_lite::StreamExt; //!# #[tokio::main] //!# async fn main() -> Result<(), Box<dyn std::error::Error>> { //!let adapter = Adapter::default().await?; //!adapter.wait_available().await?; //! //!println!("starting scan"); //!let mut scan = adapter.scan(&[]).await?; //!println!("scan started"); //!while let Some(discovered_device) = scan.next().await { //! println!( //! "{}{}: {:?}", //! discovered_device.device.name().as_deref().unwrap_or("(unknown)"), //! discovered_device //! .rssi //! .map(|x| format!(" ({}dBm)", x)) //! .unwrap_or_default(), //! discovered_device.adv_data.services //! ); //!} //!# //!# Ok(()) //!# } //! ``` //! //! # Overview //! //! The primary functions provided by Bluest are: //! //! - Device discovery: //! - [Scanning][Adapter::scan] for devices and receiving advertisements //! - Finding [connected devices][Adapter::connected_devices] //! - [Opening][Adapter::open_device] previously found devices //! - [Connecting][Adapter::connect_device] to discovered devices //! - [Pairing][Device::pair] with devices //! - Accessing remote GATT services: //! - Discovering device [services][Device::discover_services] //! - Discovering service [characteristics][Service::discover_characteristics] //! - Discovering characteristic [descriptors][Characteristic::discover_descriptors] //! - [Read][Characteristic::read], [write][Characteristic::write] (including //! [write without response][Characteristic::write_without_response]), and //! [notify/indicate][Characteristic::notify] operations on remote characteristics //! - [Read][Descriptor::read] and [write][Descriptor::write] operations on characteristic descriptors //! //! # Asynchronous runtimes //! //! On non-linux platforms, Bluest should work with any asynchronous runtime. On linux the underlying `bluer` crate //! requires the Tokio runtime and Bluest makes use of Tokio's `block_in_place` API (which requires Tokio's //! multi-threaded runtime) to make a few methods synchronous. Linux-only asynchronous versions of those methods are //! also provided, which should be preferred in platform-specific code. //! //! # Platform specifics //! //! Because Bluest aims to provide a thin abstraction over the platform-specific APIs, the available APIs represent the //! lowest common denominator of APIs among the supported platforms. For example, CoreBluetooth never exposes the //! Bluetooth address of devices to applications, therefore there is no method on `Device` for retrieving an address or //! even any Bluetooth address struct in the crate. //! //! Most Bluest APIs should behave consistently across all supported platforms. Those APIs with significant differences //! in behavior are summarized in the table below. //! //!| Method | MacOS/iOS | Windows | Linux | //!|----------------------------------------------------------|:---------:|:-------:|:-----:| //!| [`Adapter::connect_device`][Adapter::connect_device] | ✅ | ✨ | ✅ | //!| [`Adapter::disconnect_device`][Adapter::disconnect_device] | ✅ | ✨ | ✅ | //!| [`Device::name`][Device::name] | ✅ | ✅ | ⌛️ | //!| [`Device::is_paired`][Device::is_paired] | ❌ | ✅ | ✅ | //!| [`Device::pair`][Device::pair] | ✨ | ✅ | ✅ | //!| [`Device::pair_with_agent`][Device::pair_with_agent] | ✨ | ✅ | ✅ | //!| [`Device::unpair`][Device::unpair] | ❌ | ✅ | ✅ | //!| [`Device::rssi`][Device::rssi] | ✅ | ❌ | ❌ | //!| [`Service::uuid`][Service::uuid] | ✅ | ✅ | ⌛️ | //!| [`Service::is_primary`][Service::is_primary] | ✅ | ❌ | ✅ | //!| [`Characteristic::uuid`][Characteristic::uuid] | ✅ | ✅ | ⌛️ | //!| [`Characteristic::max_write_len`][Characteristic::max_write_len] | ✅ | ✅ | ⌛️ | //!| [`Descriptor::uuid`][Descriptor::uuid] | ✅ | ✅ | ⌛️ | //! //! ✅ = supported //! ✨ = managed automatically by the OS, this method is a no-op //! ⌛️ = the underlying API is async so this method uses Tokio's `block_in_place` API internally //! ❌ = returns a [`NotSupported`][error::ErrorKind::NotSupported] error //! //! Also, the errors returned by APIs in a given situation may not be consistent from platform to platform. For example, //! Linux's bluez API does not return the underlying Bluetooth protocol error in a useful way, whereas the other //! platforms do. Where it is possible to return a meaningful error, Bluest will attempt to do so. In other cases, //! Bluest may return an error with a [`kind`][Error::kind] of [`Other`][error::ErrorKind::Other] and you would need to //! look at the platform-specific [`source`][std::error::Error::source] of the error for more information. //! //! # Feature flags //! //! The `serde` feature is available to enable serializing/deserializing device //! identifiers. //! //! # Examples //! //! Examples demonstrating basic usage are available in the [examples folder]. //! //! [examples folder]: https://github.com/alexmoon/bluest/tree/master/bluest/examples mod adapter; pub mod btuuid; mod characteristic; mod descriptor; mod device; pub mod error; #[cfg(feature = "l2cap")] mod l2cap_channel; pub mod pairing; mod service; mod util; #[cfg(all(target_os = "android", not(feature = "unstable")))] compile_error!("Android support is unstable and requires the 'unstable' feature to be enabled"); #[cfg(all(windows, feature = "l2cap"))] compile_error!("L2CAP support is not available on Windows"); #[cfg(all(feature = "l2cap", not(feature = "unstable")))] compile_error!("L2CAP support is unstable and requires the 'unstable' feature to be enabled"); #[cfg(target_os = "android")] mod android; #[cfg(target_os = "linux")] mod bluer; #[cfg(any(target_os = "macos", target_os = "ios"))] mod corebluetooth; #[cfg(target_os = "windows")] mod windows; use std::collections::HashMap; #[cfg(target_os = "linux")] pub use ::bluer::Uuid; pub use adapter::{Adapter, AdapterConfig}; pub use btuuid::BluetoothUuidExt; pub use characteristic::Characteristic; pub use descriptor::Descriptor; pub use device::{Device, ServicesChanged}; pub use error::Error; #[cfg(feature = "l2cap")] pub use l2cap_channel::{L2capChannel, L2capChannelReader, L2capChannelWriter}; pub use service::Service; pub use sys::DeviceId; #[cfg(not(target_os = "linux"))] pub use uuid::Uuid; #[cfg(target_os = "android")] use crate::android as sys; #[cfg(target_os = "linux")] use crate::bluer as sys; #[cfg(any(target_os = "macos", target_os = "ios"))] use crate::corebluetooth as sys; #[cfg(target_os = "windows")] use crate::windows as sys; /// Convenience alias for a result with [`Error`] pub type Result<T, E = Error> = core::result::Result<T, E>; /// Events generated by [`Adapter::events`] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum AdapterEvent { /// The adapter has become available (powered on and ready to use) Available, /// The adapter has become unavailable (powered off or otherwise disabled) Unavailable, } /// Events generated by [`Adapter::device_connection_events`] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum ConnectionEvent { /// The device has disconnected from the host system Disconnected, /// The device has connected to the host system Connected, } /// Represents a device discovered during a scan operation #[derive(Debug, Clone, PartialEq, Eq)] pub struct AdvertisingDevice { /// The source of the advertisement pub device: crate::Device, /// The advertisment data pub adv_data: AdvertisementData, /// The signal strength in dBm of the received advertisement packet pub rssi: Option<i16>, } /// Data included in a Bluetooth advertisement or scan reponse. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AdvertisementData { /// The (possibly shortened) local name of the device (CSS §A.1.2) pub local_name: Option<String>, /// Manufacturer specific data (CSS §A.1.4) pub manufacturer_data: Option<ManufacturerData>, /// Advertised GATT service UUIDs (CSS §A.1.1) pub services: Vec<Uuid>, /// Service associated data (CSS §A.1.11) pub service_data: HashMap<Uuid, Vec<u8>>, /// Transmitted power level (CSS §A.1.5) pub tx_power_level: Option<i16>, /// Set to true for connectable advertising packets pub is_connectable: bool, } /// Manufacturer specific data included in Bluetooth advertisements. See the Bluetooth Core Specification Supplement /// §A.1.4 for details. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ManufacturerData { /// Company identifier (defined [here](https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers/)) pub company_id: u16, /// Manufacturer specific data pub data: Vec<u8>, } /// GATT characteristic properties as defined in the Bluetooth Core Specification, Vol 3, Part G, §3.3.1.1. /// Extended properties are also included as defined in §3.3.3.1. #[allow(missing_docs)] #[non_exhaustive] #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct CharacteristicProperties { pub broadcast: bool, pub read: bool, pub write_without_response: bool, pub write: bool, pub notify: bool, pub indicate: bool, pub authenticated_signed_writes: bool, pub extended_properties: bool, pub reliable_write: bool, pub writable_auxiliaries: bool, } impl CharacteristicProperties { /// Raw transmutation from [`u32`]. /// /// Extended properties are in the upper bits. pub fn from_bits(bits: u32) -> Self { CharacteristicProperties { broadcast: (bits & (1 << 0)) != 0, read: (bits & (1 << 1)) != 0, write_without_response: (bits & (1 << 2)) != 0, write: (bits & (1 << 3)) != 0, notify: (bits & (1 << 4)) != 0, indicate: (bits & (1 << 5)) != 0, authenticated_signed_writes: (bits & (1 << 6)) != 0, extended_properties: (bits & (1 << 7)) != 0, reliable_write: (bits & (1 << 8)) != 0, writable_auxiliaries: (bits & (1 << 9)) != 0, } } /// Raw transmutation to [`u32`]. /// /// Extended properties are in the upper bits. pub fn to_bits(self) -> u32 { u32::from(self.broadcast) | (u32::from(self.read) << 1) | (u32::from(self.write_without_response) << 2) | (u32::from(self.write) << 3) | (u32::from(self.notify) << 4) | (u32::from(self.indicate) << 5) | (u32::from(self.authenticated_signed_writes) << 6) | (u32::from(self.extended_properties) << 7) | (u32::from(self.reliable_write) << 8) | (u32::from(self.writable_auxiliaries) << 9) } }
rust
Apache-2.0
37e353d778b43d4892d2b7315cb5fba6cd5cb969
2026-01-04T20:23:19.181316Z
false
alexmoon/bluest
https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/device.rs
src/device.rs
#![allow(clippy::let_unit_value)] use futures_core::Stream; use futures_lite::StreamExt; use crate::error::ErrorKind; #[cfg(feature = "l2cap")] use crate::l2cap_channel::L2capChannel; use crate::pairing::PairingAgent; use crate::{sys, DeviceId, Error, Result, Service, Uuid}; /// A Bluetooth LE device #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Device(pub(crate) sys::device::DeviceImpl); impl std::fmt::Display for Device { #[inline] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.0, f) } } impl Device { /// This device's unique identifier #[inline] pub fn id(&self) -> DeviceId { self.0.id() } /// The local name for this device, if available /// /// This can either be a name advertised or read from the device, or a name assigned to the device by the OS. /// /// # Panics /// /// On Linux, this method will panic if there is a current Tokio runtime and it is single-threaded or if there is /// no current Tokio runtime and creating one fails. #[inline] pub fn name(&self) -> Result<String> { self.0.name() } /// The local name for this device, if available /// /// This can either be a name advertised or read from the device, or a name assigned to the device by the OS. #[inline] pub async fn name_async(&self) -> Result<String> { self.0.name_async().await } /// The connection status for this device #[inline] pub async fn is_connected(&self) -> bool { self.0.is_connected().await } /// The pairing status for this device #[inline] pub async fn is_paired(&self) -> Result<bool> { self.0.is_paired().await } /// Attempt to pair this device using the system default pairing UI /// /// # Platform specific /// /// ## MacOS/iOS /// /// Device pairing is performed automatically by the OS when a characteristic requiring security is accessed. This /// method is a no-op. /// /// ## Windows /// /// This will fail unless it is called from a UWP application. #[inline] pub async fn pair(&self) -> Result<()> { self.0.pair().await } /// Attempt to pair this device using the system default pairing UI /// /// # Platform specific /// /// On MacOS/iOS, device pairing is performed automatically by the OS when a characteristic requiring security is /// accessed. This method is a no-op. #[inline] pub async fn pair_with_agent<T: PairingAgent + 'static>(&self, agent: &T) -> Result<()> { self.0.pair_with_agent(agent).await } /// Disconnect and unpair this device from the system /// /// # Platform specific /// /// Not supported on MacOS/iOS. #[inline] pub async fn unpair(&self) -> Result<()> { self.0.unpair().await } /// Discover the primary services of this device. #[inline] pub async fn discover_services(&self) -> Result<Vec<Service>> { self.0.discover_services().await } /// Discover the primary service(s) of this device with the given [`Uuid`]. #[inline] pub async fn discover_services_with_uuid(&self, uuid: Uuid) -> Result<Vec<Service>> { self.0.discover_services_with_uuid(uuid).await } /// Get previously discovered services. /// /// If no services have been discovered yet, this method will perform service discovery. #[inline] pub async fn services(&self) -> Result<Vec<Service>> { self.0.services().await } /// Asynchronously blocks until a GATT services changed packet is received /// /// # Platform specific /// /// See [`Device::service_changed_indications`]. pub async fn services_changed(&self) -> Result<()> { self.service_changed_indications() .await? .next() .await .ok_or(Error::from(ErrorKind::AdapterUnavailable)) .map(|x| x.map(|_| ()))? } /// Monitors the device for service changed indications. /// /// # Platform specific /// /// On Windows an event is generated whenever the `services` value is updated. In addition to actual service change /// indications this occurs when, for example, `discover_services` is called or when an unpaired device disconnects. #[inline] pub async fn service_changed_indications( &self, ) -> Result<impl Stream<Item = Result<ServicesChanged>> + Send + Unpin + '_> { self.0.service_changed_indications().await } /// Get the current signal strength from the device in dBm. /// /// # Platform specific /// /// Returns [`NotSupported`][crate::error::ErrorKind::NotSupported] on Windows and Linux. #[inline] pub async fn rssi(&self) -> Result<i16> { self.0.rssi().await } /// Open an L2CAP connection-oriented channel (CoC) to this device. /// /// # Platform specific /// /// Returns [`NotSupported`][crate::error::ErrorKind::NotSupported] on iOS/MacOS and Linux. /// The `l2cap` feature is not available on Windows. #[inline] #[cfg(feature = "l2cap")] pub async fn open_l2cap_channel(&self, psm: u16, secure: bool) -> Result<L2capChannel> { let channel = self.0.open_l2cap_channel(psm, secure).await?; Ok(L2capChannel(channel)) } } /// A services changed notification #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct ServicesChanged(pub(crate) sys::device::ServicesChangedImpl); impl ServicesChanged { /// Check if `service` was invalidated by this service changed indication. /// /// # Platform specific /// /// Windows does not indicate which services were affected by a services changed event, so this method will /// pessimistically return true for all services. pub fn was_invalidated(&self, service: &Service) -> bool { self.0.was_invalidated(service) } }
rust
Apache-2.0
37e353d778b43d4892d2b7315cb5fba6cd5cb969
2026-01-04T20:23:19.181316Z
false
alexmoon/bluest
https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/bluer.rs
src/bluer.rs
pub mod adapter; pub mod characteristic; pub mod descriptor; pub mod device; pub mod l2cap_channel; pub mod service; mod error; /// A platform-specific device identifier. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct DeviceId(bluer::Address); impl std::fmt::Display for DeviceId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.0, f) } }
rust
Apache-2.0
37e353d778b43d4892d2b7315cb5fba6cd5cb969
2026-01-04T20:23:19.181316Z
false
alexmoon/bluest
https://github.com/alexmoon/bluest/blob/37e353d778b43d4892d2b7315cb5fba6cd5cb969/src/characteristic.rs
src/characteristic.rs
use futures_core::Stream; use crate::{sys, CharacteristicProperties, Descriptor, Result, Uuid}; /// A Bluetooth GATT characteristic #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Characteristic(pub(crate) sys::characteristic::CharacteristicImpl); impl Characteristic { /// The [`Uuid`] identifying the type of this GATT characteristic /// /// # Panics /// /// On Linux, this method will panic if there is a current Tokio runtime and it is single-threaded, if there is no /// current Tokio runtime and creating one fails, or if the underlying [`Characteristic::uuid_async()`] method /// fails. #[inline] pub fn uuid(&self) -> Uuid { self.0.uuid() } /// The [`Uuid`] identifying the type of this GATT characteristic #[inline] pub async fn uuid_async(&self) -> Result<Uuid> { self.0.uuid_async().await } /// The properties of this this GATT characteristic. /// /// Characteristic properties indicate which operations (e.g. read, write, notify, etc) may be performed on this /// characteristic. #[inline] pub async fn properties(&self) -> Result<CharacteristicProperties> { self.0.properties().await } /// The cached value of this characteristic /// /// If the value has not yet been read, this method may either return an error or perform a read of the value. #[inline] pub async fn value(&self) -> Result<Vec<u8>> { self.0.value().await } /// Read the value of this characteristic from the device #[inline] pub async fn read(&self) -> Result<Vec<u8>> { self.0.read().await } /// Write the value of this descriptor on the device to `value` and request the device return a response indicating /// a successful write. #[inline] pub async fn write(&self, value: &[u8]) -> Result<()> { self.0.write(value).await } /// Write the value of this descriptor on the device to `value` without requesting a response. #[inline] pub async fn write_without_response(&self, value: &[u8]) -> Result<()> { self.0.write_without_response(value).await } /// Get the maximum amount of data that can be written in a single packet for this characteristic. #[inline] pub fn max_write_len(&self) -> Result<usize> { self.0.max_write_len() } /// Get the maximum amount of data that can be written in a single packet for this characteristic. #[inline] pub async fn max_write_len_async(&self) -> Result<usize> { self.0.max_write_len_async().await } /// Enables notification of value changes for this GATT characteristic. /// /// Returns a stream of values for the characteristic sent from the device. #[inline] pub async fn notify(&self) -> Result<impl Stream<Item = Result<Vec<u8>>> + Send + Unpin + '_> { self.0.notify().await } /// Is the device currently sending notifications for this characteristic? #[inline] pub async fn is_notifying(&self) -> Result<bool> { self.0.is_notifying().await } /// Discover the descriptors associated with this characteristic. #[inline] pub async fn discover_descriptors(&self) -> Result<Vec<Descriptor>> { self.0.discover_descriptors().await } /// Get previously discovered descriptors. /// /// If no descriptors have been discovered yet, this method will perform descriptor discovery. #[inline] pub async fn descriptors(&self) -> Result<Vec<Descriptor>> { self.0.descriptors().await } }
rust
Apache-2.0
37e353d778b43d4892d2b7315cb5fba6cd5cb969
2026-01-04T20:23:19.181316Z
false