Skip to main content

Pkey

Struct Pkey 

Source
pub struct Pkey<T> { /* private fields */ }
Expand description

An asymmetric key (EVP_PKEY*) with a compile-time role marker.

Cloneable via EVP_PKEY_up_ref; wrapping in Arc<Pkey<T>> is safe.

Implementations§

Source§

impl<T: HasParams> Pkey<T>

Source

pub unsafe fn from_ptr(ptr: *mut EVP_PKEY) -> Self

Construct from a raw (owned) EVP_PKEY*.

§Safety

ptr must be a valid, non-null EVP_PKEY* that the caller is giving up ownership of.

Source

pub fn as_ptr(&self) -> *mut EVP_PKEY

Raw EVP_PKEY* pointer valid for the lifetime of self.

Source

pub fn bits(&self) -> u32

Size of the key in bits (e.g. 256 for P-256, 2048 for RSA-2048).

Source

pub fn security_bits(&self) -> u32

Security strength in bits (e.g. 128 for P-256, 112 for RSA-2048).

Source

pub fn is_a(&self, name: &CStr) -> bool

Return true if this key is of the named algorithm (e.g. c"EC", c"RSA").

Examples found in repository?
examples/pkcs12.rs (line 44)
9fn main() -> Result<(), Box<dyn std::error::Error>> {
10    // ── Generate key and self-signed certificate ───────────────────────────────
11
12    let mut kgen = KeygenCtx::new(c"ED25519")?;
13    let priv_key = kgen.generate()?;
14    let pub_key = native_ossl::pkey::Pkey::<native_ossl::pkey::Public>::from(priv_key.clone());
15
16    let mut name = X509NameOwned::new()?;
17    name.add_entry_by_txt(c"CN", b"example.com")?;
18
19    let cert = X509Builder::new()?
20        .set_version(2)?
21        .set_serial_number(1)?
22        .set_not_before_offset(0)?
23        .set_not_after_offset(365 * 86400)?
24        .set_subject_name(&name)?
25        .set_issuer_name(&name)?
26        .set_public_key(&pub_key)?
27        .sign(&priv_key, None)?
28        .build();
29
30    // ── Create the PKCS#12 bundle ─────────────────────────────────────────────
31
32    let password = "correct horse battery staple";
33    let p12 = Pkcs12::create(password, "example.com", &priv_key, &cert, &[])?;
34    let der = p12.to_der()?;
35    println!("PKCS#12 bundle: {} bytes", der.len());
36
37    // ── Parse it back ─────────────────────────────────────────────────────────
38
39    let loaded = Pkcs12::from_der(&der)?;
40    let (recovered_key, recovered_cert, ca_chain) = loaded.parse(password)?;
41
42    println!(
43        "Recovered key algorithm: Ed25519 = {}",
44        recovered_key.is_a(c"ED25519")
45    );
46    if let Some(subject) = recovered_cert.subject_name().to_string() {
47        println!("Recovered cert subject:  {subject}");
48    }
49    println!("CA chain length: {}", ca_chain.len());
50
51    // Public keys must match.
52    assert!(priv_key.public_eq(&recovered_key));
53    assert_eq!(cert.to_der()?, recovered_cert.to_der()?);
54    println!("Key and certificate match original: OK");
55
56    // ── DER round-trip ────────────────────────────────────────────────────────
57
58    let der2 = loaded.to_der()?;
59    assert_eq!(der, der2);
60    println!("DER round-trip: OK");
61
62    Ok(())
63}
Source

pub fn public_eq<U: HasPublic>(&self, other: &Pkey<U>) -> bool
where T: HasPublic,

Return true if this key’s public component equals other’s.

Wraps EVP_PKEY_eq. Useful for verifying that a certificate’s public key matches a private key before using them together.

