Crypto
WASM
TESTS
This commit is contained in:
Alex Emmet 2026-06-25 22:08:44 +02:00
commit 687e6f9642
49 changed files with 6272 additions and 366 deletions

View file

@ -1,4 +1,7 @@
use std::fs;
use std::path::Path;
use base64::Engine;
pub fn load_or_generate_tls(
cert_path: &str,
@ -10,6 +13,12 @@ pub fn load_or_generate_tls(
}
println!("Generating self-signed TLS certificate ...");
if let Some(parent) = Path::new(cert_path).parent() {
fs::create_dir_all(parent)?;
}
if let Some(parent) = Path::new(key_path).parent() {
fs::create_dir_all(parent)?;
}
let key_pair = rcgen::KeyPair::generate()?;
let params = rcgen::CertificateParams::new(vec!["localhost".into(), "127.0.0.1".into()])?;
let cert = params.self_signed(&key_pair)?;
@ -23,3 +32,39 @@ pub fn load_or_generate_tls(
Ok((cert_str.into_bytes(), key_str.into_bytes()))
}
pub fn certificate_sha256_hex(cert: &[u8]) -> Result<String, Box<dyn std::error::Error>> {
let der = if cert.starts_with(b"-----BEGIN CERTIFICATE-----") {
let pem = std::str::from_utf8(cert)?;
let base64 = pem
.lines()
.filter(|line| !line.starts_with("-----"))
.collect::<String>();
base64::engine::general_purpose::STANDARD.decode(base64)?
} else {
cert.to_vec()
};
Ok(hex::encode(mtp::crypto::sha256(&der)))
}
pub fn export_webtransport_cert_hash(hash: &str) -> Result<(), Box<dyn std::error::Error>> {
let public_dir = if Path::new("web-client").exists() {
Path::new("web-client/public")
} else {
Path::new("example-usage/web-client/public")
};
fs::create_dir_all(public_dir)?;
fs::write(public_dir.join("mtp_dev_cert_hash.txt"), hash)?;
let dev_cert_dir = if Path::new("dev-cert").exists() {
Path::new("dev-cert")
} else {
Path::new("example-usage/dev-cert")
};
if dev_cert_dir.exists() {
fs::write(dev_cert_dir.join("sha256.txt"), hash)?;
}
Ok(())
}