feat: improve API in ::certs::fingerprint
This commit is contained in:
parent
dfeaa50440
commit
dcd6359fcc
1 changed files with 11 additions and 6 deletions
|
@ -6,15 +6,13 @@ use super::verifier::CertificateDer;
|
||||||
const SHA256_B64_LEN: usize = 44; // 4 * ((256 / 8) as f64 / 3 as f64).ceil()
|
const SHA256_B64_LEN: usize = 44; // 4 * ((256 / 8) as f64 / 3 as f64).ceil()
|
||||||
const SHA512_B64_LEN: usize = 88; // 4 * ((512 / 8) as f64 / 3 as f64).ceil()
|
const SHA512_B64_LEN: usize = 88; // 4 * ((512 / 8) as f64 / 3 as f64).ceil()
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
pub enum Algorithm {
|
pub enum Algorithm {
|
||||||
Sha256,
|
Sha256,
|
||||||
Sha512,
|
Sha512,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn generate_fingerprint(
|
pub fn generate_fingerprint(cert: &CertificateDer, algo: Algorithm) -> String {
|
||||||
cert: &CertificateDer,
|
|
||||||
algo: Algorithm,
|
|
||||||
) -> Result<String, base64ct::InvalidLengthError> {
|
|
||||||
match algo {
|
match algo {
|
||||||
Algorithm::Sha256 => {
|
Algorithm::Sha256 => {
|
||||||
let mut hasher = Sha256::new();
|
let mut hasher = Sha256::new();
|
||||||
|
@ -23,7 +21,12 @@ pub fn generate_fingerprint(
|
||||||
}
|
}
|
||||||
let bin = hasher.finalize();
|
let bin = hasher.finalize();
|
||||||
let mut buf = [0; SHA256_B64_LEN];
|
let mut buf = [0; SHA256_B64_LEN];
|
||||||
Base64Unpadded::encode(&bin, &mut buf).map(|hash| hash.to_owned())
|
// Note on unwrap:
|
||||||
|
// Encoder returns error only if buffer length is insufficient.
|
||||||
|
// SHA-256 is *always* 256 bits (32 bytes),
|
||||||
|
// after we apply base64 formula we get 44 bytes in output including padding.
|
||||||
|
// See also comment near const SHA256_B64_LEN
|
||||||
|
Base64Unpadded::encode(&bin, &mut buf).unwrap().to_owned()
|
||||||
}
|
}
|
||||||
Algorithm::Sha512 => {
|
Algorithm::Sha512 => {
|
||||||
let mut hasher = Sha512::new();
|
let mut hasher = Sha512::new();
|
||||||
|
@ -32,7 +35,9 @@ pub fn generate_fingerprint(
|
||||||
}
|
}
|
||||||
let bin = hasher.finalize();
|
let bin = hasher.finalize();
|
||||||
let mut buf = [0; SHA512_B64_LEN];
|
let mut buf = [0; SHA512_B64_LEN];
|
||||||
Base64Unpadded::encode(&bin, &mut buf).map(|hash| hash.to_owned())
|
// Same explanation for unwrap, see above
|
||||||
|
// SHA-512 is always 512 bits or 64 bytes
|
||||||
|
Base64Unpadded::encode(&bin, &mut buf).unwrap().to_owned()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue