more performance improvements

This commit is contained in:
hal8174 2025-07-05 22:16:45 +02:00
parent 422e3018e2
commit fbd946c7ec
Signed by: hal8174
SSH key fingerprint: SHA256:JwuqS+eVfISfKr+DkDQ6NWAbGd1jFAHkPpCM1yCnlTs

View file

@ -7,7 +7,7 @@ use std::{
use aes::{
Aes128,
cipher::{BlockEncrypt, KeyInit, generic_array::GenericArray},
cipher::{self, BlockEncrypt, KeyInit, generic_array::GenericArray},
};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
@ -78,30 +78,27 @@ fn read_msgs(path: impl AsRef<Path>) -> Vec<[u8; 16]> {
const TRACES: usize = 87;
fn read_traces(path: impl AsRef<Path>) -> Vec<[u8; TRACES]> {
fn read_traces(path: impl AsRef<Path>, capacity: usize) -> Vec<Vec<u8>> {
let file = std::fs::File::open(path).unwrap();
let bufreader = std::io::BufReader::new(file);
bufreader
.lines()
.map(|l| {
let mut r: Vec<Vec<u8>> = (0..TRACES).map(|_| vec![0; capacity]).collect();
for (i, l) in bufreader.lines().enumerate() {
let l = l.unwrap();
let mut trace = [0; TRACES];
for (i, t) in l
for (j, t) in l
.trim()
.split(',')
.map(|t| t.parse::<u8>().unwrap())
.enumerate()
{
trace[i] = t;
r[j][i] = t;
}
}
trace
})
.collect()
r
}
fn correlation(
@ -109,7 +106,7 @@ fn correlation(
key_hypothesis: usize,
trace_index: usize,
cyphtertext: &[Vec<[u8; 16]>],
traces: &[[u8; TRACES]],
traces: &[Vec<u8>],
) -> f64 {
let mut x = 0i64;
let mut y = 0i64;
@ -117,9 +114,9 @@ fn correlation(
let mut xsqr = 0i64;
let mut ysqr = 0i64;
for i in 0..traces.len() {
for i in 0..traces[0].len() {
let xi = (cyphtertext[key_hypothesis][i][bit / 8] & (1 << (bit % 8))) as i64;
let yi = traces[i][trace_index] as i64;
let yi = traces[trace_index][i] as i64;
x += xi;
y += yi;
@ -128,7 +125,7 @@ fn correlation(
ysqr += yi * yi;
}
let n = traces.len() as i64;
let n = traces[0].len() as i64;
let num = (n * xy - x * y) as f64;
let denom = f64::sqrt((n * xsqr - x * x) as f64) * f64::sqrt((n * ysqr - y * y) as f64);
@ -145,7 +142,10 @@ fn main() {
println!("calculate models: {:?}", start.elapsed());
let start = std::time::Instant::now();
let traces = read_traces("./alan/Task-3-example_traces/test_traces.csv");
let traces = read_traces(
"./alan/Task-3-example_traces/test_traces.csv",
cyphertext.len(),
);
println!("read traces: {:?}", start.elapsed());
let start = std::time::Instant::now();
@ -153,7 +153,7 @@ fn main() {
let (max_index, max) = (0..256)
.into_par_iter()
.map(|key_hypothesis| {
let m = (0..traces[0].len())
let m = (0..TRACES)
.map(|trace_index| {
correlation(bit, key_hypothesis, trace_index, &models, &traces).abs()
})