Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to save and load processors #18

Merged
merged 5 commits into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,26 @@ readme = "README.md"

[features]
progress_bar = ["dep:indicatif"]
quicklog = ["dep:thiserror"]
quicklog = []

[dependencies]
serde_json = "1.0.115"
serde_json = "1.0.132"
hex = "0.4.3"
npyz = "0.7.4"
ndarray = "0.15.6"
npyz = "0.8.3"
ndarray = { version = "0.16.1", features = ["serde"] }
rayon = "1.10.0"
indicatif = { version = "0.17.8", optional = true }
ndarray-npy ="0.8.1"
itertools = "0.12.1"
thiserror = { version = "1.0.58", optional = true }
ndarray-npy ="0.9.1"
itertools = "0.13.0"
thiserror = { version = "1.0.58" }
dtw = { git = "https://github.com/Ledger-Donjon/dtw.git", rev = "0f8d7ec3bbdf2ca4ec8ea35feddb8d1db73e7d54" }
num-traits = "0.2.19"
serde = { version = "1.0.214", features = ["derive"] }

[dev-dependencies]
criterion = "0.5.1"
ndarray-rand = "0.14.0"
anyhow = "1.0.81"
ndarray-rand = "0.15.0"
anyhow = "1.0.92"
muscat = { path = ".", features = ["progress_bar"] }

[[example]]
Expand Down
22 changes: 13 additions & 9 deletions benches/cpa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,42 @@ use ndarray_rand::rand_distr::Uniform;
use ndarray_rand::RandomExt;
use std::iter::zip;

