1#![cfg_attr(feature = "encryption", doc = " ```")]
14#![cfg_attr(not(feature = "encryption"), doc = " ```ignore")]
15#![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#![cfg_attr(all(feature = "ed25519", feature = "getrandom"), doc = " ```")]
83#![cfg_attr(
84 not(all(feature = "ed25519", feature = "getrandom")),
85 doc = " ```ignore"
86)]
87#[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
174const CONVERSION_ERROR_MSG: &str = "SSH private key conversion error";
176
177#[cfg(all(feature = "rand_core", feature = "rsa"))]
179const DEFAULT_RSA_KEY_SIZE: usize = 4096;
180
181const MAX_BLOCK_SIZE: usize = 16;
185
186const PADDING_BYTES: [u8; MAX_BLOCK_SIZE] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
188
189#[cfg(all(unix, feature = "std"))]
191const UNIX_FILE_PERMISSIONS: u32 = 0o600;
192
193#[derive(Clone, Debug)]
195pub struct PrivateKey {
196 cipher: Cipher,
198
199 kdf: Kdf,
201
202 checkint: Option<u32>,
204
205 public_key: PublicKey,
207
208 key_data: KeypairData,
210
211 auth_tag: Option<Tag>,
213}
214
215impl PrivateKey {
216 const AUTH_MAGIC: &'static [u8] = b"openssh-key-v1\0";
218
219 #[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 pub fn from_openssh(pem: impl AsRef<[u8]>) -> Result<Self> {
247 Self::decode_pem(pem)
248 }
249
250 #[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 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 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 #[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 #[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 #[cfg_attr(feature = "ed25519", doc = "```")]
335 #[cfg_attr(not(feature = "ed25519"), doc = "```ignore")]
336 #[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 #[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 #[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 #[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 #[cfg(feature = "std")]
425 pub fn read_openssh_file(path: impl AsRef<Path>) -> Result<Self> {
426 let mut file = File::open(path)?;
428 Self::read_openssh(&mut file)
429 }
430
431 #[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 #[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 #[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)] 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 #[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 #[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 #[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 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 #[must_use]
563 pub fn algorithm(&self) -> Algorithm {
564 self.public_key.algorithm()
565 }
566
567 #[cfg(feature = "alloc")]
569 #[must_use]
570 pub fn comment(&self) -> &Comment {
571 self.public_key.comment()
572 }
573
574 #[must_use]
576 pub fn cipher(&self) -> Cipher {
577 self.cipher
578 }
579
580 #[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 #[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 #[must_use]
601 pub fn kdf(&self) -> &Kdf {
602 &self.kdf
603 }
604
605 #[must_use]
607 pub fn key_data(&self) -> &KeypairData {
608 &self.key_data
609 }
610
611 #[must_use]
613 pub fn public_key(&self) -> &PublicKey {
614 &self.public_key
615 }
616
617 #[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 #[cfg(feature = "alloc")]
657 pub fn set_comment(&mut self, comment: impl Into<Comment>) {
658 self.public_key.set_comment(comment);
659 }
660
661 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 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 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 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 #[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 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 fn unpadded_privatekey_comment_pair_len(&self) -> encoding::Result<usize> {
786 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, 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 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 if nkeys != 1 {
840 return Err(encoding::Error::Length.into());
841 }
842
843 let public_key = reader.read_prefixed(public::KeyData::decode)?;
844
845 #[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 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 if kdf.is_some() {
885 return Err(Error::Crypto);
886 }
887
888 reader.read_prefixed(|reader| {
889 let max_padding_size = match cipher {
898 Cipher::None => 16,
899 #[allow(clippy::arithmetic_side_effects)] _ => 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, 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 1usize.encode(writer)?;
939
940 self.public_key.key_data().encode_prefixed(writer)?;
942
943 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}