PrivateKey

Struct PrivateKey 

Source
pub struct PrivateKey { /* private fields */ }
Expand description

SSH private key.

Implementations§

Source§

impl PrivateKey

Source

pub fn new(key_data: KeypairData, comment: impl Into<String>) -> Result<Self>

Available on crate feature alloc only.

Create a new unencrypted private key with the given keypair data and comment.

On no_std platforms, use PrivateKey::from(key_data) instead.

Source

pub fn from_openssh(pem: impl AsRef<[u8]>) -> Result<Self>

Parse an OpenSSH-formatted PEM private key.

OpenSSH-formatted private keys begin with the following:

-----BEGIN OPENSSH PRIVATE KEY-----
Source

pub fn from_bytes(bytes: &[u8]) -> Result<Self>

Parse a raw binary SSH private key.

Source

pub fn encode_openssh<'o>( &self, line_ending: LineEnding, out: &'o mut [u8], ) -> Result<&'o str>

Encode OpenSSH-formatted (PEM) private key.

Source

pub fn to_openssh(&self, line_ending: LineEnding) -> Result<Zeroizing<String>>

Available on crate feature alloc only.

Encode an OpenSSH-formatted PEM private key, allocating a self-zeroizing String for the result.

Source

pub fn to_bytes(&self) -> Result<Zeroizing<Vec<u8>>>

Available on crate feature alloc only.

Serialize SSH private key as raw bytes.

Source

pub fn sign( &self, namespace: &str, hash_alg: HashAlg, msg: &[u8], ) -> Result<SshSig>

Available on crate feature alloc only.

Sign the given message using this private key, returning an SshSig.

These signatures can be produced using ssh-keygen -Y sign. They’re encoded as PEM and begin with the following:

-----BEGIN SSH SIGNATURE-----

See PROTOCOL.sshsig for more information.

§Usage

See also: PublicKey::verify.

use ssh_key::{PrivateKey, HashAlg, SshSig};

// Message to be signed.
let message = b"testing";

// Example domain/namespace used for the message.
let namespace = "example";

// Private key to use when computing the signature.
// WARNING: don't actually hardcode private keys in source code!!!
let encoded_private_key = r#"
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACCzPq7zfqLffKoBDe/eo04kH2XxtSmk9D7RQyf1xUqrYgAAAJgAIAxdACAM
XQAAAAtzc2gtZWQyNTUxOQAAACCzPq7zfqLffKoBDe/eo04kH2XxtSmk9D7RQyf1xUqrYg
AAAEC2BsIi0QwW2uFscKTUUXNHLsYX4FxlaSDSblbAj7WR7bM+rvN+ot98qgEN796jTiQf
ZfG1KaT0PtFDJ/XFSqtiAAAAEHVzZXJAZXhhbXBsZS5jb20BAgMEBQ==
-----END OPENSSH PRIVATE KEY-----
"#;

let private_key = encoded_private_key.parse::<PrivateKey>()?;
let signature = private_key.sign(namespace, HashAlg::default(), message)?;
// assert!(private_key.public_key().verify(namespace, message, &signature).is_ok());
Source

pub fn read_openssh_file(path: &Path) -> Result<Self>

Available on crate feature std only.

Read private key from an OpenSSH-formatted PEM file.

Source

pub fn write_openssh_file( &self, path: &Path, line_ending: LineEnding, ) -> Result<()>

Available on crate feature std only.

Write private key as an OpenSSH-formatted PEM file.

Source

pub fn algorithm(&self) -> Algorithm

Get the digital signature Algorithm used by this key.

Source

pub fn comment(&self) -> &str

Comment on the key (e.g. email address).

Source

pub fn cipher(&self) -> Cipher

Cipher algorithm (a.k.a. ciphername).

Source

pub fn fingerprint(&self, hash_alg: HashAlg) -> Fingerprint

Compute key fingerprint.

Use Default::default() to use the default hash function (SHA-256).

Source

pub fn is_encrypted(&self) -> bool

Is this key encrypted?

Source

pub fn kdf(&self) -> &Kdf

Key Derivation Function (KDF) used to encrypt this key.

Returns Kdf::None if this key is not encrypted.

Source

pub fn key_data(&self) -> &KeypairData

Keypair data.

Source

pub fn public_key(&self) -> &PublicKey

Get the PublicKey which corresponds to this private key.

Source

pub fn random( rng: &mut impl CryptoRngCore, algorithm: Algorithm, ) -> Result<Self>

Available on crate feature rand_core only.

Generate a random key which uses the given algorithm.

§Returns
  • Error::AlgorithmUnknown if the algorithm is unsupported.
Source

pub fn set_comment(&mut self, comment: impl Into<String>)

Available on crate feature alloc only.

Set the comment on the key.

Trait Implementations§

Source§

impl Clone for PrivateKey

Source§

fn clone(&self) -> PrivateKey

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl ConstantTimeEq for PrivateKey

Source§

fn ct_eq(&self, other: &Self) -> Choice

Determine if two items are equal. Read more
Source§

fn ct_ne(&self, other: &Self) -> Choice

Determine if two items are NOT equal. Read more
Source§

impl Debug for PrivateKey

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Decode for PrivateKey

Source§

type Error = Error