pub fn leakage_model(value: usize, guess: usize) -> usize {
hw(sbox((value ^ guess) as u8) as usize)
pub fn leakage_model(plaintext: usize, guess: usize) -> usize {
hw(sbox((plaintext ^ guess) as u8) as usize)
}

fn cpa_sequential(traces: &Array2<f64>, plaintexts: &Array2<u8>) -> Cpa {
let mut cpa = CpaProcessor::new(traces.shape()[1], 256, 0, leakage_model);
let mut cpa = CpaProcessor::new(traces.shape()[1], 256, 0);

for i in 0..traces.shape()[0] {
cpa.update(
traces.row(i).map(|&x| x as usize).view(),
plaintexts.row(i).map(|&y| y as usize).view(),
leakage_model,
);
}

cpa.finalize()
cpa.finalize(leakage_model)
}

pub fn leakage_model_normal(value: ArrayView1<usize>, guess: usize) -> usize {
hw(sbox((value[1] ^ guess) as u8) as usize)
pub fn leakage_model_normal(plaintext: ArrayView1<usize>, guess: usize) -> usize {
hw(sbox((plaintext[1] ^ guess) as u8) as usize)
}

fn cpa_normal_sequential(traces: &Array2<f64>, plaintexts: &Array2<u8>) -> Cpa {
let batch_size = 500;

let mut cpa =
cpa_normal::CpaProcessor::new(traces.shape()[1], batch_size, 256, leakage_model_normal);
let mut cpa = cpa_normal::CpaProcessor::new(traces.shape()[1], batch_size, 256);

for (trace_batch, plaintext_batch) in zip(
traces.axis_chunks_iter(Axis(0), batch_size),
plaintexts.axis_chunks_iter(Axis(0), batch_size),
) {
cpa.update(trace_batch.map(|&x| x as f32).view(), plaintext_batch);
cpa.update(
trace_batch.map(|&x| x as f32).view(),
plaintext_batch,
leakage_model_normal,
);
}

cpa.finalize()
Expand Down
4 changes: 2 additions & 2 deletions benches/dpa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ fn selection_function(metadata: ArrayView1<u8>, guess: usize) -> bool {
}

fn dpa_sequential(traces: &Array2<f32>, plaintexts: &Array2<u8>) -> Dpa {
let mut dpa = DpaProcessor::new(traces.shape()[1], 256, selection_function);
let mut dpa = DpaProcessor::new(traces.shape()[1], 256);

for i in 0..traces.shape()[0] {
dpa.update(traces.row(i), plaintexts.row(i));
dpa.update(traces.row(i), plaintexts.row(i), selection_function);
}

dpa.finalize()
Expand Down
13 changes: 5 additions & 8 deletions examples/cpa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,20 +35,17 @@ fn cpa() -> Result<()> {
.progress_with(progress_bar(len_traces))
.par_bridge()
.map(|row_number| {
let mut cpa = CpaProcessor::new(size, batch, guess_range, leakage_model);
let mut cpa = CpaProcessor::new(size, batch, guess_range);
let range_rows = row_number..row_number + batch;
let range_samples = start_sample..end_sample;
let sample_traces = traces
.slice(s![range_rows.clone(), range_samples])
.map(|l| *l as f32);
let sample_metadata = plaintext.slice(s![range_rows, ..]).map(|p| *p as usize);
cpa.update(sample_traces.view(), sample_metadata.view());
cpa.update(sample_traces.view(), sample_metadata.view(), leakage_model);
cpa
})
.reduce(
|| CpaProcessor::new(size, batch, guess_range, leakage_model),
|x, y| x + y,
);
.reduce(|| CpaProcessor::new(size, batch, guess_range), |x, y| x + y);

let cpa = cpa_parallel.finalize();
println!("Guessed key = {}", cpa.best_guess());
Expand All @@ -69,7 +66,7 @@ fn success() -> Result<()> {
let nfiles = 13; // Number of files in the directory. TBD: Automating this value
let rank_traces = 1000;

let mut cpa = CpaProcessor::new(size, batch, guess_range, leakage_model);
let mut cpa = CpaProcessor::new(size, batch, guess_range);

let mut rank = Array1::zeros(guess_range);
let mut processed_traces = 0;
Expand All @@ -87,7 +84,7 @@ fn success() -> Result<()> {
.map(|l| *l as f32);
let sample_metadata = plaintext.slice(s![range_rows, range_metadata]);

cpa.update(sample_traces.view(), sample_metadata);
cpa.update(sample_traces.view(), sample_metadata, leakage_model);
processed_traces += sample_traces.len();
if processed_traces % rank_traces == 0 {
// rank can be saved to get its evolution
Expand Down
7 changes: 4 additions & 3 deletions examples/cpa_partioned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,22 @@ fn cpa() -> Result<()> {
})
.par_bridge()
.map(|batch| {
let mut c = CpaProcessor::new(size, guess_range, target_byte, leakage_model);
let mut c = CpaProcessor::new(size, guess_range, target_byte);
for i in 0..batch.0.shape()[0] {
c.update(
batch.0.row(i).map(|x| *x as usize).view(),
batch.1.row(i).map(|y| *y as usize).view(),
leakage_model,
);
}
c
})
.reduce(
|| CpaProcessor::new(size, guess_range, target_byte, leakage_model),
|| CpaProcessor::new(size, guess_range, target_byte),
|a, b| a + b,
);

let cpa_result = cpa.finalize();
let cpa_result = cpa.finalize(leakage_model);
println!("Guessed key = {}", cpa_result.best_guess());

// save corr key curves in npy
Expand Down
21 changes: 11 additions & 10 deletions examples/dpa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,18 @@ fn dpa() -> Result<()> {
let traces = read_array2_from_npy_file::<FormatTraces>(&dir_l)?;
let plaintext = read_array2_from_npy_file::<FormatMetadata>(&dir_p)?;
let len_traces = 20000; //traces.shape()[0];
let mut dpa_proc = DpaProcessor::new(size, guess_range, selection_function);
let mut dpa_proc = DpaProcessor::new(size, guess_range);
for i in (0..len_traces).progress() {
let tmp_trace = traces
.row(i)
.slice(s![start_sample..end_sample])
.mapv(|t| t as f32);
let tmp_metadata = plaintext.row(i);
dpa_proc.update(tmp_trace.view(), tmp_metadata.to_owned());
dpa_proc.update(
tmp_trace.view(),
tmp_metadata.to_owned(),
selection_function,
);
}
let dpa = dpa_proc.finalize();
println!("Guessed key = {:02x}", dpa.best_guess());
Expand All @@ -53,7 +57,7 @@ fn dpa_success() -> Result<()> {
let traces = read_array2_from_npy_file::<FormatTraces>(&dir_l)?;
let plaintext = read_array2_from_npy_file::<FormatMetadata>(&dir_p)?;
let len_traces = traces.shape()[0];
let mut dpa_proc = DpaProcessor::new(size, guess_range, selection_function);
let mut dpa_proc = DpaProcessor::new(size, guess_range);
let rank_traces: usize = 100;

let mut rank = Array1::zeros(guess_range);
Expand All @@ -63,7 +67,7 @@ fn dpa_success() -> Result<()> {
.slice(s![start_sample..end_sample])
.mapv(|t| t as f32);
let tmp_metadata = plaintext.row(i).to_owned();
dpa_proc.update(tmp_trace.view(), tmp_metadata);
dpa_proc.update(tmp_trace.view(), tmp_metadata, selection_function);

if i % rank_traces == 0 {
// rank can be saved to get its evolution
Expand Down Expand Up @@ -102,18 +106,15 @@ fn dpa_parallel() -> Result<()> {
.slice(s![range_rows..range_rows + batch, ..])
.to_owned();

let mut dpa_inner = DpaProcessor::new(size, guess_range, selection_function);
let mut dpa_inner = DpaProcessor::new(size, guess_range);
for i in 0..batch {
let trace = tmp_traces.row(i);
let metadata = tmp_metadata.row(i).to_owned();
dpa_inner.update(trace, metadata);
dpa_inner.update(trace, metadata, selection_function);
}
dpa_inner
})
.reduce(
|| DpaProcessor::new(size, guess_range, selection_function),
|x, y| x + y,
)
.reduce(|| DpaProcessor::new(size, guess_range), |x, y| x + y)
.finalize();

println!("{:2x}", dpa.best_guess());
Expand Down
9 changes: 5 additions & 4 deletions examples/rank.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ fn rank() -> Result<()> {
let folder = String::from("../../data");
let nfiles = 5;
let batch_size = 3000;
let mut rank = CpaProcessor::new(size, guess_range, target_byte, leakage_model);
let mut rank = CpaProcessor::new(size, guess_range, target_byte);
for file in (0..nfiles).progress_with(progress_bar(nfiles)) {
let dir_l = format!("{folder}/l{file}.npy");
let dir_p = format!("{folder}/p{file}.npy");
Expand All @@ -37,24 +37,25 @@ fn rank() -> Result<()> {
let x = (0..batch_size)
.par_bridge()
.fold(
|| CpaProcessor::new(size, guess_range, target_byte, leakage_model),
|| CpaProcessor::new(size, guess_range, target_byte),
|mut r, n| {
r.update(
l_sample.row(n).map(|l| *l as usize).view(),
p_sample.row(n).map(|p| *p as usize).view(),
leakage_model,
);
r
},
)
.reduce(
|| CpaProcessor::new(size, guess_range, target_byte, leakage_model),
|| CpaProcessor::new(size, guess_range, target_byte),
|lhs, rhs| lhs + rhs,
);
rank = rank + x;
}
}

let rank = rank.finalize();
let rank = rank.finalize(leakage_model);

// save rank key curves in npy
save_array("../results/rank.npy", &rank.rank().map(|&x| x as u64))?;
Expand Down
Loading
Loading