Struct sequoia_openpgp::cert::ValidCert

source ·
pub struct ValidCert<'a> { /* private fields */ }
Expand description

A Cert plus a Policy and a reference time.

A ValidCert combines a Cert with a Policy and a reference time. This allows it to implement methods that require a Policy and a reference time without requiring the caller to explicitly pass them in. Embedding them in the ValidCert data structure rather than having the caller pass them in explicitly helps ensure that multipart operations, even those that span multiple functions, use the same Policy and reference time. This avoids a subtle class of bugs in which different views of a certificate are unintentionally used.

A ValidCert is typically obtained by transforming a Cert using Cert::with_policy.

A ValidCert is guaranteed to have a valid and live binding signature at the specified reference time. Note: this only means that the binding signature is live; it says nothing about whether the certificate or any component is live. If you care about those things, then you need to check them separately.

§Examples

use sequoia_openpgp as openpgp;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let vc = cert.with_policy(p, None)?;

Implementations§

source§

impl<'a> ValidCert<'a>

source

pub fn cert(&self) -> &'a Cert

Returns the underlying certificate.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let vc = cert.with_policy(p, None)?;
assert!(std::ptr::eq(vc.cert(), &cert));
source

pub fn time(&self) -> SystemTime

Returns the associated reference time.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let t = UNIX_EPOCH + Duration::from_secs(1307732220);
let vc = cert.with_policy(p, t)?;
assert_eq!(vc.time(), t);
source

pub fn policy(&self) -> &'a dyn Policy

Returns the associated policy.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let vc = cert.with_policy(p, None)?;
assert!(std::ptr::eq(vc.policy(), p));
source

