[][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 are preserved. Also, invalid self-signatures are dropped. 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 adopted 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.
    acc.push(cert.primary().clone().into());
    for s in cert.direct_signatures()  { acc.push(s.clone().into()) }
    for s in cert.certifications()     { acc.push(s.clone().into()) }
    for s in cert.self_revocations()   { acc.push(s.clone().into()) }
    for s in cert.other_revocations()  { acc.push(s.clone().into()) }

    // UserIDs and related signatures.
    for c in cert.userids() {
        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() {
        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.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.primary());
        for binding in cert.userids() {
            println!("User ID: {}", binding.userid());
        }
    }
    Err(err) => {
        eprintln!("Error parsing Cert: {}", err);
    }
}

Methods

impl Cert[src]

pub fn primary(&self) -> &Key<PublicParts, PrimaryRole>[src]

Returns a reference to the primary key binding.

Note: information about the primary key is often stored on the primary User ID's self signature. Since these signatures are associated with the UserID and not the primary key, that information is not contained in the key binding. Instead, you should use methods like Cert::primary_key_signature() to get information about the primary key.

pub fn primary_userid<T>(&self, t: T) -> Option<&UserIDBinding> where
    T: Into<Option<SystemTime>>, 
[src]

Returns the binding for the primary User ID at time t.

See Cert::primary_userid_full for a description of how the primary user id is determined.

pub fn primary_userid_full<T>(
    &self,
    t: T
) -> Option<(&UserIDBinding, &Signature, RevocationStatus)> where
    T: Into<Option<SystemTime>>, 
[src]

Returns the binding for the primary User ID at time t and some associated data.

In addition to the User ID binding, this also returns the binding signature and the User ID's RevocationStatus at time t.

The primary User ID is determined by taking the User IDs that are alive at time t, and sorting them as follows:

  • non-revoked first
  • primary first
  • signature creation first

If there is more than one, than one is selected in a deterministic, but undefined manner.

pub fn primary_key_signature_full<T>(
    &self,
    t: T
) -> Option<(&Signature, Option<(&UserIDBinding, RevocationStatus)>)> where
    T: Into<Option<SystemTime>>, 
[src]

Returns the primary key's current self-signature as of t.

If the current self-signature is from a User ID binding (and not a direct signature), this also returns the User ID binding and its revocation status as of t.

The primary key's current self-signature as of t is, in order of preference:

  • The binding signature of the primary User ID at time t, if the primary User ID is not revoked at time t.

  • The newest, live, direct self signature at time t.

  • The binding signature of the primary User ID at time t (this can only happen if there are only revoked User IDs at time t).

If there are no applicable signatures, None is returned.

pub fn primary_key_signature<T>(&self, t: T) -> Option<&Signature> where
    T: Into<Option<SystemTime>>, 
[src]

Returns the primary key's current self-signature.

This function is identical to Cert::primary_key_signature_full(), but it doesn't return the UserIDBinding.

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

The direct signatures.

The signatures are validated, and they are reverse sorted by their creation time (newest first).

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

Third-party certifications.

The signatures are not validated. They are reverse sorted by their creation time (newest first).

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

Revocations issued by the key itself.

The revocations are validated, and they are reverse sorted by their creation time (newest first).

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

Revocations issued by other keys.

The revocations are not validated. They are reverse sorted by their creation time (newest first).

pub fn revoked<T>(&self, 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;
let (mut cert, _) = CertBuilder::new()
    .set_cipher_suite(CipherSuite::Cv25519)
    .generate()?;
assert_eq!(RevocationStatus::NotAsFarAsWeKnow,
           cert.revoked(None));

let mut keypair = cert.primary().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(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, t: T) -> Result<()> where
    T: Into<Option<SystemTime>>, 
[src]

Returns whether or not the Cert is alive at t.

pub fn set_expiry(
    self,
    primary_signer: &mut dyn Signer,
    expiration: Option<Duration>
) -> Result<Cert>
[src]

Sets the key to expire in delta.

Note: the time is relative to the key's creation time, not the current time!

pub fn userids(&self) -> UserIDBindingIter[src]

Returns an iterator over the Cert's UserIDBindings.

pub fn user_attributes(&self) -> UserAttributeBindingIter[src]

Returns an iterator over the Cert's valid UserAttributeBindings.

A valid UserIDAttributeBinding has at least one good self-signature.

pub fn subkeys(&self) -> KeyBindingIter<PublicParts, SubordinateRole>[src]

Returns an iterator over the Cert's valid subkeys.

A valid KeyBinding has at least one good self-signature.

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

Returns an iterator over the Cert's valid unknown components.

A valid UnknownBinding has at least one good self-signature.

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, R>
pub fn keys(&self) -> KeyIter<PublicParts, UnspecifiedRole>[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 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 userids 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 Clone for Cert[src]

impl Debug for Cert[src]

impl Display for Cert[src]

impl FromStr for Cert[src]

type Err = Error

The associated error which can be returned from parsing.

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 Serialize for Cert[src]

impl SerializeInto for Cert[src]

impl StructuralPartialEq for Cert[src]

Auto Trait Implementations

impl !RefUnwindSafe for Cert

impl Send for Cert

impl Sync for Cert

impl Unpin for Cert

impl !UnwindSafe for Cert

Blanket Implementations

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

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

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

impl<T> From<T> for T[src]

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

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

type Owned = T

The resulting type after obtaining ownership.

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

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

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> 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<V> for T where
    V: MultiLane<T>,