diff --git a/ssh-key/src/private.rs b/ssh-key/src/private.rs index bc8d36d6..bb911f45 100644 --- a/ssh-key/src/private.rs +++ b/ssh-key/src/private.rs @@ -338,11 +338,25 @@ impl PrivateKey { &self, rng: &mut impl CryptoRngCore, password: impl AsRef<[u8]>, + ) -> Result { + self.encrypt_with_cipher(rng, Cipher::default(), password) + } + + /// Encrypt an unencrypted private key using the provided password to + /// derive an encryption key for the provided [`Cipher`]. + /// + /// Returns [`Error::Encrypted`] if the private key is already encrypted. + #[cfg(feature = "encryption")] + pub fn encrypt_with_cipher( + &self, + rng: &mut impl CryptoRngCore, + cipher: Cipher, + password: impl AsRef<[u8]>, ) -> Result { let checkint = rng.next_u32(); self.encrypt_with( - Cipher::default(), + cipher, Kdf::new(Default::default(), rng)?, checkint, password, diff --git a/ssh-key/tests/encrypted_private_key.rs b/ssh-key/tests/encrypted_private_key.rs index abf52547..12cef98d 100644 --- a/ssh-key/tests/encrypted_private_key.rs +++ b/ssh-key/tests/encrypted_private_key.rs @@ -126,18 +126,12 @@ fn encrypt_openssh_aes_ctr() { #[cfg(all(feature = "aes-gcm", feature = "getrandom"))] #[test] fn encrypt_openssh_aes_gcm() { - use rand_core::{OsRng, RngCore}; + use rand_core::OsRng; let key_dec = PrivateKey::from_openssh(OPENSSH_ED25519_EXAMPLE).unwrap(); - let checkint = RngCore::next_u32(&mut OsRng); let key_enc = key_dec - .encrypt_with( - Cipher::Aes256Gcm, - Kdf::new(Default::default(), &mut OsRng).unwrap(), - checkint, - PASSWORD, - ) + .encrypt_with_cipher(&mut OsRng, Cipher::Aes256Gcm, PASSWORD) .unwrap(); // Ensure encrypted key round trips through encoder/decoder