[][src]Struct sequoia_openpgp::cert::Cert

pub struct Cert { /* fields omitted */ }

A OpenPGP Certificate.

A Certificate (see RFC 4880, section 11.1) can be used to verify signatures and encrypt data. It can be stored in a keystore and uploaded to keyservers.

Certs are always canonicalized in the sense that only elements (user id, user attribute, subkey) with at least one valid self-signature at a given time under a given policy are used. However, we keep all packets around for re-serialization. It could be an component that we simply do not understand. The self-signatures are sorted so that the newest self-signature comes first. Components are sorted, but in an undefined manner (i.e., when parsing the same Cert multiple times, the components will be in the same order, but we reserve the right to change the sort function between versions). Third-party certifications are not validated, as the keys are not available; they are simply passed through as is.

Secret keys

Any key in a Cert may have a secret key attached to it. To protect secret keys from being leaked, secret keys are not written out if a Cert is serialized. To also serialize the secret keys, you need to use Cert::as_tsk() to get an object that writes them out during serialization.

Filtering certificates

To filter certificates, iterate over all components, clone what you want to keep, and reassemble the certificate. The following example simply copies all the packets, and can be adapted to suit your policy:

use openpgp::{Cert, cert::CertBuilder};

fn identity_filter(cert: &Cert) -> Result<Cert> {
    // Iterate over all of the Cert components, pushing packets we
    // want to keep into the accumulator.
    let mut acc = Vec::new();

    // Primary key and related signatures.
    let c = cert.primary_key().bundle();
    acc.push(c.key().clone().mark_role_primary().into());
    for s in c.self_signatures()   { acc.push(s.clone().into()) }
    for s in c.certifications()    { acc.push(s.clone().into()) }
    for s in c.self_revocations()  { acc.push(s.clone().into()) }
    for s in c.other_revocations() { acc.push(s.clone().into()) }

    // UserIDs and related signatures.
    for c in cert.userids().bundles() {
        acc.push(c.userid().clone().into());
        for s in c.self_signatures()   { acc.push(s.clone().into()) }
        for s in c.certifications()    { acc.push(s.clone().into()) }
        for s in c.self_revocations()  { acc.push(s.clone().into()) }
        for s in c.other_revocations() { acc.push(s.clone().into()) }
    }

    // UserAttributes and related signatures.
    for c in cert.user_attributes().bundles() {
        acc.push(c.user_attribute().clone().into());
        for s in c.self_signatures()   { acc.push(s.clone().into()) }
        for s in c.certifications()    { acc.push(s.clone().into()) }
        for s in c.self_revocations()  { acc.push(s.clone().into()) }
        for s in c.other_revocations() { acc.push(s.clone().into()) }
    }

    // Subkeys and related signatures.
    for c in cert.keys().subkeys() {
        acc.push(c.key().clone().into());
        for s in c.self_signatures()   { acc.push(s.clone().into()) }
        for s in c.certifications()    { acc.push(s.clone().into()) }
        for s in c.self_revocations()  { acc.push(s.clone().into()) }
        for s in c.other_revocations() { acc.push(s.clone().into()) }
    }

    // Unknown components and related signatures.
    for c in cert.unknowns() {
        acc.push(c.unknown().clone().into());
        for s in c.self_signatures()   { acc.push(s.clone().into()) }
        for s in c.certifications()    { acc.push(s.clone().into()) }
        for s in c.self_revocations()  { acc.push(s.clone().into()) }
        for s in c.other_revocations() { acc.push(s.clone().into()) }
    }

    // Any signatures that we could not associate with a component.
    for s in cert.bad_signatures()     { acc.push(s.clone().into()) }

    // Finally, parse into Cert.
    Cert::from_packet_pile(acc.into())
}

let (cert, _) =
    CertBuilder::general_purpose(None, Some("alice@example.org"))
    .generate()?;
assert_eq!(cert, identity_filter(&cert)?);

