From dcd6359fcc0ad10c4be7bd893a25d9cd1554550b Mon Sep 17 00:00:00 2001 From: DarkCat09 Date: Tue, 6 Aug 2024 11:07:35 +0400 Subject: [PATCH] feat: improve API in ::certs::fingerprint --- src/certs/fingerprint.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/certs/fingerprint.rs b/src/certs/fingerprint.rs index 8a89ad9..2846b3e 100644 --- a/src/certs/fingerprint.rs +++ b/src/certs/fingerprint.rs @@ -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 { +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() } } }