96 Zeilen
2,6 KiB
Rust
96 Zeilen
2,6 KiB
Rust
use crate::{
|
|
consts::{
|
|
BRAINPOOL_MIDDLE,
|
|
BRAINPOOL_STRONG,
|
|
BRAINPOOL_WEAK,
|
|
SECP_MIDDLE,
|
|
SECP_STRONG,
|
|
SECP_WEAK,
|
|
},
|
|
types::cryptography::{
|
|
Algorithm,
|
|
Strength,
|
|
},
|
|
};
|
|
use log::*;
|
|
use openssl::{
|
|
ec::EcKey,
|
|
error::ErrorStack,
|
|
nid::Nid,
|
|
pkey::{
|
|
PKey,
|
|
Private,
|
|
},
|
|
rsa::Rsa,
|
|
x509::{
|
|
X509Name,
|
|
X509NameBuilder,
|
|
},
|
|
};
|
|
|
|
pub fn prefix_emails(input: Vec<String>) -> Vec<String> {
|
|
let mut output = Vec::with_capacity(input.len());
|
|
for mut addr in input {
|
|
if addr.starts_with("mailto:") {
|
|
output.push(addr);
|
|
} else {
|
|
addr.insert_str(0, "mailto:");
|
|
output.push(addr);
|
|
}
|
|
}
|
|
output
|
|
}
|
|
|
|
|
|
fn gen_ec_key(algorithm: Algorithm, strength: Strength) -> Result<PKey<Private>, ErrorStack> {
|
|
let (weak, middle, strong) = match algorithm {
|
|
Algorithm::Rsa | Algorithm::ED25519 => unreachable!(),
|
|
Algorithm::Secp => (SECP_WEAK, SECP_MIDDLE, SECP_STRONG),
|
|
Algorithm::Brainpool => (BRAINPOOL_WEAK, BRAINPOOL_MIDDLE, BRAINPOOL_STRONG),
|
|
};
|
|
let algo = EcKey::from_curve_name(match strength {
|
|
Strength::Weak => weak,
|
|
Strength::Middle => middle,
|
|
Strength::Strong => strong,
|
|
});
|
|
let key = match algo {
|
|
Err(error) => {
|
|
error!("Failed to generate key due of an problem with the algorithms: {error}");
|
|
return Err(error);
|
|
},
|
|
Ok(algo) => EcKey::generate(algo.group()),
|
|
};
|
|
match key {
|
|
Ok(private) => PKey::from_ec_key(private),
|
|
Err(error) => {
|
|
error!("Failed to generate Private key from EcKey: {error}");
|
|
Err(error)
|
|
},
|
|
}
|
|
}
|
|
|
|
|
|
pub fn gen_key(algorithm: Algorithm, strength: Strength) -> Result<PKey<Private>, String> {
|
|
let key = match algorithm {
|
|
Algorithm::Rsa => {
|
|
let key = Rsa::generate(strength.rsabits());
|
|
match key {
|
|
Ok(key) => PKey::from_rsa(key),
|
|
Err(error) => Err(error),
|
|
}
|
|
},
|
|
Algorithm::Secp => gen_ec_key(Algorithm::Secp, strength),
|
|
Algorithm::ED25519 => PKey::generate_ed25519(),
|
|
Algorithm::Brainpool => gen_ec_key(Algorithm::Brainpool, strength),
|
|
};
|
|
match key {
|
|
Ok(key) => Ok(key),
|
|
Err(error) => Err(format!("Failed to generate an key to the parameters: {error}")),
|
|
}
|
|
}
|
|
|
|
pub fn string_to_cn(name: String) -> X509Name {
|
|
let mut builder = X509NameBuilder::new().unwrap();
|
|
builder.append_entry_by_nid(Nid::COMMONNAME, &name).unwrap();
|
|
builder.build()
|
|
}
|