Skip to main content

SecretKey

Struct SecretKey 

Source
pub struct SecretKey<C: Curve> {
    inner: ScalarValue<C>,
}
Expand description

Elliptic curve secret keys.

This type wraps a secret scalar value, helping to prevent accidental exposure and securely erasing the value from memory when dropped.

§Generating secret keys

SecretKeys can be generated using the Generate trait.

§Parsing PKCS#8 Keys

PKCS#8 is a commonly used format for encoding secret keys (especially ones generated by OpenSSL).

Keys in PKCS#8 format are either binary (ASN.1 BER/DER), or PEM encoded (ASCII) and begin with the following:

-----BEGIN PRIVATE KEY-----

To decode an elliptic curve private key from PKCS#8, enable the pkcs8 feature of this crate (or the pkcs8 feature of a specific RustCrypto elliptic curve crate) and use the DecodePrivateKey trait to parse it.

When the pem feature of this crate (or a specific RustCrypto elliptic curve crate) is enabled, a FromStr impl is also available.

Fields§

§inner: ScalarValue<C>

Scalar value

Implementations§

Source§

impl<C> SecretKey<C>
where C: Curve,

Source

pub const MIN_SIZE: usize = 24

Minimum allowed size of an elliptic curve secret key in bytes.

This provides the equivalent of 96-bits of symmetric security.

Source

pub fn from_scalar(scalar: impl Into<ScalarValue<C>>) -> CtOption<Self>

Create a new secret key from a scalar value.

§Returns

This will return a none if the scalar is all-zero.

Source

pub fn as_scalar_value(&self) -> &ScalarValue<C>

Borrow the inner secret ScalarValue value.

Security Warning

This value is key material. Please treat it with the care it deserves!

Source

pub fn to_nonzero_scalar(&self) -> NonZeroScalar<C>
where C: CurveArithmetic,

Get the secret NonZeroScalar value for this key.

Security Warning

This value is key material. Please treat it with the care it deserves!

Source

pub fn public_key(&self) -> PublicKey<C>
where C: CurveArithmetic,

Get the PublicKey which corresponds to this secret key

Source

pub fn from_bytes(bytes: &FieldBytes<C>) -> Result<Self>

Deserialize secret key from an encoded secret scalar.

§Errors

Returns Error if bytes overflows the scalar modulus.

Source

pub fn from_slice(slice: &[u8]) -> Result<Self>

Deserialize secret key from an encoded secret scalar passed as a byte slice.

The slice is expected to be a minimum of 24-bytes (192-bytes) and at most C::FieldBytesSize bytes in length.

Byte slices shorter than the field size are handled by zero padding the input.

NOTE: this function is variable-time with respect to the input length. To avoid a timing sidechannel, always ensure that the input has been pre-padded to C::FieldBytesSize.

§Errors
  • if slice is shorter than Self::MIN_SIZE.
  • if slice is not sized appropriately for the scalar modulus.
  • if the decoded scalar field element overflows the scalar modulus.
Source

pub fn to_bytes(&self) -> FieldBytes<C>

Serialize raw secret scalar as a big endian integer.

Source

pub fn diffie_hellman(&self, public_key: &PublicKey<C>) -> SharedSecret<C>
where C: CurveArithmetic,

Perform Elliptic Curve Diffie-Hellman with the given public key, returning a shared secret.

See the documentation in the ecdh module for more information.

Source

pub fn from_der(der_bytes: &[u8]) -> DecodeResult<Self>

Decode SecretKey from DER-encoded private key.

§Supported formats
  • PKCS#8: requires pkcs8 feature
  • SEC1: requires sec1 feature

If you are expecting one format over the other, it’s better to use a more specific method:

§Errors
Source

pub fn from_pem(pem: &str) -> DecodeResult<Self>

Decode SecretKey from PEM-encoded private key.

If you are expecting one format over the other, it’s better to use a more specific method:

§Errors
Source

pub fn from_sec1_der(der_bytes: &[u8]) -> DecodeResult<Self>

Deserialize secret key encoded in the SEC1 ASN.1 DER ECPrivateKey format.

§Errors
  • if der_bytes does not encode a valid SEC1 private key
  • if the contained document does not encode a valid key for this curve
Source

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

Serialize secret key in the SEC1 ASN.1 DER ECPrivateKey format.

§Errors

If an internal error occurs encoding this key.

Source

pub fn from_sec1_pem(s: &str) -> DecodeResult<Self>

Parse SecretKey from PEM-encoded SEC1 ECPrivateKey format.

PEM-encoded SEC1 keys can be identified by the leading delimiter:

