feat: improve API in ::certs::fingerprint

This commit is contained in:
DarkCat09 2024-08-06 11:07:35 +04:00
parent dfeaa50440
commit dcd6359fcc
Signed by: DarkCat09
GPG key ID: 0A26CD5B3345D6E3

View file

@ -6,15 +6,13 @@ use super::verifier::CertificateDer;
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()
#[derive(Debug, Clone, Copy)]
pub enum Algorithm {
Sha256,
Sha512,
}
pub fn generate_fingerprint(
cert: &CertificateDer,
algo: Algorithm,
) -> Result<String, base64ct::InvalidLengthError> {
pub fn generate_fingerprint(cert: &CertificateDer, algo: Algorithm) -> String {
match algo {
Algorithm::Sha256 => {
let mut hasher = Sha256::new();
@ -23,7 +21,12 @@ pub fn generate_fingerprint(
}
let bin = hasher.finalize();
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 => {
let mut hasher = Sha512::new();
@ -32,7 +35,9 @@ pub fn generate_fingerprint(
}
let bin = hasher.finalize();
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()
}
}
}