Type returned in the event of a decoding error.
Source§

fn decode(reader: &mut impl Reader) -> Result<Self>

Attempt to decode a value of this type using the provided Reader.
Source§

impl Encode for PrivateKey

Source§

fn encoded_len(&self) -> Result<usize>

Get the length of this type encoded in bytes, prior to Base64 encoding.
Source§

fn encode(&self, writer: &mut impl Writer) -> Result<()>

Encode this value using the provided Writer.
Source§

fn encoded_len_prefixed(&self) -> Result<usize, Error>

Return the length of this type after encoding when prepended with a uint32 length prefix.
Source§

fn encode_prefixed(&self, writer: &mut impl Writer) -> Result<(), Error>

Encode this value, first prepending a uint32 length prefix set to Encode::encoded_len.
Source§

impl From<&PrivateKey> for KeyData

Source§

fn from(private_key: &PrivateKey) -> KeyData

Converts to this type from the input type.
Source§

impl From<&PrivateKey> for PublicKey

Source§

fn from(private_key: &PrivateKey) -> PublicKey

Converts to this type from the input type.
Source§

impl From<DsaKeypair> for PrivateKey

Available on crate feature alloc only.
Source§

fn from(keypair: DsaKeypair) -> PrivateKey

Converts to this type from the input type.
Source§

impl From<EcdsaKeypair> for PrivateKey

Available on crate feature ecdsa only.
Source§

fn from(keypair: EcdsaKeypair) -> PrivateKey

Converts to this type from the input type.
Source§

impl From<Ed25519Keypair> for PrivateKey

Source§

fn from(keypair: Ed25519Keypair) -> PrivateKey

Converts to this type from the input type.
Source§

impl From<PrivateKey> for KeyData

Source§

fn from(private_key: PrivateKey) -> KeyData

Converts to this type from the input type.
Source§

impl From<PrivateKey> for PublicKey

Source§

fn from(private_key: PrivateKey) -> PublicKey

Converts to this type from the input type.
Source§

impl From<RsaKeypair> for PrivateKey

Available on crate feature alloc only.
Source§

fn from(keypair: RsaKeypair) -> PrivateKey

Converts to this type from the input type.
Source§

impl From<SkEcdsaSha2NistP256> for PrivateKey

Available on crate features alloc and ecdsa only.
Source§

fn from(keypair: SkEcdsaSha2NistP256) -> PrivateKey

Converts to this type from the input type.
Source§

impl From<SkEd25519> for PrivateKey

Available on crate feature alloc only.
Source§

fn from(keypair: SkEd25519) -> PrivateKey

Converts to this type from the input type.
Source§

impl FromStr for PrivateKey

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self>

Parses a string s to return a value of this type. Read more
Source§

impl PartialEq for PrivateKey

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PemLabel for PrivateKey

Source§

const PEM_LABEL: &'static str = "OPENSSH PRIVATE KEY"

Expected PEM type label for a given document, e.g. "PRIVATE KEY"
Source§

fn validate_pem_label(actual: &str) -> Result<(), Error>

Validate that a given label matches the expected label.
Source§

impl Signer<Signature> for PrivateKey

Available on crate feature alloc only.
Source§

fn try_sign(&self, message: &[u8]) -> Result<Signature>

Attempt to sign the given message, returning a digital signature on success, or an error if something went wrong. Read more
Source§

fn sign(&self, msg: &[u8]) -> S

Sign the given message and return a digital signature
Source§

impl TryFrom<KeypairData> for PrivateKey

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(key_data: KeypairData) -> Result<PrivateKey>

Performs the conversion.
Source§

impl Eq for PrivateKey

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DecodePem for T
where T: Decode + PemLabel,

Source§

fn decode_pem(pem: impl AsRef<[u8]>) -> Result<T, <T as Decode>::Error>

Decode the provided PEM-encoded string, interpreting the Base64-encoded body of the document using the Decode trait.
Source§

impl<T> EncodePem for T
where T: Encode + PemLabel,

Source§

fn encode_pem<'o>( &self, line_ending: LineEnding, out: &'o mut [u8], ) -> Result<&'o str, Error>

Encode this type using the Encode trait, writing the resulting PEM document into the provided out buffer.
Source§

fn encode_pem_string(&self, line_ending: LineEnding) -> Result<String, Error>

Encode this type using the Encode trait, writing the resulting PEM document to a returned String.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<S, T> SignerMut<S> for T
where T: Signer<S>,

Source§

fn try_sign(&mut self, msg: &[u8]) -> Result<S, Error>

Attempt to sign the given message, updating the state, and returning a digital signature on success, or an error if something went wrong. Read more
Source§

fn sign(&mut self, msg: &[u8]) -> S

Sign the given message, update the state, and return a digital signature.
Source§

impl<T> SigningKey for T
where T: Signer<Signature>, KeyData: for<'a> From<&'a T>,

Source§

fn public_key(&self) -> KeyData

Available on crate feature alloc only.
Get the public::KeyData for this signing key.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.

Layout§

Note: Most layout information is completely unstable and may even differ between compilations. The only exception is types with certain repr(...) attributes. Please see the Rust Reference's “Type Layout” chapter for details on type layout guarantees.

Size: 424 bytes