diff --git a/crates/bitwarden-ssh/src/lib.rs b/crates/bitwarden-ssh/src/lib.rs index 668afe1d..f95b504a 100644 --- a/crates/bitwarden-ssh/src/lib.rs +++ b/crates/bitwarden-ssh/src/lib.rs @@ -1,6 +1,5 @@ -use rand::SeedableRng; -use rand_chacha::ChaCha8Rng; -use ssh_key::{Algorithm, HashAlg, LineEnding}; +use error::KeyGenerationError; +use ssh_key::{rand_core::CryptoRngCore, Algorithm, HashAlg, LineEnding}; pub mod error; pub mod models; @@ -14,10 +13,14 @@ pub enum KeyAlgorithm { pub fn generate_keypair( key_algorithm: KeyAlgorithm, ) -> Result { - // sourced from cryptographically secure entropy source, with sources for all targets: https://docs.rs/getrandom - // if it cannot be securely sourced, this will panic instead of leading to a weak key - let mut rng: ChaCha8Rng = ChaCha8Rng::from_entropy(); + let rng = rand::thread_rng(); + generate_keypair_internal(key_algorithm, rng) +} +fn generate_keypair_internal( + key_algorithm: KeyAlgorithm, + mut rng: impl CryptoRngCore, +) -> Result { let key = match key_algorithm { KeyAlgorithm::Ed25519 => ssh_key::PrivateKey::random(&mut rng, Algorithm::Ed25519), KeyAlgorithm::Rsa3072 | KeyAlgorithm::Rsa4096 => { @@ -28,21 +31,19 @@ pub fn generate_keypair( }; let rsa_keypair = ssh_key::private::RsaKeypair::random(&mut rng, bits) - .map_err(|e| error::KeyGenerationError::KeyGenerationError(e.to_string()))?; + .map_err(|e| KeyGenerationError::KeyGenerationError(e.to_string()))?; - let private_key = ssh_key::PrivateKey::new( - ssh_key::private::KeypairData::from(rsa_keypair), - "".to_string(), - ) - .map_err(|e| error::KeyGenerationError::KeyGenerationError(e.to_string()))?; + let private_key = + ssh_key::PrivateKey::new(ssh_key::private::KeypairData::from(rsa_keypair), "") + .map_err(|e| KeyGenerationError::KeyGenerationError(e.to_string()))?; Ok(private_key) } } - .map_err(|e| error::KeyGenerationError::KeyGenerationError(e.to_string()))?; + .map_err(|e| KeyGenerationError::KeyGenerationError(e.to_string()))?; let private_key_openssh = key .to_openssh(LineEnding::LF) - .map_err(|e| error::KeyGenerationError::KeyConversionError(e.to_string()))?; + .map_err(|e| KeyGenerationError::KeyConversionError(e.to_string()))?; Ok(models::SshKey { private_key: private_key_openssh.to_string(), public_key: key.public_key().to_string(),