#![no_std]
#![no_main]
use esp32c3_hal::{
clock::ClockControl,
hmac::{Hmac, HmacPurpose, KeyId},
peripherals::Peripherals,
prelude::*,
systimer::SystemTimer,
Rng,
};
use esp_backtrace as _;
use esp_println::println;
use hmac::{Hmac as HmacSw, Mac};
use nb::block;
use sha2::Sha256;
type HmacSha256 = HmacSw<Sha256>;
#[entry]
fn main() -> ! {
let peripherals = Peripherals::take();
let system = peripherals.SYSTEM.split();
let _clocks = ClockControl::boot_defaults(system.clock_control).freeze();
let mut rng = Rng::new(peripherals.RNG);
let key = [0_u8; 32].as_ref();
let mut hw_hmac = Hmac::new(peripherals.HMAC);
let mut src = [0_u8; 1024];
rng.read(src.as_mut_slice()).unwrap();
let mut output = [0u8; 32];
println!("Beginning stress tests...");
println!("Testing length from 0 to {:?} bytes for HMAC...", src.len());
for i in 0..src.len() + 1 {
let (nsrc, _) = src.split_at(i);
let mut remaining = nsrc;
hw_hmac.init();
block!(hw_hmac.configure(HmacPurpose::ToUser, KeyId::Key0)).expect("Key purpose mismatch");
let pre_hw_hmac = SystemTimer::now();
while remaining.len() > 0 {
remaining = block!(hw_hmac.update(remaining)).unwrap();
}
block!(hw_hmac.finalize(output.as_mut_slice())).unwrap();
let post_hw_hmac = SystemTimer::now();
let hw_time = post_hw_hmac - pre_hw_hmac;
let mut sw_hmac = HmacSha256::new_from_slice(key).expect("HMAC can take key of any size");
let pre_sw_hash = SystemTimer::now();
sw_hmac.update(nsrc);
let soft_result = sw_hmac.finalize().into_bytes();
let post_sw_hash = SystemTimer::now();
let soft_time = post_sw_hash - pre_sw_hash;
for (a, b) in output.iter().zip(soft_result) {
assert_eq!(*a, b);
}
println!("Testing for length: {:>4} | HW: {:>6} cycles, SW: {:>7} cycles (HW HMAC is {:>2}x faster)", i, hw_time, soft_time, soft_time / hw_time);
}
println!("Finished stress tests!");
loop {}
}