pub fn with_policy<T>( self, policy: &'a dyn Policy, time: T, ) -> Result<ValidCert<'a>>
where T: Into<Option<SystemTime>>,

Changes the associated policy and reference time.

If time is None, the current time is used.

Returns an error if the certificate is not valid for the given policy at the specified time.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::policy::{StandardPolicy, NullPolicy};

let sp = &StandardPolicy::new();
let np = &NullPolicy::new();

let vc = cert.with_policy(sp, None)?;

// ...

// Now with a different policy.
let vc = vc.with_policy(np, None)?;
source

pub fn direct_key_signature(&self) -> Result<&'a Signature>

Returns the certificate’s direct key signature as of the reference time.

Subpackets on direct key signatures apply to all components of the certificate, cf. Section 5.2.3.3 of RFC 4880.

§Examples
use sequoia_openpgp as openpgp;
use sequoia_openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let vc = cert.with_policy(p, None)?;
println!("{:?}", vc.direct_key_signature());
source

pub fn revocation_status(&self) -> RevocationStatus<'a>

Returns the certificate’s revocation status.

A certificate is considered revoked at time t if:

  • There is a valid and live revocation at time t that is newer than all valid and live self signatures at time t, or

  • There is a valid hard revocation (even if it is not live at time t, and even if there is a newer self signature).

Note: certificates and subkeys have different revocation criteria from User IDs and User Attributes.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::types::RevocationStatus;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let (cert, rev) =
    CertBuilder::general_purpose(None, Some("alice@example.org"))
    .generate()?;

// Not revoked.
assert_eq!(cert.with_policy(p, None)?.revocation_status(),
           RevocationStatus::NotAsFarAsWeKnow);

// Merge the revocation certificate.  `cert` is now considered
// to be revoked.
let cert = cert.insert_packets(rev.clone())?;
assert_eq!(cert.with_policy(p, None)?.revocation_status(),
           RevocationStatus::Revoked(vec![&rev.into()]));
source

pub fn alive(&self) -> Result<()>

Returns whether or not the certificate is alive at the reference time.

A certificate is considered to be alive at time t if the primary key is alive at time t.

A valid certificate’s primary key is guaranteed to have a live binding signature, however, that does not mean that the primary key is necessarily alive.

§Examples
use std::time;
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let a_second = time::Duration::from_secs(1);

let creation_time = time::SystemTime::now();
let before_creation = creation_time - a_second;
let validity_period = 60 * a_second;
let expiration_time = creation_time + validity_period;
let before_expiration_time = expiration_time - a_second;
let after_expiration_time = expiration_time + a_second;

let (cert, _) = CertBuilder::new()
    .add_userid("Alice")
    .set_creation_time(creation_time)
    .set_validity_period(validity_period)
    .generate()?;

// There is no binding signature before the certificate was created.
assert!(cert.with_policy(p, before_creation).is_err());
assert!(cert.with_policy(p, creation_time)?.alive().is_ok());
assert!(cert.with_policy(p, before_expiration_time)?.alive().is_ok());
// The binding signature is still alive, but the key has expired.
assert!(cert.with_policy(p, expiration_time)?.alive().is_err());
assert!(cert.with_policy(p, after_expiration_time)?.alive().is_err());
source

pub fn primary_key(&self) -> ValidPrimaryKeyAmalgamation<'a, PublicParts>

Returns the certificate’s primary key.

A key’s secret key material may be protected with a password. In such cases, it needs to be decrypted before it can be used to decrypt data or generate a signature. Refer to Key::decrypt_secret for details.

§Examples
let primary = vc.primary_key();
// The certificate's fingerprint *is* the primary key's fingerprint.
assert_eq!(vc.fingerprint(), primary.fingerprint());
source

pub fn keys(&self) -> ValidKeyAmalgamationIter<'a, PublicParts, UnspecifiedRole>

Returns an iterator over the certificate’s valid keys.

That is, this returns an iterator over the primary key and any subkeys.

The iterator always returns the primary key first. The order of the subkeys is undefined.

To only iterate over the certificate’s subkeys, call ValidKeyAmalgamationIter::subkeys on the returned iterator instead of skipping the first key: this causes the iterator to return values with a more accurate type.

A key’s secret key material may be protected with a password. In such cases, it needs to be decrypted before it can be used to decrypt data or generate a signature. Refer to Key::decrypt_secret for details.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

// Create a key with two subkeys: one for signing and one for
// encrypting data in transit.
let (cert, _) = CertBuilder::new()
    .add_userid("Alice")
    .add_signing_subkey()
    .add_transport_encryption_subkey()
    .generate()?;
// They should all be valid.
assert_eq!(cert.with_policy(p, None)?.keys().count(), 1 + 2);
source

pub fn primary_userid(&self) -> Result<ValidUserIDAmalgamation<'a>>

Returns the primary User ID at the reference time, if any.

A certificate may not have a primary User ID if it doesn’t have any valid User IDs. If a certificate has at least one valid User ID at time t, then it has a primary User ID at time t.

The primary User ID is determined as follows:

  • Discard User IDs that are not valid or not alive at time t.

  • Order the remaining User IDs by whether a User ID does not have a valid self-revocation (i.e., non-revoked first, ignoring third-party revocations).

  • Break ties by ordering by whether the User ID is marked as being the primary User ID.

  • Break ties by ordering by the binding signature’s creation time, most recent first.

If there are multiple User IDs that are ordered first, then one is chosen in a deterministic, but undefined manner (currently, we order the value of the User IDs lexographically, but you shouldn’t rely on this).

§Examples
use std::time;
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::packet::prelude::*;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let t1 = time::SystemTime::now();
let t2 = t1 + time::Duration::from_secs(1);

let (cert, _) = CertBuilder::new()
    .set_creation_time(t1)
    .add_userid("Alice")
    .generate()?;
let mut signer = cert
    .primary_key().key().clone().parts_into_secret()?.into_keypair()?;

// There is only one User ID.  It must be the primary User ID.
let vc = cert.with_policy(p, t1)?;
let alice = vc.primary_userid().unwrap();
assert_eq!(alice.value(), b"Alice");
// By default, the primary User ID flag is set.
assert!(alice.binding_signature().primary_userid().is_some());

let template: signature::SignatureBuilder
    = alice.binding_signature().clone().into();

// Add another user id whose creation time is after the
// existing User ID, and doesn't have the User ID set.
let sig = template.clone()
    .set_signature_creation_time(t2)?
    .set_primary_userid(false)?;
let bob: UserID = "Bob".into();
let sig = bob.bind(&mut signer, &cert, sig)?;
let cert = cert.insert_packets(vec![Packet::from(bob), sig.into()])?;

// Alice should still be the primary User ID, because it has the
// primary User ID flag set.
let alice = cert.with_policy(p, t2)?.primary_userid().unwrap();
assert_eq!(alice.value(), b"Alice");


// Add another User ID, whose binding signature's creation
// time is after Alice's and also has the primary User ID flag set.
let sig = template.clone()
   .set_signature_creation_time(t2)?;
let carol: UserID = "Carol".into();
let sig = carol.bind(&mut signer, &cert, sig)?;
let cert = cert.insert_packets(vec![Packet::from(carol), sig.into()])?;

// It should now be the primary User ID, because it is the
// newest User ID with the primary User ID bit is set.
let carol = cert.with_policy(p, t2)?.primary_userid().unwrap();
assert_eq!(carol.value(), b"Carol");
source

pub fn userids(&self) -> ValidUserIDAmalgamationIter<'a>

Returns an iterator over the certificate’s valid User IDs.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::packet::prelude::*;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

// `cert` was created at t0.  Add a second User ID at t1.
let userid = UserID::from("alice@example.com");
// Use the primary User ID's current binding signature as the
// basis for the new User ID's binding signature.
let template : signature::SignatureBuilder
    = cert.with_policy(p, None)?
          .primary_userid()?
          .binding_signature()
          .clone()
          .into();
let sig = template.set_signature_creation_time(t1)?;
let mut signer = cert
    .primary_key().key().clone().parts_into_secret()?.into_keypair()?;
let binding = userid.bind(&mut signer, &cert, sig)?;
// Merge it.
let cert = cert.insert_packets(
    vec![Packet::from(userid), binding.into()])?;

// At t0, the new User ID is not yet valid (it doesn't have a
// binding signature that is live at t0).  Thus, it is not
// returned.
let vc = cert.with_policy(p, t0)?;
assert_eq!(vc.userids().count(), 1);
// But, at t1, we see both User IDs.
let vc = cert.with_policy(p, t1)?;
assert_eq!(vc.userids().count(), 2);
source

pub fn primary_user_attribute( &self, ) -> Result<ValidComponentAmalgamation<'a, UserAttribute>>

Returns the primary User Attribute, if any.

If a certificate has any valid User Attributes, then it has a primary User Attribute. In other words, it will not have a primary User Attribute at time t if there are no valid User Attributes at time t.

The primary User Attribute is determined in the same way as the primary User ID. See the documentation of ValidCert::primary_userid for details.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let vc = cert.with_policy(p, None)?;
let ua = vc.primary_user_attribute();
source

pub fn user_attributes(&self) -> ValidUserAttributeAmalgamationIter<'a>

Returns an iterator over the certificate’s valid UserAttributes.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

// Add a User Attribute without a self-signature to the certificate.
let cert = cert.insert_packets(ua)?;
assert_eq!(cert.user_attributes().count(), 1);

// Without a self-signature, it is definitely not valid.
let vc = cert.with_policy(p, None)?;
assert_eq!(vc.user_attributes().count(), 0);
source

pub fn revocation_keys<P>( &self, policy: P, ) -> Box<dyn Iterator<Item = &'a RevocationKey> + 'a>
where P: Into<Option<&'a dyn Policy>>,

Returns a list of any designated revokers for this certificate.

This function returns the designated revokers listed on the primary key’s binding signatures and the certificate’s direct key signatures.

Note: the returned list is deduplicated.

In order to preserve our API during the 1.x series, this function takes an optional policy argument. It should be None, but if it is Some(_), it will be used instead of the ValidCert’s policy. This makes the function signature compatible with Cert::revocation_keys.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::policy::StandardPolicy;
use openpgp::types::RevocationKey;

let p = &StandardPolicy::new();

let (alice, _) =
    CertBuilder::general_purpose(None, Some("alice@example.org"))
    .generate()?;
// Make Alice a designated revoker for Bob.
let (bob, _) =
    CertBuilder::general_purpose(None, Some("bob@example.org"))
    .set_revocation_keys(vec![(&alice).into()])
    .generate()?;

// Make sure Alice is listed as a designated revoker for Bob.
assert_eq!(bob.with_policy(p, None)?.revocation_keys(None)
           .collect::<Vec<&RevocationKey>>(),
           vec![&(&alice).into()]);

Methods from Deref<Target = Cert>§

source

pub fn primary_key(&self) -> PrimaryKeyAmalgamation<'_, PublicParts>

Returns the primary key.

Unlike getting the certificate’s primary key using the Cert::keys method, this method does not erase the key’s role.

A key’s secret key material may be protected with a password. In such cases, it needs to be decrypted before it can be used to decrypt data or generate a signature. Refer to Key::decrypt_secret for details.

§Examples

The first key returned by Cert::keys is the primary key, but its role has been erased:

assert_eq!(cert.primary_key().key().role_as_unspecified(),
           cert.keys().nth(0).unwrap().key());
source

pub fn revocation_status<T>( &self, policy: &dyn Policy, t: T, ) -> RevocationStatus<'_>
where T: Into<Option<SystemTime>>,

Returns the certificate’s revocation status.

Normally, methods that take a policy and a reference time are only provided by ValidCert. This method is provided here because there are two revocation criteria, and one of them is independent of the reference time. That is, even if it is not possible to turn a Cert into a ValidCert at time t, it may still be considered revoked at time t.

A certificate is considered revoked at time t if:

  • There is a valid and live revocation at time t that is newer than all valid and live self signatures at time t, or

  • There is a valid hard revocation (even if it is not live at time t, and even if there is a newer self signature).

Note: certificates and subkeys have different revocation criteria from User IDs and User Attributes.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::types::RevocationStatus;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let (cert, rev) =
    CertBuilder::general_purpose(None, Some("alice@example.org"))
    .generate()?;

assert_eq!(cert.revocation_status(p, None), RevocationStatus::NotAsFarAsWeKnow);

// Merge the revocation certificate.  `cert` is now considered
// to be revoked.
let cert = cert.insert_packets(rev.clone())?;
assert_eq!(cert.revocation_status(p, None),
           RevocationStatus::Revoked(vec![&rev.into()]));
source

pub fn revoke( &self, primary_signer: &mut dyn Signer, code: ReasonForRevocation, reason: &[u8], ) -> Result<Signature>

Generates a revocation certificate.

This is a convenience function around CertRevocationBuilder to generate a revocation certificate. To use the revocation certificate, merge it into the certificate using Cert::insert_packets.

If you want to revoke an individual component, use SubkeyRevocationBuilder, UserIDRevocationBuilder, or UserAttributeRevocationBuilder, as appropriate.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::types::{ReasonForRevocation, RevocationStatus, SignatureType};
use openpgp::cert::prelude::*;
use openpgp::crypto::KeyPair;
use openpgp::parse::Parse;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let (cert, rev) = CertBuilder::new()
    .set_cipher_suite(CipherSuite::Cv25519)
    .generate()?;

// A new certificate is not revoked.
assert_eq!(cert.revocation_status(p, None),
           RevocationStatus::NotAsFarAsWeKnow);

// The default revocation certificate is a generic
// revocation.
assert_eq!(rev.reason_for_revocation().unwrap().0,
           ReasonForRevocation::Unspecified);

// Create a revocation to explain what *really* happened.
let mut keypair = cert.primary_key()
    .key().clone().parts_into_secret()?.into_keypair()?;
let rev = cert.revoke(&mut keypair,
                      ReasonForRevocation::KeyCompromised,
                      b"It was the maid :/")?;
let cert = cert.insert_packets(rev)?;
if let RevocationStatus::Revoked(revs) = cert.revocation_status(p, None) {
    assert_eq!(revs.len(), 1);
    let rev = revs[0];

    assert_eq!(rev.typ(), SignatureType::KeyRevocation);
    assert_eq!(rev.reason_for_revocation(),
               Some((ReasonForRevocation::KeyCompromised,
                     "It was the maid :/".as_bytes())));
} else {
    unreachable!()
}
source

pub fn set_expiration_time<T>( &self, policy: &dyn Policy, t: T, primary_signer: &mut dyn Signer, expiration: Option<SystemTime>, ) -> Result<Vec<Signature>>
where T: Into<Option<SystemTime>>,

Sets the certificate to expire at the specified time.

If no time (None) is specified, then the certificate is set to not expire.

This function creates new binding signatures that cause the certificate to expire at the specified time. Specifically, it updates the current binding signature on each of the valid, non-revoked User IDs, and the direct key signature, if any. This is necessary, because the primary User ID is first consulted when determining the certificate’s expiration time, and certificates can be distributed with a possibly empty subset of User IDs.

A policy is needed, because the expiration is updated by updating the current binding signatures.

§Examples
use std::time;
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::crypto::KeyPair;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

// The certificate is alive (not expired).
assert!(cert.with_policy(p, None)?.alive().is_ok());

// Make cert expire now.
let mut keypair = cert.primary_key()
    .key().clone().parts_into_secret()?.into_keypair()?;
let sigs = cert.set_expiration_time(p, None, &mut keypair,
                                    Some(time::SystemTime::now()))?;

let cert = cert.insert_packets(sigs)?;
assert!(cert.with_policy(p, None)?.alive().is_err());
source

pub fn userids(&self) -> UserIDAmalgamationIter<'_>

Returns an iterator over the certificate’s User IDs.

Note: This returns all User IDs, even those without a binding signature. This is not what you want, unless you are doing a low-level inspection of the certificate. Use ValidCert::userids instead. (You turn a Cert into a ValidCert by using Cert::with_policy.)

§Examples
println!("{}'s User IDs:", cert.fingerprint());
for ua in cert.userids() {
    println!("  {}", String::from_utf8_lossy(ua.value()));
}
source

pub fn user_attributes(&self) -> UserAttributeAmalgamationIter<'_>

Returns an iterator over the certificate’s User Attributes.

Note: This returns all User Attributes, even those without a binding signature. This is not what you want, unless you are doing a low-level inspection of the certificate. Use ValidCert::user_attributes instead. (You turn a Cert into a ValidCert by using Cert::with_policy.)

§Examples
println!("{}'s has {} User Attributes.",
         cert.fingerprint(),
         cert.user_attributes().count());
source

pub fn keys(&self) -> KeyAmalgamationIter<'_, PublicParts, UnspecifiedRole>

Returns an iterator over the certificate’s keys.

That is, this returns an iterator over the primary key and any subkeys.

Note: This returns all keys, even those without a binding signature. This is not what you want, unless you are doing a low-level inspection of the certificate. Use ValidCert::keys instead. (You turn a Cert into a ValidCert by using Cert::with_policy.)

By necessity, this function erases the returned keys’ roles. If you are only interested in the primary key, use Cert::primary_key. If you are only interested in the subkeys, use KeyAmalgamationIter::subkeys. These functions preserve the keys’ role in the type system.

A key’s secret key material may be protected with a password. In such cases, it needs to be decrypted before it can be used to decrypt data or generate a signature. Refer to Key::decrypt_secret for details.

§Examples
println!("{}'s has {} keys.",
         cert.fingerprint(),
         cert.keys().count());
source

pub fn unknowns(&self) -> UnknownComponentAmalgamationIter<'_>

Returns an iterator over the certificate’s unknown components.

This function returns all unknown components even those without a binding signature.

§Examples
println!("{}'s has {} unknown components.",
         cert.fingerprint(),
         cert.unknowns().count());
for ua in cert.unknowns() {
    println!("  Unknown component with tag {} ({}), error: {}",
             ua.tag(), u8::from(ua.tag()), ua.error());
}
source

pub fn bad_signatures(&self) -> impl Iterator<Item = &Signature> + Send + Sync

Returns the bad signatures.

Bad signatures are signatures and revocations that we could not associate with one of the certificate’s components.

For self signatures and self revocations, we check that the signature is correct. For third-party signatures and third-party revocations, we only check that the digest prefix is correct, because third-party keys are not available. Checking the digest prefix is not an integrity check; third party-signatures and third-party revocations may be invalid and must still be checked for validity before use.

§Examples
println!("{}'s has {} bad signatures.",
         cert.fingerprint(),
         cert.bad_signatures().count());
source

pub fn revocation_keys<'a>( &'a self, policy: &dyn Policy, ) -> Box<dyn Iterator<Item = &'a RevocationKey> + 'a>

