Skip to content

Commit 8f573ec

Browse files
authored
Merge pull request #10 from parv68/SIEM
cargo fmt all example files to satisfy CI fmt check
2 parents 22c29d4 + 673da17 commit 8f573ec

22 files changed

Lines changed: 439 additions & 134 deletions

examples/01_simple_detect.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,16 @@ fn main() {
99
println!("Input: {:?}", input);
1010

1111
if let Some(hash) = cryptotrace::core::hashing::detect_hash(input) {
12-
println!(" Hash: {} (confidence {:.2})", hash.algorithm, hash.confidence);
12+
println!(
13+
" Hash: {} (confidence {:.2})",
14+
hash.algorithm, hash.confidence
15+
);
1316
}
1417
if let Some(enc) = cryptotrace::core::encoding::detect_encoding(input) {
15-
println!(" Encoding: {} (confidence {:.2})", enc.encoding_type, enc.confidence);
18+
println!(
19+
" Encoding: {} (confidence {:.2})",
20+
enc.encoding_type, enc.confidence
21+
);
1622
}
1723

1824
let (entropy, _freq) = cryptotrace::core::entropy::shannon_entropy(input.as_bytes());

examples/02_scan_file.rs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,22 @@ use std::fs;
33

44
fn main() {
55
let args: Vec<String> = env::args().collect();
6-
let path = if args.len() > 1 { &args[1] } else { "Cargo.toml" };
6+
let path = if args.len() > 1 {
7+
&args[1]
8+
} else {
9+
"Cargo.toml"
10+
};
711

812
let data = fs::read(path).expect("Failed to read file");
913

10-
match cryptotrace::analyzers::file::analyze_bytes(&data, cryptotrace::types::SourceType::Binary) {
14+
match cryptotrace::analyzers::file::analyze_bytes(&data, cryptotrace::types::SourceType::Binary)
15+
{
1116
Ok(result) => {
1217
println!("File: {}", path);
13-
println!("Algorithm: {}", result.algorithm.unwrap_or_else(|| "<none>".into()));
18+
println!(
19+
"Algorithm: {}",
20+
result.algorithm.unwrap_or_else(|| "<none>".into())
21+
);
1422
println!("Encoding: {}", result.detected_type);
1523
let (entropy, _) = cryptotrace::core::entropy::shannon_entropy(&data);
1624
println!("Entropy: {:.2}", entropy);

examples/03_batch_folder.rs

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,16 @@ use std::fs;
44
fn main() {
55
let args: Vec<String> = env::args().collect();
66
let dir = if args.len() > 1 { &args[1] } else { "." };
7-
let max_size: u64 = std::env::var("MAX_FILE_SIZE").ok().and_then(|s| s.parse().ok()).unwrap_or(10_485_760);
7+
let max_size: u64 = std::env::var("MAX_FILE_SIZE")
8+
.ok()
9+
.and_then(|s| s.parse().ok())
10+
.unwrap_or(10_485_760);
811

912
for entry in fs::read_dir(dir).unwrap().flatten() {
1013
let path = entry.path();
11-
if !path.is_file() { continue; }
14+
if !path.is_file() {
15+
continue;
16+
}
1217

1318
let _meta = match fs::metadata(&path) {
1419
Ok(m) if m.len() <= max_size => m,
@@ -20,12 +25,21 @@ fn main() {
2025
Err(_) => continue,
2126
};
2227

23-
match cryptotrace::analyzers::file::analyze_bytes(&data, cryptotrace::types::SourceType::Binary) {
28+
match cryptotrace::analyzers::file::analyze_bytes(
29+
&data,
30+
cryptotrace::types::SourceType::Binary,
31+
) {
2432
Ok(result) => {
2533
let algo = result.algorithm.unwrap_or_else(|| "-".into());
2634
let (entropy, _) = cryptotrace::core::entropy::shannon_entropy(&data);
27-
println!("{}\t{}\t{}\t{:.2}\t{:.2}",
28-
path.display(), algo, result.detected_type, entropy, result.confidence);
35+
println!(
36+
"{}\t{}\t{}\t{:.2}\t{:.2}",
37+
path.display(),
38+
algo,
39+
result.detected_type,
40+
entropy,
41+
result.confidence
42+
);
2943
}
3044
Err(e) => eprintln!("Error scanning {}: {}", path.display(), e),
3145
}

examples/04_compare_inputs.rs

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,37 @@ fn main() {
66

77
// Method 1: Raw bytes
88
println!("=== Raw bytes ===");
9-
let r1 = cryptotrace::analyzers::file::analyze_bytes(test_data, cryptotrace::types::SourceType::Binary).unwrap();
10-
println!(" algo={:?} type={} ent={:.2} conf={:.2}", r1.algorithm, r1.detected_type, r1.entropy, r1.confidence);
9+
let r1 = cryptotrace::analyzers::file::analyze_bytes(
10+
test_data,
11+
cryptotrace::types::SourceType::Binary,
12+
)
13+
.unwrap();
14+
println!(
15+
" algo={:?} type={} ent={:.2} conf={:.2}",
16+
r1.algorithm, r1.detected_type, r1.entropy, r1.confidence
17+
);
1118

1219
// Method 2: File
1320
println!("=== From file ===");
1421
let r2 = cryptotrace::analyzers::file::analyze_file(Path::new("Cargo.toml")).unwrap();
15-
println!(" algo={:?} type={} ent={:.2} conf={:.2}", r2.algorithm, r2.detected_type, r2.entropy, r2.confidence);
22+
println!(
23+
" algo={:?} type={} ent={:.2} conf={:.2}",
24+
r2.algorithm, r2.detected_type, r2.entropy, r2.confidence
25+
);
1626

1727
// Method 3: Stdin (if piped)
1828
println!("=== Stdin (pipe data or skip) ===");
1929
let mut buf = Vec::new();
2030
if std::io::stdin().read_to_end(&mut buf).is_ok() && !buf.is_empty() {
21-
let r3 = cryptotrace::analyzers::file::analyze_bytes(&buf, cryptotrace::types::SourceType::Binary).unwrap();
22-
println!(" algo={:?} type={} ent={:.2} conf={:.2}", r3.algorithm, r3.detected_type, r3.entropy, r3.confidence);
31+
let r3 = cryptotrace::analyzers::file::analyze_bytes(
32+
&buf,
33+
cryptotrace::types::SourceType::Binary,
34+
)
35+
.unwrap();
36+
println!(
37+
" algo={:?} type={} ent={:.2} conf={:.2}",
38+
r3.algorithm, r3.detected_type, r3.entropy, r3.confidence
39+
);
2340
} else {
2441
println!(" (no stdin data)");
2542
}

examples/05_csv_export.rs

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,29 @@ fn main() {
77
let out = args.get(2).map(|s| s.as_str()).unwrap_or("scan_report.csv");
88

99
let mut wtr = csv::Writer::from_path(out).expect("Failed to create CSV");
10-
wtr.write_record(["path", "algorithm", "detected_type", "entropy", "confidence", "risk_level"])
11-
.unwrap();
10+
wtr.write_record([
11+
"path",
12+
"algorithm",
13+
"detected_type",
14+
"entropy",
15+
"confidence",
16+
"risk_level",
17+
])
18+
.unwrap();
1219

1320
for entry in fs::read_dir(dir).unwrap().flatten() {
1421
let path = entry.path();
15-
if !path.is_file() { continue; }
22+
if !path.is_file() {
23+
continue;
24+
}
1625
let data = match fs::read(&path) {
1726
Ok(d) if d.len() <= 10_485_760 => d,
1827
_ => continue,
1928
};
20-
if let Ok(r) = cryptotrace::analyzers::file::analyze_bytes(&data, cryptotrace::types::SourceType::Binary) {
29+
if let Ok(r) = cryptotrace::analyzers::file::analyze_bytes(
30+
&data,
31+
cryptotrace::types::SourceType::Binary,
32+
) {
2133
let (entropy, _) = cryptotrace::core::entropy::shannon_entropy(&data);
2234
wtr.write_record([
2335
path.to_string_lossy().as_ref(),
@@ -26,7 +38,8 @@ fn main() {
2638
&format!("{:.4}", entropy),
2739
&format!("{:.4}", r.confidence),
2840
&format!("{:?}", r.risk_level),
29-
]).ok();
41+
])
42+
.ok();
3043
}
3144
}
3245
wtr.flush().ok();

examples/06_recursive_decode.rs

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,46 +6,63 @@ fn main() {
66
// Gzip then base64 encode
77
let mut compressed = Vec::new();
88
{
9-
let mut encoder = flate2::write::GzEncoder::new(&mut compressed, flate2::Compression::default());
9+
let mut encoder =
10+
flate2::write::GzEncoder::new(&mut compressed, flate2::Compression::default());
1011
encoder.write_all(plaintext).unwrap();
1112
encoder.finish().unwrap();
1213
}
1314

1415
use base64::Engine;
1516
let b64_payload = base64::engine::general_purpose::STANDARD.encode(&compressed);
1617

17-
println!("Encoded payload (first 80 chars): {:?}", &b64_payload[..80.min(b64_payload.len())]);
18+
println!(
19+
"Encoded payload (first 80 chars): {:?}",
20+
&b64_payload[..80.min(b64_payload.len())]
21+
);
1822

1923
// Decode layer by layer
2024
let mut current = b64_payload.as_bytes().to_vec();
2125
for layer in 1..=5 {
2226
let s = String::from_utf8_lossy(&current);
2327

2428
if let Some(enc) = cryptotrace::core::encoding::detect_encoding(&s) {
25-
println!("Layer {}: detected encoding = {} (conf={:.2})", layer, enc.encoding_type, enc.confidence);
29+
println!(
30+
"Layer {}: detected encoding = {} (conf={:.2})",
31+
layer, enc.encoding_type, enc.confidence
32+
);
2633

2734
match enc.encoding_type.as_str() {
2835
"Base64" => {
29-
if let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(s.trim()) {
36+
if let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(s.trim())
37+
{
3038
current = decoded;
3139
continue;
3240
}
3341
}
34-
_ => { break; }
42+
_ => {
43+
break;
44+
}
3545
}
3646
}
3747

3848
if cryptotrace::core::compression::detect_compression(&current).is_some() {
3949
let mut decompressed = Vec::new();
4050
let mut d = flate2::read::GzDecoder::new(std::io::Cursor::new(&current));
4151
if d.read_to_end(&mut decompressed).is_ok() && !decompressed.is_empty() {
42-
println!("Layer {}: gzip decompressed ({} bytes)", layer, decompressed.len());
52+
println!(
53+
"Layer {}: gzip decompressed ({} bytes)",
54+
layer,
55+
decompressed.len()
56+
);
4357
current = decompressed;
4458
continue;
4559
}
4660
}
4761
break;
4862
}
4963

50-
println!("Final decoded text: {:?}", String::from_utf8_lossy(&current));
64+
println!(
65+
"Final decoded text: {:?}",
66+
String::from_utf8_lossy(&current)
67+
);
5168
}

examples/07_sandbox_crash_test.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,19 @@ fn main() {
1919
}
2020
}
2121
Err(e) => {
22-
println!("Sandbox worker failed (expected if no worker binary): {}", e);
22+
println!(
23+
"Sandbox worker failed (expected if no worker binary): {}",
24+
e
25+
);
2326
println!("Falling back to in-process analysis...");
24-
match cryptotrace::analyzers::file::analyze_bytes(test_data, cryptotrace::types::SourceType::Binary) {
25-
Ok(r) => println!("In-process result: algo={:?} ent={}", r.algorithm, r.entropy),
27+
match cryptotrace::analyzers::file::analyze_bytes(
28+
test_data,
29+
cryptotrace::types::SourceType::Binary,
30+
) {
31+
Ok(r) => println!(
32+
"In-process result: algo={:?} ent={}",
33+
r.algorithm, r.entropy
34+
),
2635
Err(e2) => eprintln!("Fallback also failed: {}", e2),
2736
}
2837
}

examples/08_confidence_calibration.rs

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
use cryptotrace::core::calibration::{generate_synthetic_dataset, train, predict_proba, signal_contributions, save_model, load_model};
1+
use cryptotrace::core::calibration::{
2+
generate_synthetic_dataset, load_model, predict_proba, save_model, signal_contributions, train,
3+
};
24
use cryptotrace::types::SignalBreakdown;
35

46
fn main() {
@@ -8,7 +10,10 @@ fn main() {
810
println!(" {} samples generated", dataset.len());
911

1012
let model = train(&dataset, 0.01, 1000, 0.001);
11-
println!("Model trained: intercept={:.4}, weights={:?}", model.intercept, model.weights);
13+
println!(
14+
"Model trained: intercept={:.4}, weights={:?}",
15+
model.intercept, model.weights
16+
);
1217
println!("Dataset size: {}", model.dataset_size);
1318

1419
let test_signals = SignalBreakdown {
@@ -26,12 +31,20 @@ fn main() {
2631
let contribs = signal_contributions(&model, &test_signals);
2732
println!("\nSignal contributions:");
2833
for sc in &contribs {
29-
println!(" {:20} {:>8} {:.4}", sc.signal_name, if sc.coefficient > 0.0 { "+" } else { "-" }, sc.contribution);
34+
println!(
35+
" {:20} {:>8} {:.4}",
36+
sc.signal_name,
37+
if sc.coefficient > 0.0 { "+" } else { "-" },
38+
sc.contribution
39+
);
3040
}
3141

3242
save_model(&model, "calibration_example.json").ok();
3343
if let Ok(loaded) = load_model("calibration_example.json") {
34-
println!("\nModel save/load roundtrip: OK (weights={:?})", loaded.weights);
44+
println!(
45+
"\nModel save/load roundtrip: OK (weights={:?})",
46+
loaded.weights
47+
);
3548
}
3649
std::fs::remove_file("calibration_example.json").ok();
3750
}

examples/09_sliding_entropy.rs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,40 @@ use std::fs;
22

33
fn main() {
44
let args: Vec<String> = std::env::args().collect();
5-
let path = if args.len() > 1 { &args[1] } else { "Cargo.toml" };
5+
let path = if args.len() > 1 {
6+
&args[1]
7+
} else {
8+
"Cargo.toml"
9+
};
610
let data = fs::read(path).expect("Failed to read file");
711

812
println!("File: {} ({} bytes)", path, data.len());
913
let (entropy, _) = cryptotrace::core::entropy::shannon_entropy(&data);
1014
println!("Global Shannon entropy: {:.2} bits/byte", entropy);
1115

12-
let sw = cryptotrace::core::sliding_entropy::sliding_window_entropy(&data, Some(4096), None, Some(7.5));
16+
let sw = cryptotrace::core::sliding_entropy::sliding_window_entropy(
17+
&data,
18+
Some(4096),
19+
None,
20+
Some(7.5),
21+
);
1322

1423
if sw.window_scores.is_empty() {
1524
println!("File too small for any window");
1625
return;
1726
}
1827

1928
let avg: f64 = sw.window_scores.iter().sum::<f64>() / sw.window_scores.len() as f64;
20-
let max_score = sw.window_scores.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
21-
let min_score = sw.window_scores.iter().cloned().fold(f64::INFINITY, f64::min);
29+
let max_score = sw
30+
.window_scores
31+
.iter()
32+
.cloned()
33+
.fold(f64::NEG_INFINITY, f64::max);
34+
let min_score = sw
35+
.window_scores
36+
.iter()
37+
.cloned()
38+
.fold(f64::INFINITY, f64::min);
2239

2340
println!("Windows analyzed: {}", sw.window_scores.len());
2441
println!("Avg window entropy: {:.2}", avg);

0 commit comments

Comments
 (0)