-----BEGIN EC PRIVATE KEY-----
§Errors
  • if the document cannot be decoded as PEM
  • if the PEM document does not encode a valid private key for this curve
Source

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

Serialize private key as self-zeroizing PEM-encoded SEC1 ECPrivateKey with the given pem::LineEnding.

Pass Default::default() to use the OS’s native line endings.

§Errors

If an internal error occurs encoding this key.

Source

pub fn random<R: CryptoRng + ?Sized>(rng: &mut R) -> Self

👎Deprecated since 0.14.0: use the Generate trait instead

Deprecated: Generate a random SecretKey.

Trait Implementations§

Source§

impl<C> AssociatedAlgorithmIdentifier for SecretKey<C>
where C: AssociatedOid + Curve,

Source§

const ALGORITHM_IDENTIFIER: AlgorithmIdentifier<ObjectIdentifier>

AlgorithmIdentifier for this structure.
Source§

type Params = ObjectIdentifier

Algorithm parameters.
Source§

impl<C: Clone + Curve> Clone for SecretKey<C>

Source§

fn clone(&self) -> SecretKey<C>

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<C> ConstantTimeEq for SecretKey<C>
where C: Curve,

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<C> Debug for SecretKey<C>
where C: Curve,

Source§

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

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

impl<C> DecodeEcPrivateKey for SecretKey<C>

Available on crate feature sec1 only.
Source§

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

Deserialize SEC1 private key from ASN.1 DER-encoded data (binary format).
Source§

fn from_sec1_pem(s: &str) -> Result<Self, Error>

Deserialize SEC1-encoded private key from PEM. Read more
Source§

fn read_sec1_der_file(path: impl AsRef<Path>) -> Result<Self, Error>

Load SEC1 private key from an ASN.1 DER-encoded file on the local filesystem (binary format).
Source§

fn read_sec1_pem_file(path: impl AsRef<Path>) -> Result<Self, Error>

Load SEC1 private key from a PEM-encoded file on the local filesystem.
Source§

impl<C> Drop for SecretKey<C>
where C: Curve,

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<C> EncodeEcPrivateKey for SecretKey<C>

Available on crate features alloc and arithmetic and sec1 only.
Source§

fn to_sec1_der(&self) -> Result<SecretDocument>

Serialize a SecretDocument containing a SEC1-encoded private key.
Source§

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

Serialize this private key as PEM-encoded SEC1 with the given LineEnding. Read more
Source§

fn write_sec1_der_file(&self, path: impl AsRef<Path>) -> Result<(), Error>

Write ASN.1 DER-encoded SEC1 private key to the given path.
Source§

fn write_sec1_pem_file( &self, path: impl AsRef<Path>, line_ending: LineEnding, ) -> Result<(), Error>

Write ASN.1 PEM-encoded SEC1 private key to the given path.
Source§

impl<C> EncodePrivateKey for SecretKey<C>

Available on crate features alloc and arithmetic only.
Source§

fn to_pkcs8_der(&self) -> Result<SecretDocument>

Serialize a SecretDocument containing a PKCS#8-encoded private key. Read more
Source§

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

Serialize this private key as PEM-encoded PKCS#8 with the given LineEnding. Read more
Source§

fn write_pkcs8_der_file(&self, path: impl AsRef<Path>) -> Result<(), Error>

Write ASN.1 DER-encoded PKCS#8 private key to the given path. Read more
Source§

fn write_pkcs8_pem_file( &self, path: impl AsRef<Path>, line_ending: LineEnding, ) -> Result<(), Error>

Write ASN.1 PEM-encoded PKCS#8 private key to the given path. Read more
Source§

impl<C> From<&NonZeroScalar<C>> for SecretKey<C>
where C: CurveArithmetic,

Available on crate feature arithmetic only.
Source§

fn from(scalar: &NonZeroScalar<C>) -> SecretKey<C>

Converts to this type from the input type.
Source§

impl<C> From<&SecretKey<C>> for NonZeroScalar<C>
where C: CurveArithmetic,

Source§

fn from(sk: &SecretKey<C>) -> NonZeroScalar<C>

Converts to this type from the input type.
Source§

impl<C> From<&SecretKey<C>> for PublicKey<C>
where C: CurveArithmetic,

Source§

fn from(secret_key: &SecretKey<C>) -> PublicKey<C>

Converts to this type from the input type.
Source§

impl<C> From<NonZeroScalar<C>> for SecretKey<C>
where C: CurveArithmetic,

Available on crate feature arithmetic only.
Source§

fn from(scalar: NonZeroScalar<C>) -> SecretKey<C>