Example

use openpgp::Cert;

match Cert::from_packet_parser(ppr) {
    Ok(cert) => {
        println!("Key: {}", cert.fingerprint());
        for binding in cert.userids().bundles() {
            println!("User ID: {}", binding.userid());
        }
    }
    Err(err) => {
        eprintln!("Error parsing Cert: {}", err);
    }
}

Methods

impl Cert[src]

pub fn primary_key(&self) -> PrimaryKeyAmalgamation<PublicParts>[src]

Returns the amalgamated primary key.

pub fn revoked<T>(&self, policy: &dyn Policy, t: T) -> RevocationStatus where
    T: Into<Option<SystemTime>>, 
[src]

Returns the Cert's revocation status at time t.

A Cert is revoked at time t if:

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

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

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

Note: this only returns whether this Cert is revoked; it does not imply anything about the Cert or other components.

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

Revokes the Cert in place.

Note: to just generate a revocation certificate, use the CertRevocationBuilder.

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

Example

use openpgp::RevocationStatus;
use openpgp::types::{ReasonForRevocation, SignatureType};
use openpgp::cert::{CipherSuite, CertBuilder};
use openpgp::crypto::KeyPair;
use openpgp::parse::Parse;
use sequoia_openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let (mut cert, _) = CertBuilder::new()
    .set_cipher_suite(CipherSuite::Cv25519)
    .generate()?;
assert_eq!(RevocationStatus::NotAsFarAsWeKnow,
           cert.revoked(p, None));

let mut keypair = cert.primary_key().key().clone()
    .mark_parts_secret()?.into_keypair()?;
let cert = cert.revoke_in_place(&mut keypair,
                              ReasonForRevocation::KeyCompromised,
                              b"It was the maid :/")?;
if let RevocationStatus::Revoked(sigs) = cert.revoked(p, None) {
    assert_eq!(sigs.len(), 1);
    assert_eq!(sigs[0].typ(), SignatureType::KeyRevocation);
    assert_eq!(sigs[0].reason_for_revocation(),
               Some((ReasonForRevocation::KeyCompromised,
                     "It was the maid :/".as_bytes())));
} else {
    unreachable!()
}

pub fn alive<T>(&self, policy: &dyn Policy, t: T) -> Result<()> where
    T: Into<Option<SystemTime>>, 
[src]

Returns whether or not the Cert is alive at t.

pub fn set_expiration_time(
    self,
    policy: &dyn Policy,
    primary_signer: &mut dyn Signer,
    expiration: Option<SystemTime>
) -> Result<Cert>
[src]

Sets the key to expire at the given time.

A policy is needed, because the expiration is updated by adding a self-signature to the primary user id.

pub fn primary_userid<'a, T>(
    &'a self,
    policy: &'a dyn Policy,
    t: T
) -> Option<ValidComponentAmalgamation<'a, UserID>> where
    T: Into<Option<SystemTime>>, 
[src]

Returns the amalgamated primary userid at t, if any.

Important traits for ComponentIter<'a, C>
pub fn userids(&self) -> ComponentIter<UserID>[src]

Returns an iterator over the Cert's userids.

pub fn primary_user_attribute<'a, T>(
    &'a self,
    policy: &'a dyn Policy,
    t: T
) -> Option<ValidComponentAmalgamation<'a, UserAttribute>> where
    T: Into<Option<SystemTime>>, 
[src]

Returns the amalgamated primary user attribute at t, if any.

Important traits for ComponentIter<'a, C>
pub fn user_attributes(&self) -> ComponentIter<UserAttribute>[src]

Returns an iterator over the Cert's UserAttributeBundles.

pub fn unknowns(&self) -> UnknownBundleIter[src]

Returns an iterator over the Cert's unknown components.

pub fn bad_signatures(&self) -> &[Signature][src]

Returns a slice containing all bad signatures.

