Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion ssh-key/src/private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,25 @@ impl PrivateKey {
&self,
rng: &mut impl CryptoRngCore,
password: impl AsRef<[u8]>,
) -> Result<Self> {
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<Self> {
let checkint = rng.next_u32();

self.encrypt_with(
Cipher::default(),
cipher,
Kdf::new(Default::default(), rng)?,
checkint,
password,
Expand Down
10 changes: 2 additions & 8 deletions ssh-key/tests/encrypted_private_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down