Struct ssh_key::private::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 decrypt(&self, password: impl AsRef<[u8]>) -> Result<Self>

Available on crate feature encryption only.

Attempt to decrypt an encrypted private key using the provided password to derive an encryption key.

Returns Error::Decrypted if the private key is already decrypted.

source

pub fn encrypt( &self, rng: &mut impl CryptoRngCore, password: impl AsRef<[u8]> ) -> Result<Self>

Available on crate feature encryption only.

Encrypt an unencrypted private key using the provided password to derive an encryption key.

Uses the following algorithms:

Returns Error::Encrypted if the private key is already encrypted.

source

pub fn encrypt_with_cipher( &self, rng: &mut impl CryptoRngCore, cipher: Cipher, password: impl AsRef<[u8]> ) -> Result<Self>

Available on crate feature encryption only.

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.

source

pub fn encrypt_with( &self, cipher: Cipher, kdf: Kdf, checkint: u32, password: impl AsRef<[u8]> ) -> Result<Self>

Available on crate feature encryption only.

Encrypt an unencrypted private key using the provided cipher and KDF configuration.

Returns Error::Encrypted if the private key is already encrypted.

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 copy 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

§

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

§

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method 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

§

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> 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>

Available on crate feature alloc only.
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

§

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,

§

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>,

§

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>,

§

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.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V