Examples found in repository?
examples/pkcs12.rs (line 52)
9fn main() -> Result<(), Box<dyn std::error::Error>> {
10    // ── Generate key and self-signed certificate ───────────────────────────────
11
12    let mut kgen = KeygenCtx::new(c"ED25519")?;
13    let priv_key = kgen.generate()?;
14    let pub_key = native_ossl::pkey::Pkey::<native_ossl::pkey::Public>::from(priv_key.clone());
15
16    let mut name = X509NameOwned::new()?;
17    name.add_entry_by_txt(c"CN", b"example.com")?;
18
19    let cert = X509Builder::new()?
20        .set_version(2)?
21        .set_serial_number(1)?
22        .set_not_before_offset(0)?
23        .set_not_after_offset(365 * 86400)?
24        .set_subject_name(&name)?
25        .set_issuer_name(&name)?
26        .set_public_key(&pub_key)?
27        .sign(&priv_key, None)?
28        .build();
29
30    // ── Create the PKCS#12 bundle ─────────────────────────────────────────────
31
32    let password = "correct horse battery staple";
33    let p12 = Pkcs12::create(password, "example.com", &priv_key, &cert, &[])?;
34    let der = p12.to_der()?;
35    println!("PKCS#12 bundle: {} bytes", der.len());
36
37    // ── Parse it back ─────────────────────────────────────────────────────────
38
39    let loaded = Pkcs12::from_der(&der)?;
40    let (recovered_key, recovered_cert, ca_chain) = loaded.parse(password)?;
41
42    println!(
43        "Recovered key algorithm: Ed25519 = {}",
44        recovered_key.is_a(c"ED25519")
45    );
46    if let Some(subject) = recovered_cert.subject_name().to_string() {
47        println!("Recovered cert subject:  {subject}");
48    }
49    println!("CA chain length: {}", ca_chain.len());
50
51    // Public keys must match.
52    assert!(priv_key.public_eq(&recovered_key));
53    assert_eq!(cert.to_der()?, recovered_cert.to_der()?);
54    println!("Key and certificate match original: OK");
55
56    // ── DER round-trip ────────────────────────────────────────────────────────
57
58    let der2 = loaded.to_der()?;
59    assert_eq!(der, der2);
60    println!("DER round-trip: OK");
61
62    Ok(())
63}
Source