Returns a list of any designated revokers for this certificate.

This function returns the designated revokers listed on the primary key’s binding signatures and the certificate’s direct key signatures.

Note: the returned list is deduplicated.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::policy::StandardPolicy;
use openpgp::types::RevocationKey;

let p = &StandardPolicy::new();

let (alice, _) =
    CertBuilder::general_purpose(None, Some("alice@example.org"))
    .generate()?;
// Make Alice a designated revoker for Bob.
let (bob, _) =
    CertBuilder::general_purpose(None, Some("bob@example.org"))
    .set_revocation_keys(vec![(&alice).into()])
    .generate()?;

// Make sure Alice is listed as a designated revoker for Bob.
assert_eq!(bob.revocation_keys(p).collect::<Vec<&RevocationKey>>(),
           vec![&(&alice).into()]);
source

pub fn key_handle(&self) -> KeyHandle

Returns the certificate’s fingerprint as a KeyHandle.

§Examples
println!("{}", cert.key_handle());

// This always returns a fingerprint.
match cert.key_handle() {
    KeyHandle::Fingerprint(_) => (),
    KeyHandle::KeyID(_) => unreachable!(),
}
source

pub fn fingerprint(&self) -> Fingerprint

Returns the certificate’s fingerprint.

§Examples
println!("{}", cert.fingerprint());
source