Bad signatures are signatures that we could not associate with one of the components.

Important traits for KeyIter<'a, PublicParts>
pub fn keys(&self) -> KeyIter<PublicParts>[src]

Returns an iterator over the certificate's keys.

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

pub fn from_packet_parser(ppr: PacketParserResult) -> Result<Self>[src]

Returns the Cert found in the packet stream.

If there are more packets after the Cert, e.g. because the packet stream is a keyring, this function will return Error::MalformedCert.

pub fn from_packet_pile(p: PacketPile) -> Result<Self>[src]

Returns the first Cert found in the PacketPile.

pub fn key_handle(&self) -> KeyHandle[src]

Returns the Cert's fingerprint.

pub fn fingerprint(&self) -> Fingerprint[src]

Returns the Cert's fingerprint.

pub fn keyid(&self) -> KeyID[src]

Returns the Cert's keyid.

pub fn into_packets(self) -> impl Iterator<Item = Packet>[src]

Converts the Cert into an iterator over a sequence of packets.

This method discards invalid components and bad signatures.

pub fn into_packet_pile(self) -> PacketPile[src]

Converts the Cert into a PacketPile.

This method discards invalid components and bad signatures.

pub fn merge(self, other: Cert) -> Result<Self>[src]

Merges other into self.

If other is a different key, then an error is returned.

pub fn merge_packets(self, packets: Vec<Packet>) -> Result<Self>[src]

Adds packets to the Cert.

This recanonicalizes the Cert. If the packets are invalid, they are dropped.

If a key is merged in that already exists in the cert, it replaces the key. This way, secret key material can be added, removed, encrypted, or decrypted.

pub fn is_tsk(&self) -> bool[src]

Returns whether at least one of the keys includes a secret part.

impl Cert[src]

pub fn as_tsk<'a>(&'a self) -> TSK<'a>[src]

Derive a TSK object from this key.

This object writes out secret keys during serialization.

impl Cert[src]

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

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.

pub fn armored<'a>(&'a self) -> impl Serialize + SerializeInto + 'a[src]

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 userids are added as comments, so that it is easier to identify the Cert when looking at the armored data.

Example

use sequoia_openpgp as openpgp;
use openpgp::cert;
use openpgp::serialize::SerializeInto;

let (cert, _) =
    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

impl Serialize for Cert[src]

impl SerializeInto for Cert[src]

fn to_vec(&self) -> Result<Vec<u8>>[src]

Serializes the packet to a vector.

fn export_to_vec(&self) -> Result<Vec<u8>>[src]

Exports to a vector. Read more

impl<'a> Parse<'a, Cert> for Cert[src]

fn from_reader<R: Read>(reader: R) -> Result<Self>[src]

Returns the first Cert encountered in the reader.

fn from_file<P: AsRef<Path>>(path: P) -> Result<Self>[src]

Returns the first Cert encountered in the file.

fn from_bytes<D: AsRef<[u8]> + ?Sized>(data: &'a D) -> Result<Self>[src]

Returns the first Cert found in buf.

buf must be an OpenPGP-encoded message.

impl PartialEq<Cert> for Cert[src]

impl Clone for Cert[src]

fn clone_from(&mut self, source: &Self)
1.0.0
[src]

Performs copy-assignment from source. Read more

impl Display for Cert[src]

impl Debug for Cert[src]

impl FromStr for Cert[src]

type Err = Error

The associated error which can be returned from parsing.

Auto Trait Implementations

impl Send for Cert

impl Sync for Cert

Blanket Implementations

impl<T> From for T[src]

impl<T, U> Into for T where
    U: From<T>, 
[src]

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

impl<T> ToString for T where
    T: Display + ?Sized
[src]

impl<T, U> TryFrom for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T> Borrow for T where
    T: ?Sized
[src]

impl<T> BorrowMut for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T, U> TryInto for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<V, T> VZip for T where
    V: MultiLane<T>,