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>
impl<T: HasParams> Pkey<T>
Sourcepub unsafe fn from_ptr(ptr: *mut EVP_PKEY) -> Self
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.
Sourcepub fn security_bits(&self) -> u32
pub fn security_bits(&self) -> u32
Security strength in bits (e.g. 128 for P-256, 112 for RSA-2048).
Sourcepub fn is_a(&self, name: &CStr) -> bool
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?
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}Sourcepub fn public_eq<U: HasPublic>(&self, other: &Pkey<U>) -> boolwhere
T: HasPublic,
pub fn public_eq<U: HasPublic>(&self, other: &Pkey<U>) -> boolwhere
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?
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}Sourcepub fn get_params(&self, params: &mut Params<'_>) -> Result<(), ErrorStack>
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
Sourcepub fn public_key_to_der(&self) -> Result<Vec<u8>, ErrorStack>where
T: HasPublic,
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>
impl Pkey<Private>
Sourcepub fn from_pem(pem: &[u8]) -> Result<Self, ErrorStack>
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
Sourcepub fn to_pem(&self) -> Result<Vec<u8>, ErrorStack>
pub fn to_pem(&self) -> Result<Vec<u8>, ErrorStack>
Serialise the private key to PEM (PKCS#8 BEGIN PRIVATE KEY).
§Errors
Sourcepub fn from_pem_in(ctx: &Arc<LibCtx>, pem: &[u8]) -> Result<Self, ErrorStack>
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
Sourcepub fn from_der(der: &[u8]) -> Result<Self, ErrorStack>
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
Sourcepub fn from_pem_passphrase(
pem: &[u8],
passphrase: &[u8],
) -> Result<Self, ErrorStack>
pub fn from_pem_passphrase( pem: &[u8], passphrase: &[u8], ) -> Result<Self, ErrorStack>
Sourcepub fn to_pem_encrypted(
&self,
cipher: &CipherAlg,
passphrase: &[u8],
) -> Result<Vec<u8>, ErrorStack>
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
Sourcepub fn to_pkcs8_der(&self) -> Result<Vec<u8>, ErrorStack>
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>
impl Pkey<Public>
Sourcepub fn from_pem(pem: &[u8]) -> Result<Self, ErrorStack>
pub fn from_pem(pem: &[u8]) -> Result<Self, ErrorStack>
Load a public key from PEM (SubjectPublicKeyInfo or RSA public key).
§Errors
Sourcepub fn from_pem_in(ctx: &Arc<LibCtx>, pem: &[u8]) -> Result<Self, ErrorStack>
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§impl Pkey<Private>
impl Pkey<Private>
Sourcepub fn from_params(
ctx: Option<&Arc<LibCtx>>,
pkey_type: &CStr,
params: &Params<'_>,
) -> Result<Self, ErrorStack>
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§impl Pkey<Public>
impl Pkey<Public>
Sourcepub fn from_params(
ctx: Option<&Arc<LibCtx>>,
pkey_type: &CStr,
params: &Params<'_>,
) -> Result<Self, ErrorStack>
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.