diff --git a/Cargo.lock b/Cargo.lock index d6e9cd9..0215741 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -812,6 +812,7 @@ version = "0.3.0-pre.0" dependencies = [ "base64ct", "bytes", + "digest", "hex-literal", "pem-rfc7468", "sha2", diff --git a/ssh-encoding/Cargo.toml b/ssh-encoding/Cargo.toml index 2c6f779..c2ac88d 100644 --- a/ssh-encoding/Cargo.toml +++ b/ssh-encoding/Cargo.toml @@ -20,6 +20,7 @@ base64ct = { version = "1.4", optional = true } bytes = { version = "1", optional = true, default-features = false } pem-rfc7468 = { version = "1.0.0-rc.1", optional = true } sha2 = { version = "=0.11.0-pre.4", optional = true, default-features = false } +digest = { version = "=0.11.0-pre.9", default-features = false } [dev-dependencies] hex-literal = "0.4.1" diff --git a/ssh-encoding/src/lib.rs b/ssh-encoding/src/lib.rs index 3972909..c11d190 100644 --- a/ssh-encoding/src/lib.rs +++ b/ssh-encoding/src/lib.rs @@ -48,7 +48,7 @@ pub use crate::{ error::{Error, Result}, label::{Label, LabelError}, reader::Reader, - writer::Writer, + writer::{DigestWriter, Writer}, }; #[cfg(feature = "base64")] diff --git a/ssh-encoding/src/writer.rs b/ssh-encoding/src/writer.rs index 41641da..e716e38 100644 --- a/ssh-encoding/src/writer.rs +++ b/ssh-encoding/src/writer.rs @@ -8,8 +8,7 @@ use alloc::vec::Vec; #[cfg(feature = "bytes")] use bytes::{BufMut, BytesMut}; -#[cfg(feature = "sha2")] -use sha2::{Digest, Sha256, Sha512}; +use digest::Digest; /// Writer trait which encodes the SSH binary format to various output /// encodings. @@ -34,18 +33,18 @@ impl Writer for BytesMut { } } -#[cfg(feature = "sha2")] -impl Writer for Sha256 { - fn write(&mut self, bytes: &[u8]) -> Result<()> { - self.update(bytes); - Ok(()) - } -} +/// Wrapper for digests. +/// +/// This allows to update digests from the serializer directly. +#[derive(Debug)] +pub struct DigestWriter<'d, D>(pub &'d mut D); -#[cfg(feature = "sha2")] -impl Writer for Sha512 { +impl Writer for DigestWriter<'_, D> +where + D: Digest, +{ fn write(&mut self, bytes: &[u8]) -> Result<()> { - self.update(bytes); + self.0.update(bytes); Ok(()) } } diff --git a/ssh-key/src/fingerprint.rs b/ssh-key/src/fingerprint.rs index 6a37b8b..35c708e 100644 --- a/ssh-key/src/fingerprint.rs +++ b/ssh-key/src/fingerprint.rs @@ -10,7 +10,7 @@ use core::{ }; use encoding::{ base64::{Base64Unpadded, Encoding}, - Encode, + DigestWriter, Encode, }; use sha2::{Digest, Sha256, Sha512}; @@ -63,12 +63,16 @@ impl Fingerprint { match algorithm { HashAlg::Sha256 => { let mut digest = Sha256::new(); - public_key.encode(&mut digest).expect(FINGERPRINT_ERR_MSG); + public_key + .encode(&mut DigestWriter(&mut digest)) + .expect(FINGERPRINT_ERR_MSG); Self::Sha256(digest.finalize().into()) } HashAlg::Sha512 => { let mut digest = Sha512::new(); - public_key.encode(&mut digest).expect(FINGERPRINT_ERR_MSG); + public_key + .encode(&mut DigestWriter(&mut digest)) + .expect(FINGERPRINT_ERR_MSG); Self::Sha512(digest.finalize().into()) } }