pub fn keyid(&self) -> KeyID

Returns the certificate’s Key ID.

As a general rule of thumb, you should prefer the fingerprint as it is possible to create keys with a colliding Key ID using a birthday attack.

§Examples
println!("{}", cert.keyid());
source

pub fn is_tsk(&self) -> bool

Returns whether at least one of the keys includes secret key material.

This returns true if either the primary key or at least one of the subkeys includes secret key material.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::policy::StandardPolicy;
use openpgp::serialize::Serialize;
use openpgp::parse::Parse;

let p = &StandardPolicy::new();

// Create a new key.
let (cert, _) =
      CertBuilder::general_purpose(None, Some("alice@example.org"))
      .generate()?;
assert!(cert.is_tsk());

// If we serialize the certificate, the secret key material is
// stripped, unless we first convert it to a TSK.

let mut buffer = Vec::new();
cert.as_tsk().serialize(&mut buffer);
let cert = Cert::from_bytes(&buffer)?;
assert!(cert.is_tsk());

// Now round trip it without first converting it to a TSK.  This
// drops the secret key material.
let mut buffer = Vec::new();
cert.serialize(&mut buffer);
let cert = Cert::from_bytes(&buffer)?;
assert!(!cert.is_tsk());
source

pub fn with_policy<'a, T>( &'a self, policy: &'a dyn Policy, time: T, ) -> Result<ValidCert<'a>>
where T: Into<Option<SystemTime>>,