Converts to this type from the input type.
Source§

impl<C> From<SecretKey<C>> for NonZeroScalar<C>
where C: CurveArithmetic,

Source§

fn from(sk: SecretKey<C>) -> NonZeroScalar<C>

Converts to this type from the input type.
Source§

impl<C> From<SecretKey<C>> for PublicKey<C>
where C: CurveArithmetic,

Source§

fn from(secret_key: SecretKey<C>) -> Self

Converts to this type from the input type.
Source§

impl<C> FromStr for SecretKey<C>

Available on crate feature pem only.
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<C> Generate for SecretKey<C>
where C: Curve,

Source§

fn try_generate_from_rng<R: TryCryptoRng + ?Sized>( rng: &mut R, ) -> Result<Self, R::Error>

Generate random key using the provided TryCryptoRng. Read more
Source§

fn generate_from_rng<R>(rng: &mut R) -> Self
where R: CryptoRng + ?Sized,

Generate random key using the provided CryptoRng.
Source§

fn try_generate() -> Result<Self, Error>

Randomly generate a value of this type using the system’s ambient cryptographically secure random number generator. Read more
Source§

fn generate() -> Self

Randomly generate a value of this type using the system’s ambient cryptographically secure random number generator. Read more
Source§

impl<C> KeySizeUser for SecretKey<C>
where C: Curve,

Source§

type KeySize = <C as Curve>::FieldBytesSize

Key size in bytes.
Source§

fn key_size() -> usize

Return key size in bytes.
Source§

impl<C> PartialEq for SecretKey<C>
where C: Curve,

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<C> TryFrom<EcPrivateKey<'_>> for SecretKey<C>

Available on crate feature sec1 only.
Source§

type Error = Error

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

fn try_from(sec1_private_key: EcPrivateKey<'_>) -> Result<Self>

Performs the conversion.
Source§

impl<C> TryFrom<PrivateKeyInfo<AnyRef<'_>, &OctetStringRef, BitStringRef<'_>>> for SecretKey<C>

Source§

type Error = Error

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

fn try_from(private_key_info: PrivateKeyInfoRef<'_>) -> Result<Self>

Performs the conversion.
Source§

impl<C> TryKeyInit for SecretKey<C>
where C: Curve,

Source§

fn new(key_bytes: &FieldBytes<C>) -> Result<Self, InvalidKey>

Create new value from a fixed-size key. Read more
Source§

fn new_from_slice(key: &[u8]) -> Result<Self, InvalidKey>

Create new value from a variable size key. Read more
Source§

impl<C: Curve> Eq for SecretKey<C>

Source§

impl<C> ZeroizeOnDrop for SecretKey<C>
where C: Curve,

Auto Trait Implementations§

§

impl<C> Freeze for SecretKey<C>
where <C as Curve>::Uint: Freeze,

§

impl<C> RefUnwindSafe for SecretKey<C>
where <C as Curve>::Uint: RefUnwindSafe,

§

impl<C> Send for SecretKey<C>

§

impl<C> Sync for SecretKey<C>

§

impl<C> Unpin for SecretKey<C>
where <C as Curve>::Uint: Unpin,

§

impl<C> UnsafeUnpin for SecretKey<C>
where <C as Curve>::Uint: UnsafeUnpin,

§

impl<C> UnwindSafe for SecretKey<C>
where <C as Curve>::Uint: UnwindSafe,

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> DecodePrivateKey for T
where T: for<'a> TryFrom<PrivateKeyInfo<AnyRef<'a>, &'a OctetStringRef, BitStringRef<'a>>, Error = Error>,

Source§

fn from_pkcs8_der(bytes: &[u8]) -> Result<T, Error>

Deserialize PKCS#8 private key from ASN.1 DER-encoded data (binary format). Read more
Source§

fn from_pkcs8_pem(s: &str) -> Result<Self, Error>

Deserialize PKCS#8-encoded private key from PEM. Read more
Source§

fn read_pkcs8_der_file(path: impl AsRef<Path>) -> Result<Self, Error>

Load PKCS#8 private key from an ASN.1 DER-encoded file (binary format) on the local filesystem. Read more
Source§

fn read_pkcs8_pem_file(path: impl AsRef<Path>) -> Result<Self, Error>

Load PKCS#8 private key from a PEM-encoded file on the local filesystem. Read more
Source§

impl<T> DynAssociatedAlgorithmIdentifier for T

Source§

fn algorithm_identifier(&self) -> Result<AlgorithmIdentifier<Any>, Error>

AlgorithmIdentifier for this structure. Read more
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<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.