Skip to main content

ssh_key/
private.rs

1//! SSH private key support.
2//!
3//! Support for decoding SSH private keys (i.e. digital signature keys)
4//! from the OpenSSH file format:
5//!
6//! <https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.key?annotate=HEAD>
7//!
8//! ## Decrypting encrypted private keys
9//!
10//! When the `encryption` feature of this crate is enabled, it's possible to
11//! decrypt keys which have been encrypted under a password:
12//!
13#![cfg_attr(feature = "encryption", doc = " ```")]
14#![cfg_attr(not(feature = "encryption"), doc = " ```ignore")]
15//! # fn main() -> Result<(), ssh_key::Error> {
16//! use ssh_key::PrivateKey;
17//!
18//! // WARNING: don't actually hardcode private keys in source code!!!
19//! let encoded_key = r#"
20//! -----BEGIN OPENSSH PRIVATE KEY-----
21//! b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABBKH96ujW
22//! umB6/WnTNPjTeaAAAAEAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN
23//! 796jTiQfZfG1KaT0PtFDJ/XFSqtiAAAAoFzvbvyFMhAiwBOXF0mhUUacPUCMZXivG2up2c
24//! hEnAw1b6BLRPyWbY5cC2n9ggD4ivJ1zSts6sBgjyiXQAReyrP35myYvT/OIB/NpwZM/xIJ
25//! N7MHSUzlkX4adBrga3f7GS4uv4ChOoxC4XsE5HsxtGsq1X8jzqLlZTmOcxkcEneYQexrUc
26//! bQP0o+gL5aKK8cQgiIlXeDbRjqhc4+h4EF6lY=
27//! -----END OPENSSH PRIVATE KEY-----
28//! "#;
29//!
30//! let encrypted_key = PrivateKey::from_openssh(encoded_key)?;
31//! assert!(encrypted_key.is_encrypted());
32//!
33//! // WARNING: don't hardcode passwords, and this one's bad anyway
34//! let password = "hunter42";
35//!
36//! let decrypted_key = encrypted_key.decrypt(password)?;
37//! assert!(!decrypted_key.is_encrypted());
38//! # Ok(())
39//! # }
40//! ```
41//!
42//! ## Encrypting plaintext private keys
43//!
44//! When the `encryption` feature of this crate is enabled, it's possible to
45//! encrypt plaintext private keys under a provided password.
46//!
47//! The example below also requires enabling this crate's `getrandom` feature.
48//!
49#![cfg_attr(
50    all(feature = "ed25519", feature = "encryption", feature = "getrandom",),
51    doc = " ```"
52)]
53#![cfg_attr(
54    not(all(feature = "ed25519", feature = "encryption", feature = "getrandom",)),
55    doc = " ```ignore"
56)]
57//! # fn main() -> Result<(), ssh_key::Error> {
58//! use ssh_key::{Algorithm, PrivateKey, getrandom::SysRng, rand_core::UnwrapErr};
59//!
60//! // Generate a random key
61//! let mut rng = UnwrapErr(SysRng);
62//! let unencrypted_key = PrivateKey::random(&mut rng, Algorithm::Ed25519)?;
63//!
64//! // WARNING: don't hardcode passwords, and this one's bad anyway
65//! let password = "hunter42";
66//!
67//! let encrypted_key = unencrypted_key.encrypt(&mut SysRng, password)?;
68//! assert!(encrypted_key.is_encrypted());
69//! # Ok(())
70//! # }
71//! ```
72//!
73//! ## Generating random keys
74//!
75//! This crate supports generation of random keys using algorithm-specific
76//! backends gated on cargo features.
77//!
78//! The examples below require enabling this crate's `getrandom` feature as
79//! well as the crate feature identified in backticks in the title of each
80//! example.
81//!
82#![cfg_attr(all(feature = "ed25519", feature = "getrandom"), doc = " ```")]
83#![cfg_attr(
84    not(all(feature = "ed25519", feature = "getrandom")),
85    doc = " ```ignore"
86)]
87//! # fn main() -> Result<(), ssh_key::Error> {
88//! use ssh_key::{Algorithm, PrivateKey, getrandom::SysRng, rand_core::UnwrapErr};
89//!
90//! let mut rng = UnwrapErr(SysRng);
91//! let private_key = PrivateKey::random(&mut rng, Algorithm::Ed25519)?;
92//! # Ok(())
93//! # }
94//! ```
95
96#[cfg(feature = "alloc")]
97mod dsa;
98#[cfg(feature = "ecdsa")]
99mod ecdsa;
100mod ed25519;
101mod keypair;
102#[cfg(feature = "alloc")]
103mod opaque;
104#[cfg(feature = "alloc")]
105mod rsa;
106#[cfg(feature = "alloc")]
107mod sk;
108
109pub use self::{
110    ed25519::{Ed25519Keypair, Ed25519PrivateKey},
111    keypair::KeypairData,
112};
113
114#[cfg(feature = "alloc")]
115pub use crate::{
116    Comment, SshSig,
117    encoding::digest::Digest,
118    private::{
119        dsa::{DsaKeypair, DsaPrivateKey},
120        opaque::{OpaqueKeypair, OpaqueKeypairBytes, OpaquePrivateKeyBytes},
121        rsa::{RsaKeypair, RsaPrivateKey},
122        sk::SkEd25519,
123    },
124};
125
126#[cfg(all(feature = "mldsa", feature = "ed25519"))]
127pub use crate::composite::{MlDsa44Ed25519Keypair, MlDsa44Ed25519PrivateKey};
128#[cfg(all(feature = "mldsa", feature = "p384"))]
129pub use crate::composite::{MlDsa87P384Keypair, MlDsa87P384PrivateKey};
130
131#[cfg(feature = "ecdsa")]
132pub use self::ecdsa::{EcdsaKeypair, EcdsaPrivateKey};
133
134#[cfg(all(feature = "alloc", feature = "ecdsa"))]
135pub use self::sk::SkEcdsaSha2NistP256;
136
137use crate::{Algorithm, Cipher, Error, Kdf, PublicKey, Result, public};
138use cipher::Tag;
139use core::str;
140use ctutils::{Choice, CtEq};
141use encoding::{
142    CheckedSum, Decode, DecodePem, Decoder, Encode, EncodePem, Reader, Writer,
143    pem::{LineEnding, PemLabel},
144};
145
146#[cfg(feature = "alloc")]
147use {
148    crate::AssociatedHashAlg,
149    alloc::{string::String, vec::Vec},
150    zeroize::Zeroizing,
151};
152
153#[cfg(feature = "encryption")]
154use rand_core::TryCryptoRng;
155
156#[cfg(feature = "rand_core")]
157use rand_core::CryptoRng;
158
159#[cfg(feature = "sha2")]
160use crate::Fingerprint;
161
162#[cfg(any(feature = "alloc", feature = "sha2"))]
163use crate::HashAlg;
164
165#[cfg(feature = "std")]
166use std::{fs::File, path::Path};
167
168#[cfg(feature = "std")]
169use std::io::{self, Read, Write};
170
171#[cfg(all(unix, feature = "std"))]
172use std::os::unix::fs::OpenOptionsExt;
173
174/// Error message for infallible conversions (used by `expect`)
175const CONVERSION_ERROR_MSG: &str = "SSH private key conversion error";
176
177/// Default key size to use for RSA keys in bits.
178#[cfg(all(feature = "rand_core", feature = "rsa"))]
179const DEFAULT_RSA_KEY_SIZE: usize = 4096;
180
181/// Maximum supported block size.
182///
183/// This is the block size used by e.g. AES.
184const MAX_BLOCK_SIZE: usize = 16;
185
186/// Padding bytes to use.
187const PADDING_BYTES: [u8; MAX_BLOCK_SIZE] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
188
189/// Unix file permissions for SSH private keys.
190#[cfg(all(unix, feature = "std"))]
191const UNIX_FILE_PERMISSIONS: u32 = 0o600;
192
193/// SSH private key.
194#[derive(Clone, Debug)]
195pub struct PrivateKey {
196    /// Cipher algorithm.
197    cipher: Cipher,
198
199    /// KDF options.
200    kdf: Kdf,
201
202    /// "Checkint" value used to verify successful decryption.
203    checkint: Option<u32>,
204
205    /// Public key.
206    public_key: PublicKey,
207
208    /// Private keypair data.
209    key_data: KeypairData,
210
211    /// Authentication tag for authenticated encryption modes.
212    auth_tag: Option<Tag>,
213}
214
215impl PrivateKey {
216    /// Magic string used to identify keys in this format.
217    const AUTH_MAGIC: &'static [u8] = b"openssh-key-v1\0";
218
219    /// Create a new unencrypted private key with the given keypair data and comment.
220    ///
221    /// On `no_alloc` platforms, use `PrivateKey::try_from(key_data)` instead.
222    ///
223    /// # Errors
224    /// Returns [`Error::Encrypted`] if the key is encrypted.
225    #[cfg(feature = "alloc")]
226    pub fn new(key_data: KeypairData, comment: impl Into<Comment>) -> Result<Self> {
227        if key_data.is_encrypted() {
228            return Err(Error::Encrypted);
229        }
230
231        let mut private_key = Self::try_from(key_data)?;
232        private_key.public_key.comment = comment.into();
233        Ok(private_key)
234    }
235
236    /// Parse an OpenSSH-formatted PEM private key.
237    ///
238    /// OpenSSH-formatted private keys begin with the following:
239    ///
240    /// ```text
241    /// -----BEGIN OPENSSH PRIVATE KEY-----
242    /// ```
243    ///
244    /// # Errors
245    /// Returns [`Error::Encoding`] in the event of an encoding error.
246    pub fn from_openssh(pem: impl AsRef<[u8]>) -> Result<Self> {
247        Self::decode_pem(pem)
248    }
249
250    /// Parse a PuTTY PPK private key.
251    ///
252    /// PPK-formatted private keys begin with the following:
253    ///
254    /// ```text
255    /// PuTTY-User-Key-File-<VERSION>: <ALGORITHM>
256    /// ```
257    ///
258    /// # Errors
259    /// Returns [`Error::Encoding`] in the event of an encoding error.
260    #[cfg(feature = "ppk")]
261    pub fn from_ppk(ppk: impl AsRef<str>, passphrase: Option<String>) -> Result<Self> {
262        use crate::ppk::PpkContainer;
263
264        let ppk: PpkContainer = PpkContainer::new(ppk.as_ref().try_into()?, passphrase)?;
265
266        Ok(Self {
267            auth_tag: None,
268            checkint: None,
269            cipher: Cipher::None,
270            kdf: Kdf::None,
271            key_data: ppk.keypair_data,
272            public_key: ppk.public_key,
273        })
274    }
275
276    /// Parse a raw binary SSH private key.
277    ///
278    /// # Errors
279    /// Returns [`Error::Encoding`] in the event of an encoding error.
280    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
281        let mut reader = Decoder::new(bytes)?;
282        let private_key = Self::decode(&mut reader)?;
283        Ok(reader.finish(private_key)?)
284    }
285
286    /// Encode OpenSSH-formatted (PEM) private key.
287    ///
288    /// # Errors
289    /// Returns [`Error::Encoding`] in the event of an encoding error.
290    pub fn encode_openssh<'o>(
291        &self,
292        line_ending: LineEnding,
293        out: &'o mut [u8],
294    ) -> Result<&'o str> {
295        Ok(self.encode_pem(line_ending, out)?)
296    }
297
298    /// Encode an OpenSSH-formatted PEM private key, allocating a self-zeroizing [`String`] for the
299    /// result.
300    ///
301    /// # Errors
302    /// Returns [`Error::Encoding`] in the event of an encoding error.
303    #[cfg(feature = "alloc")]
304    pub fn to_openssh(&self, line_ending: LineEnding) -> Result<Zeroizing<String>> {
305        Ok(self.encode_pem_string(line_ending).map(Zeroizing::new)?)
306    }
307
308    /// Serialize SSH private key as raw bytes.
309    ///
310    /// # Errors
311    /// Returns [`Error::Encoding`] in the event of an encoding error.
312    #[cfg(feature = "alloc")]
313    pub fn to_bytes(&self) -> Result<Zeroizing<Vec<u8>>> {
314        let mut private_key_bytes = Vec::with_capacity(self.encoded_len()?);
315        self.encode(&mut private_key_bytes)?;
316        Ok(Zeroizing::new(private_key_bytes))
317    }
318
319    /// Sign the given message using this private key, returning an [`SshSig`].
320    ///
321    /// These signatures can be produced using `ssh-keygen -Y sign`. They're
322    /// encoded as PEM and begin with the following:
323    ///
324    /// ```text
325    /// -----BEGIN SSH SIGNATURE-----
326    /// ```
327    ///
328    /// See [PROTOCOL.sshsig] for more information.
329    ///
330    /// # Usage
331    ///
332    /// See also: [`PublicKey::verify`].
333    ///
334    #[cfg_attr(feature = "ed25519", doc = "```")]
335    #[cfg_attr(not(feature = "ed25519"), doc = "```ignore")]
336    /// # fn main() -> Result<(), ssh_key::Error> {
337    /// use ssh_key::{PrivateKey, HashAlg, SshSig};
338    ///
339    /// // Message to be signed.
340    /// let message = b"testing";
341    ///
342    /// // Example domain/namespace used for the message.
343    /// let namespace = "example";
344    ///
345    /// // Private key to use when computing the signature.
346    /// // WARNING: don't actually hardcode private keys in source code!!!
347    /// let encoded_private_key = r#"
348    /// -----BEGIN OPENSSH PRIVATE KEY-----
349    /// b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
350    /// QyNTUxOQAAACCzPq7zfqLffKoBDe/eo04kH2XxtSmk9D7RQyf1xUqrYgAAAJgAIAxdACAM
351    /// XQAAAAtzc2gtZWQyNTUxOQAAACCzPq7zfqLffKoBDe/eo04kH2XxtSmk9D7RQyf1xUqrYg
352    /// AAAEC2BsIi0QwW2uFscKTUUXNHLsYX4FxlaSDSblbAj7WR7bM+rvN+ot98qgEN796jTiQf
353    /// ZfG1KaT0PtFDJ/XFSqtiAAAAEHVzZXJAZXhhbXBsZS5jb20BAgMEBQ==
354    /// -----END OPENSSH PRIVATE KEY-----
355    /// "#;
356    ///
357    /// let private_key = encoded_private_key.parse::<PrivateKey>()?;
358    /// let signature = private_key.sign(namespace, HashAlg::default(), message)?;
359    /// // assert!(private_key.public_key().verify(namespace, message, &signature).is_ok());
360    /// # Ok(())
361    /// # }
362    /// ```
363    ///
364    /// [PROTOCOL.sshsig]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.sshsig?annotate=HEAD
365    ///
366    /// # Errors
367    /// Propagates errors from [`SshSig::sign`].
368    #[cfg(all(feature = "alloc", feature = "sha2"))]
369    pub fn sign(&self, namespace: &str, hash_alg: HashAlg, msg: &[u8]) -> Result<SshSig> {
370        SshSig::sign(self, namespace, hash_alg, msg)
371    }
372
373    /// Sign the given message [`Digest`] using this private key, returning an [`SshSig`].
374    ///
375    /// These signatures can be produced using `ssh-keygen -Y sign`.
376    ///
377    /// For more information, see [`PrivateKey::sign`].
378    ///
379    /// # Errors
380    /// Propagates errors from [`SshSig::sign_digest`].
381    #[cfg(feature = "alloc")]
382    pub fn sign_digest<D: AssociatedHashAlg + Digest>(
383        &self,
384        namespace: &str,
385        digest: D,
386    ) -> Result<SshSig> {
387        SshSig::sign_digest(self, namespace, digest)
388    }
389
390    /// Sign the given raw message prehash using this private key, returning an [`SshSig`].
391    ///
392    /// These signatures can be produced using `ssh-keygen -Y sign`.
393    ///
394    /// For more information, see [`PrivateKey::sign`].
395    ///
396    /// # Errors
397    /// Propagates errors from [`SshSig::sign_prehash`].
398    #[cfg(feature = "alloc")]
399    pub fn sign_prehash(
400        &self,
401        namespace: &str,
402        hash_alg: HashAlg,
403        prehash: &[u8],
404    ) -> Result<SshSig> {
405        SshSig::sign_prehash(self, namespace, hash_alg, prehash)
406    }
407
408    /// Read private key from an OpenSSH-formatted PEM source.
409    ///
410    /// # Errors
411    /// - Returns [`Error::Io`] on I/O errors.
412    /// - Returns [`Error::Encoding`] in the event of an encoding error.
413    #[cfg(feature = "std")]
414    pub fn read_openssh(reader: &mut impl Read) -> Result<Self> {
415        let pem = Zeroizing::new(io::read_to_string(reader)?);
416        Self::from_openssh(&*pem)
417    }
418
419    /// Read private key from an OpenSSH-formatted PEM file.
420    ///
421    /// # Errors
422    /// - Returns [`Error::Io`] on I/O errors.
423    /// - Returns [`Error::Encoding`] in the event of an encoding error.
424    #[cfg(feature = "std")]
425    pub fn read_openssh_file(path: impl AsRef<Path>) -> Result<Self> {
426        // TODO(tarcieri): verify file permissions match `UNIX_FILE_PERMISSIONS`
427        let mut file = File::open(path)?;
428        Self::read_openssh(&mut file)
429    }
430
431    /// Write private key as an OpenSSH-formatted PEM file.
432    ///
433    /// # Errors
434    /// - Returns [`Error::Io`] on I/O errors.
435    /// - Returns [`Error::Encoding`] in the event of an encoding error.
436    #[cfg(feature = "std")]
437    pub fn write_openssh(&self, writer: &mut impl Write, line_ending: LineEnding) -> Result<()> {
438        let pem = self.to_openssh(line_ending)?;
439        writer.write_all(pem.as_bytes())?;
440        Ok(())
441    }
442
443    /// Write private key as an OpenSSH-formatted PEM file.
444    ///
445    /// # Errors
446    /// - Returns [`Error::Io`] on I/O errors.
447    /// - Returns [`Error::Encoding`] in the event of an encoding error.
448    #[cfg(feature = "std")]
449    pub fn write_openssh_file(
450        &self,
451        path: impl AsRef<Path>,
452        line_ending: LineEnding,
453    ) -> Result<()> {
454        let mut options = File::options();
455
456        #[cfg(unix)]
457        options.mode(UNIX_FILE_PERMISSIONS);
458
459        let mut file = options.write(true).create(true).truncate(true).open(path)?;
460
461        self.write_openssh(&mut file, line_ending)
462    }
463
464    /// Attempt to decrypt an encrypted private key using the provided
465    /// password to derive an encryption key.
466    ///
467    /// # Errors
468    /// Returns [`Error::Decrypted`] if the private key is already decrypted.
469    #[cfg(feature = "encryption")]
470    pub fn decrypt(&self, password: impl AsRef<[u8]>) -> Result<Self> {
471        let (key, iv) = self.kdf.derive_key_and_iv(self.cipher, password)?;
472
473        let ciphertext = self.key_data.encrypted().ok_or(Error::Decrypted)?;
474        let mut buffer = Zeroizing::new(ciphertext.to_vec());
475        self.cipher.decrypt(&key, &iv, &mut buffer, self.auth_tag)?;
476
477        #[allow(clippy::arithmetic_side_effects)] // block sizes are constants
478        Self::decode_privatekey_comment_pair(
479            &mut (&**buffer).into_decoder()?,
480            self.public_key.key_data.clone(),
481            self.cipher.block_size(),
482            self.cipher.block_size() - 1,
483        )
484    }
485
486    /// Encrypt an unencrypted private key using the provided password to
487    /// derive an encryption key.
488    ///
489    /// Uses the following algorithms:
490    /// - Cipher: [`Cipher::Aes256Ctr`]
491    /// - KDF: [`Kdf::Bcrypt`] (i.e. `bcrypt-pbkdf`)
492    ///
493    /// # Errors
494    /// Returns [`Error::Encrypted`] if the private key is already encrypted.
495    #[cfg(feature = "encryption")]
496    pub fn encrypt<R: TryCryptoRng + ?Sized>(
497        &self,
498        rng: &mut R,
499        password: impl AsRef<[u8]>,
500    ) -> Result<Self> {
501        self.encrypt_with_cipher(rng, Cipher::Aes256Ctr, password)
502    }
503
504    /// Encrypt an unencrypted private key using the provided password to
505    /// derive an encryption key for the provided [`Cipher`].
506    ///
507    /// # Errors
508    /// Returns [`Error::Encrypted`] if the private key is already encrypted.
509    #[cfg(feature = "encryption")]
510    pub fn encrypt_with_cipher<R: TryCryptoRng + ?Sized>(
511        &self,
512        rng: &mut R,
513        cipher: Cipher,
514        password: impl AsRef<[u8]>,
515    ) -> Result<Self> {
516        let checkint = rng.try_next_u32().map_err(|_| Error::RngFailure)?;
517
518        self.encrypt_with(
519            cipher,
520            Kdf::new(Default::default(), rng)?,
521            checkint,
522            password,
523        )
524    }
525
526    /// Encrypt an unencrypted private key using the provided cipher and KDF
527    /// configuration.
528    ///
529    /// # Errors
530    /// Returns [`Error::Encrypted`] if the private key is already encrypted.
531    #[cfg(feature = "encryption")]
532    pub fn encrypt_with(
533        &self,
534        cipher: Cipher,
535        kdf: Kdf,
536        checkint: u32,
537        password: impl AsRef<[u8]>,
538    ) -> Result<Self> {
539        if self.is_encrypted() {
540            return Err(Error::Encrypted);
541        }
542
543        let (key_bytes, iv_bytes) = kdf.derive_key_and_iv(cipher, password)?;
544        let msg_len = self.encoded_privatekey_comment_pair_len(cipher)?;
545        let mut out = Vec::with_capacity(msg_len);
546
547        // Encode and encrypt private key
548        self.encode_privatekey_comment_pair(&mut out, cipher, checkint)?;
549        let auth_tag = cipher.encrypt(&key_bytes, &iv_bytes, out.as_mut_slice())?;
550
551        Ok(Self {
552            cipher,
553            kdf,
554            checkint: None,
555            public_key: self.public_key.key_data.clone().into(),
556            key_data: KeypairData::Encrypted(out),
557            auth_tag,
558        })
559    }
560
561    /// Get the digital signature [`Algorithm`] used by this key.
562    #[must_use]
563    pub fn algorithm(&self) -> Algorithm {
564        self.public_key.algorithm()
565    }
566
567    /// Comment on the key (e.g. email address).
568    #[cfg(feature = "alloc")]
569    #[must_use]
570    pub fn comment(&self) -> &Comment {
571        self.public_key.comment()
572    }
573
574    /// Cipher algorithm (a.k.a. `ciphername`).
575    #[must_use]
576    pub fn cipher(&self) -> Cipher {
577        self.cipher
578    }
579
580    /// Compute key fingerprint.
581    ///
582    /// Use [`Default::default()`] to use the default hash function (SHA-256).
583    #[cfg(feature = "sha2")]
584    #[must_use]
585    pub fn fingerprint(&self, hash_alg: HashAlg) -> Fingerprint {
586        self.public_key.fingerprint(hash_alg)
587    }
588
589    /// Is this key encrypted?
590    #[must_use]
591    pub fn is_encrypted(&self) -> bool {
592        let ret = self.key_data.is_encrypted();
593        debug_assert_eq!(ret, self.cipher.is_some());
594        ret
595    }
596
597    /// Key Derivation Function (KDF) used to encrypt this key.
598    ///
599    /// Returns [`Kdf::None`] if this key is not encrypted.
600    #[must_use]
601    pub fn kdf(&self) -> &Kdf {
602        &self.kdf
603    }
604
605    /// Keypair data.
606    #[must_use]
607    pub fn key_data(&self) -> &KeypairData {
608        &self.key_data
609    }
610
611    /// Get the [`PublicKey`] which corresponds to this private key.
612    #[must_use]
613    pub fn public_key(&self) -> &PublicKey {
614        &self.public_key
615    }
616
617    /// Generate a random key which uses the given algorithm.
618    ///
619    /// # Errors
620    /// Returns `Error::AlgorithmUnknown` if the algorithm is unsupported.
621    #[cfg(feature = "rand_core")]
622    #[allow(unreachable_code, unused_variables)]
623    pub fn random<R: CryptoRng + ?Sized>(rng: &mut R, algorithm: Algorithm) -> Result<Self> {
624        let checkint = rng.next_u32();
625
626        let key_data = match algorithm {
627            #[cfg(feature = "dsa")]
628            Algorithm::Dsa => KeypairData::from(DsaKeypair::random(rng)?),
629            #[cfg(any(feature = "p256", feature = "p384", feature = "p521"))]
630            Algorithm::Ecdsa { curve } => KeypairData::from(EcdsaKeypair::random(rng, curve)?),
631            #[cfg(feature = "ed25519")]
632            Algorithm::Ed25519 => KeypairData::from(Ed25519Keypair::random(rng)),
633            #[cfg(feature = "rsa")]
634            Algorithm::Rsa { .. } => {
635                KeypairData::from(RsaKeypair::random(rng, DEFAULT_RSA_KEY_SIZE)?)
636            }
637            #[cfg(all(feature = "mldsa", feature = "ed25519"))]
638            Algorithm::MlDsa44Ed25519 => KeypairData::from(MlDsa44Ed25519Keypair::random(rng)?),
639            #[cfg(all(feature = "mldsa", feature = "p384"))]
640            Algorithm::MlDsa87P384 => KeypairData::from(MlDsa87P384Keypair::random(rng)),
641            _ => return Err(Error::AlgorithmUnknown),
642        };
643        let public_key = public::KeyData::try_from(&key_data)?;
644
645        Ok(Self {
646            cipher: Cipher::None,
647            kdf: Kdf::None,
648            checkint: Some(checkint),
649            public_key: public_key.into(),
650            key_data,
651            auth_tag: None,
652        })
653    }
654
655    /// Set the comment on the key.
656    #[cfg(feature = "alloc")]
657    pub fn set_comment(&mut self, comment: impl Into<Comment>) {
658        self.public_key.set_comment(comment);
659    }
660
661    /// Decode [`KeypairData`] along with its associated checkints and comment,
662    /// storing the comment in the provided public key on success.
663    ///
664    /// This method also checks padding for validity and ensures that the
665    /// decoded private key matches the provided public key.
666    ///
667    /// For private key format specification, see OpenSSH [PROTOCOL.key] ยง 3:
668    ///
669    /// ```text
670    /// uint32  checkint
671    /// uint32  checkint
672    /// byte[]  privatekey1
673    /// string  comment1
674    /// byte[]  privatekey2
675    /// string  comment2
676    /// ...
677    /// string  privatekeyN
678    /// string  commentN
679    /// char    1
680    /// char    2
681    /// char    3
682    /// ...
683    /// char    padlen % 255
684    /// ```
685    ///
686    /// [PROTOCOL.key]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.key?annotate=HEAD
687    fn decode_privatekey_comment_pair(
688        reader: &mut Decoder<impl Reader>,
689        public_key: public::KeyData,
690        block_size: usize,
691        max_padding_size: usize,
692    ) -> Result<Self> {
693        debug_assert!(block_size <= MAX_BLOCK_SIZE);
694        debug_assert!(max_padding_size <= MAX_BLOCK_SIZE);
695
696        // Ensure input data is padding-aligned
697        if reader.remaining_len().checked_rem(block_size) != Some(0) {
698            return Err(encoding::Error::Length.into());
699        }
700
701        let checkint1 = u32::decode(reader)?;
702        let checkint2 = u32::decode(reader)?;
703
704        if checkint1 != checkint2 {
705            return Err(Error::Crypto);
706        }
707
708        let key_data = KeypairData::decode(reader)?;
709
710        // Ensure public key matches private key
711        if public_key != public::KeyData::try_from(&key_data)? {
712            return Err(Error::PublicKey);
713        }
714
715        let mut public_key = PublicKey::from(public_key);
716        public_key.decode_comment(reader)?;
717
718        let padding_len = reader.remaining_len();
719
720        if padding_len > max_padding_size {
721            return Err(encoding::Error::Length.into());
722        }
723
724        if padding_len != 0 {
725            let mut padding = [0u8; MAX_BLOCK_SIZE];
726            reader.read(&mut padding[..padding_len])?;
727
728            if PADDING_BYTES[..padding_len] != padding[..padding_len] {
729                return Err(Error::FormatEncoding);
730            }
731        }
732
733        if !reader.is_finished() {
734            return Err(Error::TrailingData {
735                remaining: reader.remaining_len(),
736            });
737        }
738
739        Ok(Self {
740            cipher: Cipher::None,
741            kdf: Kdf::None,
742            checkint: Some(checkint1),
743            public_key,
744            key_data,
745            auth_tag: None,
746        })
747    }
748
749    /// Encode [`KeypairData`] along with its associated checkints, comment,
750    /// and padding.
751    fn encode_privatekey_comment_pair(
752        &self,
753        writer: &mut impl Writer,
754        cipher: Cipher,
755        checkint: u32,
756    ) -> encoding::Result<()> {
757        let unpadded_len = self.unpadded_privatekey_comment_pair_len()?;
758        let padding_len = cipher.padding_len(unpadded_len);
759
760        checkint.encode(writer)?;
761        checkint.encode(writer)?;
762        self.key_data.encode(writer)?;
763
764        // Serialize comment
765        #[cfg(not(feature = "alloc"))]
766        "".encode(writer)?;
767        #[cfg(feature = "alloc")]
768        self.comment().encode(writer)?;
769
770        writer.write(&PADDING_BYTES[..padding_len])?;
771        Ok(())
772    }
773
774    /// Get the length of this private key when encoded with the given comment
775    /// and padded using the padding size for the given cipher.
776    fn encoded_privatekey_comment_pair_len(&self, cipher: Cipher) -> encoding::Result<usize> {
777        let len = self.unpadded_privatekey_comment_pair_len()?;
778        [len, cipher.padding_len(len)].checked_sum()
779    }
780
781    /// Get the length of this private key when encoded with the given comment.
782    ///
783    /// This length is just the checkints, private key data, and comment sans
784    /// any padding.
785    fn unpadded_privatekey_comment_pair_len(&self) -> encoding::Result<usize> {
786        // This method is intended for use with unencrypted keys only
787        debug_assert!(!self.is_encrypted(), "called on encrypted key");
788
789        #[cfg(not(feature = "alloc"))]
790        let comment_len = "".encoded_len()?;
791        #[cfg(feature = "alloc")]
792        let comment_len = self.comment().encoded_len()?;
793
794        [
795            8, // 2 x uint32 checkints,
796            self.key_data.encoded_len()?,
797            comment_len,
798        ]
799        .checked_sum()
800    }
801}
802
803impl CtEq for PrivateKey {
804    fn ct_eq(&self, other: &Self) -> Choice {
805        // Constant-time with respect to private key data
806        self.key_data.ct_eq(&other.key_data)
807            & Choice::from(u8::from(
808                self.cipher == other.cipher
809                    && self.kdf == other.kdf
810                    && self.public_key == other.public_key,
811            ))
812    }
813}
814
815impl Eq for PrivateKey {}
816
817impl PartialEq for PrivateKey {
818    fn eq(&self, other: &Self) -> bool {
819        self.ct_eq(other).into()
820    }
821}
822
823impl Decode for PrivateKey {
824    type Error = Error;
825
826    fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
827        let mut auth_magic = [0u8; Self::AUTH_MAGIC.len()];
828        reader.read(&mut auth_magic)?;
829
830        if auth_magic != Self::AUTH_MAGIC {
831            return Err(Error::FormatEncoding);
832        }
833
834        let cipher = Cipher::decode(reader)?;
835        let kdf = Kdf::decode(reader)?;
836        let nkeys = usize::decode(reader)?;
837
838        // TODO(tarcieri): support more than one key?
839        if nkeys != 1 {
840            return Err(encoding::Error::Length.into());
841        }
842
843        let public_key = reader.read_prefixed(public::KeyData::decode)?;
844
845        // Handle encrypted private key
846        #[cfg(not(feature = "alloc"))]
847        if cipher.is_some() {
848            return Err(Error::Encrypted);
849        }
850        #[cfg(feature = "alloc")]
851        if cipher.is_some() {
852            let ciphertext = Vec::decode(reader)?;
853
854            // Ensure ciphertext is padded to the expected length
855            if ciphertext.len().checked_rem(cipher.block_size()) != Some(0) {
856                return Err(Error::Crypto);
857            }
858
859            let auth_tag = if cipher.has_tag() {
860                let mut tag = Tag::default();
861                reader.read(&mut tag)?;
862                Some(tag)
863            } else {
864                None
865            };
866
867            if !reader.is_finished() {
868                return Err(Error::TrailingData {
869                    remaining: reader.remaining_len(),
870                });
871            }
872
873            return Ok(Self {
874                cipher,
875                kdf,
876                checkint: None,
877                public_key: public_key.into(),
878                key_data: KeypairData::Encrypted(ciphertext),
879                auth_tag,
880            });
881        }
882
883        // Processing unencrypted key. No KDF should be set.
884        if kdf.is_some() {
885            return Err(Error::Crypto);
886        }
887
888        reader.read_prefixed(|reader| {
889            // PuTTYgen uses a non-standard block size of 16
890            // and _always_ adds a padding even if data length
891            // is divisible by 16 - for unencrypted keys
892            // in the OpenSSH format.
893            // We're only relaxing the exact length check, but will
894            // still validate that the contents of the padding area.
895            // In all other cases there can be up to (but not including)
896            // `block_size` padding bytes as per `PROTOCOL.key`.
897            let max_padding_size = match cipher {
898                Cipher::None => 16,
899                #[allow(clippy::arithmetic_side_effects)] // block sizes are constants
900                _ => cipher.block_size() - 1,
901            };
902            Self::decode_privatekey_comment_pair(
903                reader,
904                public_key,
905                cipher.block_size(),
906                max_padding_size,
907            )
908        })
909    }
910}
911
912impl Encode for PrivateKey {
913    fn encoded_len(&self) -> encoding::Result<usize> {
914        let private_key_len = if self.is_encrypted() {
915            self.key_data.encoded_len_prefixed()?
916        } else {
917            [4, self.encoded_privatekey_comment_pair_len(Cipher::None)?].checked_sum()?
918        };
919
920        [
921            Self::AUTH_MAGIC.len(),
922            self.cipher.encoded_len()?,
923            self.kdf.encoded_len()?,
924            4, // number of keys (uint32)
925            self.public_key.key_data().encoded_len_prefixed()?,
926            private_key_len,
927            self.auth_tag.map_or(0, |tag| tag.len()),
928        ]
929        .checked_sum()
930    }
931
932    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
933        writer.write(Self::AUTH_MAGIC)?;
934        self.cipher.encode(writer)?;
935        self.kdf.encode(writer)?;
936
937        // TODO(tarcieri): support for encoding more than one private key
938        1usize.encode(writer)?;
939
940        // Encode public key
941        self.public_key.key_data().encode_prefixed(writer)?;
942
943        // Encode private key
944        if self.is_encrypted() {
945            self.key_data.encode_prefixed(writer)?;
946
947            if let Some(tag) = &self.auth_tag {
948                writer.write(tag)?;
949            }
950        } else {
951            self.encoded_privatekey_comment_pair_len(Cipher::None)?
952                .encode(writer)?;
953
954            let checkint = self.checkint.unwrap_or_else(|| self.key_data.checkint());
955            self.encode_privatekey_comment_pair(writer, Cipher::None, checkint)?;
956        }
957
958        Ok(())
959    }
960}
961
962impl From<PrivateKey> for PublicKey {
963    fn from(private_key: PrivateKey) -> PublicKey {
964        private_key.public_key
965    }
966}
967
968impl From<&PrivateKey> for PublicKey {
969    fn from(private_key: &PrivateKey) -> PublicKey {
970        private_key.public_key.clone()
971    }
972}
973
974impl From<PrivateKey> for public::KeyData {
975    fn from(private_key: PrivateKey) -> public::KeyData {
976        private_key.public_key.key_data
977    }
978}
979
980impl From<&PrivateKey> for public::KeyData {
981    fn from(private_key: &PrivateKey) -> public::KeyData {
982        private_key.public_key.key_data.clone()
983    }
984}
985
986#[cfg(feature = "alloc")]
987impl From<DsaKeypair> for PrivateKey {
988    fn from(keypair: DsaKeypair) -> PrivateKey {
989        KeypairData::from(keypair)
990            .try_into()
991            .expect(CONVERSION_ERROR_MSG)
992    }
993}
994
995#[cfg(feature = "ecdsa")]
996impl From<EcdsaKeypair> for PrivateKey {
997    fn from(keypair: EcdsaKeypair) -> PrivateKey {
998        KeypairData::from(keypair)
999            .try_into()
1000            .expect(CONVERSION_ERROR_MSG)
1001    }
1002}
1003
1004impl From<Ed25519Keypair> for PrivateKey {
1005    fn from(keypair: Ed25519Keypair) -> PrivateKey {
1006        KeypairData::from(keypair)
1007            .try_into()
1008            .expect(CONVERSION_ERROR_MSG)
1009    }
1010}
1011
1012#[cfg(feature = "alloc")]
1013impl From<RsaKeypair> for PrivateKey {
1014    fn from(keypair: RsaKeypair) -> PrivateKey {
1015        KeypairData::from(keypair)
1016            .try_into()
1017            .expect(CONVERSION_ERROR_MSG)
1018    }
1019}
1020
1021#[cfg(all(feature = "mldsa", feature = "ed25519"))]
1022impl From<MlDsa44Ed25519Keypair> for PrivateKey {
1023    fn from(keypair: MlDsa44Ed25519Keypair) -> PrivateKey {
1024        KeypairData::from(keypair)
1025            .try_into()
1026            .expect(CONVERSION_ERROR_MSG)
1027    }
1028}
1029
1030#[cfg(all(feature = "mldsa", feature = "p384"))]
1031impl From<MlDsa87P384Keypair> for PrivateKey {
1032    fn from(keypair: MlDsa87P384Keypair) -> PrivateKey {
1033        KeypairData::from(keypair)
1034            .try_into()
1035            .expect(CONVERSION_ERROR_MSG)
1036    }
1037}
1038
1039#[cfg(all(feature = "alloc", feature = "ecdsa"))]
1040impl From<SkEcdsaSha2NistP256> for PrivateKey {
1041    fn from(keypair: SkEcdsaSha2NistP256) -> PrivateKey {
1042        KeypairData::from(keypair)
1043            .try_into()
1044            .expect(CONVERSION_ERROR_MSG)
1045    }
1046}
1047
1048#[cfg(feature = "alloc")]
1049impl From<SkEd25519> for PrivateKey {
1050    fn from(keypair: SkEd25519) -> PrivateKey {
1051        KeypairData::from(keypair)
1052            .try_into()
1053            .expect(CONVERSION_ERROR_MSG)
1054    }
1055}
1056
1057impl TryFrom<KeypairData> for PrivateKey {
1058    type Error = Error;
1059
1060    fn try_from(key_data: KeypairData) -> Result<PrivateKey> {
1061        let public_key = public::KeyData::try_from(&key_data)?;
1062
1063        Ok(Self {
1064            cipher: Cipher::None,
1065            kdf: Kdf::None,
1066            checkint: None,
1067            public_key: public_key.into(),
1068            key_data,
1069            auth_tag: None,
1070        })
1071    }
1072}
1073
1074impl PemLabel for PrivateKey {
1075    const PEM_LABEL: &'static str = "OPENSSH PRIVATE KEY";
1076}
1077
1078impl str::FromStr for PrivateKey {
1079    type Err = Error;
1080
1081    fn from_str(s: &str) -> Result<Self> {
1082        Self::from_openssh(s)
1083    }
1084}