Associates a policy and a reference time with the certificate.

This is used to turn a Cert into a ValidCert. (See also ValidateAmalgamation, which does the same for component amalgamations.)

A certificate is considered valid if:

  • It has a self signature that is live at time t.

  • The policy considers it acceptable.

This doesn’t say anything about whether the certificate itself is alive (see ValidCert::alive) or revoked (see ValidCert::revocation_status).

§Examples
use sequoia_openpgp as openpgp;
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let vc = cert.with_policy(p, None)?;
source

pub fn exportable(&self) -> bool

Returns whether the certificate should be exported.

A certificate should only be exported if it has at least one exportable direct key signature, or there is at least one user ID with at least one exportable self signature.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;

// By default, certificates are exportable.
let (cert, _) =
    CertBuilder::general_purpose(None, Some("alice@example.org"))
        .generate()?;
assert!(cert.exportable());

// Setting the exportable flag to false makes them
// not-exportable.
let (cert, _) =
    CertBuilder::general_purpose(None, Some("alice@example.org"))
        .set_exportable(false)
        .generate()?;
assert!(! cert.exportable());
source

pub fn as_tsk(&self) -> TSK<'_>

Derive a TSK object from this key.

This object writes out secret keys during serialization.

source

pub fn armor_headers(&self) -> Vec<String>

