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 max_output_size(&self) -> usize
pub fn max_output_size(&self) -> usize
Maximum output size in bytes for this key’s primary operation.
For signing keys (RSA, ECDSA, Ed25519) this is the maximum signature length. For encryption keys (RSA-OAEP) this is the maximum ciphertext length. Use this to size output buffers before calling signing or encryption operations.
Returns 0 if the key does not support a size query.
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.
Sourcepub fn default_digest_name(&self) -> Result<Option<String>, ErrorStack>where
T: HasPublic,
pub fn default_digest_name(&self) -> Result<Option<String>, ErrorStack>where
T: HasPublic,
Returns the default digest algorithm name for this key, or None if the
key type mandates no external digest (e.g. Ed25519, ML-DSA).
Wraps EVP_PKEY_get_default_digest_name. The function returns 1 when the
digest is optional and 2 when it is mandatory; both are treated as success.
When the key’s algorithm performs its own internal hashing (Ed25519, ML-DSA,
SLH-DSA), OpenSSL writes "none" or an empty string — both map to Ok(None).
Callers should check this before deciding whether to pass a digest to
DigestSign / DigestVerify: if default_digest_name() returns None,
pass digest: None in SignInit; otherwise pass the returned name.
§Errors
Returns Err if OpenSSL cannot determine the digest.
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_der_in(ctx: &Arc<LibCtx>, der: &[u8]) -> Result<Self, ErrorStack>
pub fn from_der_in(ctx: &Arc<LibCtx>, der: &[u8]) -> Result<Self, ErrorStack>
Load a private key from DER bytes using an explicit library context.
The key format is detected automatically (PKCS#8, traditional, etc.).
Wraps d2i_AutoPrivateKey_ex — unlike from_der (which uses a
BIO), this function passes the raw byte pointer directly to OpenSSL so that
the key’s internal algorithm fetch is bound to ctx’s provider set. Use
this when the loaded key will be used for EVP operations inside an isolated
(e.g. FIPS) context.
§Errors
Returns Err if the DER bytes are malformed or the algorithm is not
available in ctx.
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
Sourcepub fn from_der(der: &[u8]) -> Result<Self, ErrorStack>
pub fn from_der(der: &[u8]) -> Result<Self, ErrorStack>
Load a public key from DER (SubjectPublicKeyInfo).
§Errors
Sourcepub fn from_der_in(ctx: &Arc<LibCtx>, der: &[u8]) -> Result<Self, ErrorStack>
pub fn from_der_in(ctx: &Arc<LibCtx>, der: &[u8]) -> Result<Self, ErrorStack>
Load a SubjectPublicKeyInfo DER public key using an explicit library context.
Wraps d2i_PUBKEY_ex — unlike from_der (which uses a
BIO), this function passes the raw byte pointer directly so that the
key’s internal algorithm fetch is bound to ctx’s provider set. Use
this when the loaded key will be used for EVP operations inside an isolated
(e.g. FIPS) context.
§Errors
Returns Err if the DER bytes are malformed or the algorithm is not
available in ctx.
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.
§Errors
Source§impl<T: HasPrivate> Pkey<T>
impl<T: HasPrivate> Pkey<T>
Sourcepub fn to_der_legacy(&self) -> Result<Vec<u8>, ErrorStack>
pub fn to_der_legacy(&self) -> Result<Vec<u8>, ErrorStack>
Encode this private key to legacy raw-key DER (not PKCS#8).
Wraps i2d_PrivateKey. The output is the algorithm-specific raw key
structure (e.g. RSAPrivateKey / RFC 3447 for RSA, ECPrivateKey /
RFC 5915 for EC) — not the PrivateKeyInfo / PKCS#8 wrapper.
Use this for interoperability with software that requires the legacy
format. For new code prefer to_pkcs8_der
(PKCS#8 / RFC 5958), which is algorithm-agnostic and more widely supported
by modern toolkits.
§Errors
Returns Err if serialisation fails (e.g. the algorithm does not support
legacy DER export, such as some post-quantum algorithms).