pub fn get_params(&self, params: &mut Params<'_>) -> Result<(), ErrorStack>

Fill the values for a pre-prepared mutable Params query array.

Wraps EVP_PKEY_get_params. The array must already contain the keys of interest with null data pointers; OpenSSL writes the values in place.

§Errors
Source

pub fn public_key_to_der(&self) -> Result<Vec<u8>, ErrorStack>
where T: HasPublic,

DER-encode the public key (SubjectPublicKeyInfo format).

Zero-copy: writes directly into a caller-owned Vec<u8> — no OpenSSL heap allocation occurs.

§Errors

Returns Err if serialisation fails.

Source§

impl Pkey<Private>

Source

pub fn from_pem(pem: &[u8]) -> Result<Self, ErrorStack>

Load a private key from PEM bytes.

Pass passphrase = Some(cb) for encrypted PEM; None for unencrypted.

§Errors
Source

pub fn to_pem(&self) -> Result<Vec<u8>, ErrorStack>

Serialise the private key to PEM (PKCS#8 BEGIN PRIVATE KEY).

§Errors
Source

pub fn from_pem_in(ctx: &Arc<LibCtx>, pem: &[u8]) -> Result<Self, ErrorStack>

Load a private key from PEM bytes within a specific library context.

Uses PEM_read_bio_PrivateKey_ex so the key’s internal algorithm fetch uses ctx’s provider set. Necessary when the private key is later used for EVP operations inside an isolated (e.g. FIPS) context.

§Errors
Source

pub fn from_der(der: &[u8]) -> Result<Self, ErrorStack>

Load a private key from DER bytes (auto-detecting PKCS#8 / traditional).

Zero-copy: the EVP_PKEY is decoded from the caller’s slice without copying.

§Errors
Source

pub fn from_pem_passphrase( pem: &[u8], passphrase: &[u8], ) -> Result<Self, ErrorStack>

Load a private key from passphrase-encrypted PEM.

Passes passphrase directly to PEM_read_bio_PrivateKey via a pem_password_cb. Returns Err if the key cannot be decrypted or the PEM is malformed. For unencrypted PEM use from_pem.

§Errors
Source

pub fn to_pem_encrypted( &self, cipher: &CipherAlg, passphrase: &[u8], ) -> Result<Vec<u8>, ErrorStack>

Serialise the private key as passphrase-encrypted PKCS#8 PEM (BEGIN ENCRYPTED PRIVATE KEY).

cipher controls the wrapping algorithm (e.g. CipherAlg::fetch(c"AES-256-CBC", None)). The passphrase is passed directly to OpenSSL via kstr/klen.

§Panics

Panics if passphrase is longer than i32::MAX bytes.

§Errors
Source

pub fn to_pkcs8_der(&self) -> Result<Vec<u8>, ErrorStack>

Serialise the private key as unencrypted PKCS#8 DER (PrivateKeyInfo / OneAsymmetricKey, RFC 5958).

Equivalent to writing unencrypted PEM and stripping the base64 wrapper, but avoids the encode/decode round-trip. To encrypt the output, use to_pem_encrypted instead.

§Errors
Source§

impl Pkey<Public>

Source

pub fn from_pem(pem: &[u8]) -> Result<Self, ErrorStack>

Load a public key from PEM (SubjectPublicKeyInfo or RSA public key).

§Errors
Source

pub fn from_pem_in(ctx: &Arc<LibCtx>, pem: &[u8]) -> Result<Self, ErrorStack>

Load a public key from PEM bytes within a specific library context.

Uses PEM_read_bio_PUBKEY_ex so the key’s internal algorithm fetch uses ctx’s provider set. Necessary when the public key is later used for EVP operations inside an isolated (e.g. FIPS) context.

§Errors
Source

pub fn from_der(der: &[u8]) -> Result<Self, ErrorStack>

Load a public key from DER (SubjectPublicKeyInfo).

§Errors
Source

pub fn to_pem(&self) -> Result<Vec<u8>, ErrorStack>

Serialise the public key to PEM.

§Errors
Source§

impl Pkey<Private>

Source

pub fn from_params( ctx: Option<&Arc<LibCtx>>, pkey_type: &CStr, params: &Params<'_>, ) -> Result<Self, ErrorStack>

Import a private key pair from an OSSL_PARAM array.

Equivalent to EVP_PKEY_fromdata with EVP_PKEY_KEYPAIR selection. Pass ctx = None to use the global default library context.

§Errors
Source

pub fn export(&self) -> Result<Params<'static>, ErrorStack>

Export all key parameters (private + public) as an owned OSSL_PARAM array.

Uses EVP_PKEY_KEYPAIR selection so both private and public material are included in the returned array.

§Errors
Source§

impl Pkey<Public>

Source

pub fn from_params( ctx: Option<&Arc<LibCtx>>, pkey_type: &CStr, params: &Params<'_>, ) -> Result<Self, ErrorStack>

Import a public key from an OSSL_PARAM array.

Equivalent to EVP_PKEY_fromdata with EVP_PKEY_PUBLIC_KEY selection. Pass ctx = None to use the global default library context.

§Errors
Source

pub fn export(&self) -> Result<Params<'static>, ErrorStack>

Export the public key parameters as an owned OSSL_PARAM array.

Uses EVP_PKEY_PUBLIC_KEY selection.

§Errors

Trait Implementations§

Source§

impl<T> Clone for Pkey<T>

Source§

fn clone(&self) -> Self

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<T> Drop for Pkey<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl From<Pkey<Private>> for Pkey<Public>

Source§

fn from(k: Pkey<Private>) -> Self

Converts to this type from the input type.
Source§

impl<T> Send for Pkey<T>

Source§

impl<T> Sync for Pkey<T>

Auto Trait Implementations§

§

impl<T> Freeze for Pkey<T>

§

impl<T> RefUnwindSafe for Pkey<T>
where T: RefUnwindSafe,

§

impl<T> Unpin for Pkey<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for Pkey<T>

§

impl<T> UnwindSafe for Pkey<T>
where T: 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> 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> 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.