Creates descriptive armor headers.

Returns armor headers that describe this Cert. The Cert’s primary fingerprint and valid userids (according to the default policy) are included as comments, so that it is easier to identify the Cert when looking at the armored data.

source

pub fn armored(&self) -> impl Serialize + SerializeInto + '_

Wraps this Cert in an armor structure when serialized.

Derives an object from this Cert that adds an armor structure to the serialized Cert when it is serialized. Additionally, the Cert’s User IDs are added as comments, so that it is easier to identify the Cert when looking at the armored data.

§Examples
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::serialize::SerializeInto;

let (cert, _) =
    CertBuilder::general_purpose(None, Some("Mr. Pink ☮☮☮"))
    .generate()?;
let armored = String::from_utf8(cert.armored().to_vec()?)?;

assert!(armored.starts_with("-----BEGIN PGP PUBLIC KEY BLOCK-----"));
assert!(armored.contains("Mr. Pink ☮☮☮"));

Trait Implementations§

source§

impl<'a> Clone for ValidCert<'a>

source§

fn clone(&self) -> ValidCert<'a>

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<'a> Debug for ValidCert<'a>

source§

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

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

impl<'a> Display for ValidCert<'a>

source§

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

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

impl<'a> Preferences<'a> for ValidCert<'a>

source§

fn preferred_symmetric_algorithms(&self) -> Option<&'a [SymmetricAlgorithm]>

Returns the supported symmetric algorithms ordered by preference. Read more
source§

fn preferred_hash_algorithms(&self) -> Option<&'a [HashAlgorithm]>

Returns the supported hash algorithms ordered by preference. Read more
source§

fn preferred_compression_algorithms(&self) -> Option<&'a [CompressionAlgorithm]>

Returns the supported compression algorithms ordered by preference. Read more
source§

fn preferred_aead_algorithms(&self) -> Option<&'a [AEADAlgorithm]>

👎Deprecated
Returns the supported AEAD algorithms ordered by preference. Read more
source§

fn key_server_preferences(&self) -> Option<KeyServerPreferences>

Returns the certificate holder’s keyserver preferences.
source§

fn preferred_key_server(&self) -> Option<&'a [u8]>

Returns the certificate holder’s preferred keyserver for updates.
source§

fn policy_uri(&self) -> Option<&'a [u8]>

Returns the URI of a document describing the policy the certificate was issued under.
source§

fn features(&self) -> Option<Features>

Returns the certificate holder’s feature set.
source§

impl<'a> Deref for ValidCert<'a>

§

type Target = Cert

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.

Auto Trait Implementations§

§

impl<'a> Freeze for ValidCert<'a>

§

impl<'a> !RefUnwindSafe for ValidCert<'a>

§

impl<'a> Send for ValidCert<'a>

§

impl<'a> Sync for ValidCert<'a>

§

impl<'a> Unpin for ValidCert<'a>

§

impl<'a> !UnwindSafe for ValidCert<'a>

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§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> DynClone for T
where T: Clone,

source§

fn __clone_box(&self, _: Private) -> *mut ()

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<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> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. 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<T> ErasedDestructor for T
where T: 'static,

source§

impl<T> MaybeSendSync for T