Enum sequoia_openpgp::packet::Key[][src]

#[non_exhaustive]
pub enum Key<P: KeyParts, R: KeyRole> {
    V4(Key4<P, R>),
}
Expand description

Holds a public key, public subkey, private key or private subkey packet.

The different Key packets are described in Section 5.5 of RFC 4880.

Note: This enum cannot be exhaustively matched to allow future extensions.

Key Variants

There are four different types of keys in OpenPGP: public keys, secret keys, public subkeys, and secret subkeys. Although the semantics of each type of key are slightly different, the underlying representation is identical (even a public key and a secret key are the same: the public key variant just contains 0 bits of secret key material).

In Sequoia, we use a single type, Key, for all four variants. To improve type safety, we use marker traits rather than an enum to distinguish them. Specifically, we Key is generic over two type variables, P and R.

P and R take marker traits, which describe how any secret key material should be treated, and the key’s role (primary or subordinate). The markers also determine the Key’s behavior and the exposed functionality. P can be key::PublicParts, key::SecretParts, or key::UnspecifiedParts. And, R can be key::PrimaryRole, key::SubordinateRole, or key::UnspecifiedRole.

If P is key::PublicParts, any secret key material that is present is ignored. For instance, when serializing a key with this marker, any secret key material will be skipped. This is illutrated in the following example. If P is key::SecretParts, then the key definitely contains secret key material (although it is not guaranteed that the secret key material is valid), and methods that require secret key material are available.

Unlike P, R does not say anything about the Key’s content. But, a key’s role does influence’s the key’s semantics. For instance, some of a primary key’s meta-data is located on the primary User ID whereas a subordinate key’s meta-data is located on its binding signature.

The unspecified variants key::UnspecifiedParts and key::UnspecifiedRole exist to simplify type erasure, which is needed to mix different types of keys in a single collection. For instance, Cert::keys returns an iterator over the keys in a certificate. Since the keys have different roles (a primary key and zero or more subkeys), but the Iterator has to be over a single, fixed type, the returned keys use the key::UnspecifiedRole marker.

Examples

Serializing a public key with secret key material drops the secret key material:

use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::packet::prelude::*;
use sequoia_openpgp::parse::Parse;
use openpgp::serialize::Serialize;

// Generate a new certificate.  It has secret key material.
let (cert, _) = CertBuilder::new()
    .generate()?;

let pk = cert.primary_key().key();
assert!(pk.has_secret());

// Serializing a `Key<key::PublicParts, _>` drops the secret key
// material.
let mut bytes = Vec::new();
Packet::from(pk.clone()).serialize(&mut bytes);
let p : Packet = Packet::from_bytes(&bytes)?;

if let Packet::PublicKey(key) = p {
    assert!(! key.has_secret());
} else {
    unreachable!();
}

Conversions

Sometimes it is necessary to change a marker. For instance, to help prevent a user from inadvertently leaking secret key material, the Cert data structure never returns keys with the key::SecretParts marker. This means, to use any secret key material, e.g., when creating a Signer, the user needs to explicitly opt-in by changing the marker using Key::parts_into_secret or Key::parts_as_secret.

For P, the conversion functions are: Key::parts_into_public, Key::parts_as_public, Key::parts_into_secret, Key::parts_as_secret, Key::parts_into_unspecified, and Key::parts_as_unspecified. With the exception of converting P to key::SecretParts, these functions are infallible. Converting P to key::SecretParts may fail if the key doesn’t have any secret key material. (Note: although the secret key material is required, it not checked for validity.)

For R, the conversion functions are Key::role_into_primary, Key::role_as_primary, Key::role_into_subordinate, Key::role_as_subordinate, Key::role_into_unspecified, and Key::role_as_unspecified.

It is also possible to use From.

Examples

Changing a marker:

use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::packet::prelude::*;

// Generate a new certificate.  It has secret key material.
let (cert, _) = CertBuilder::new()
    .generate()?;

let pk: &Key<key::PublicParts, key::PrimaryRole>
    = cert.primary_key().key();
// `has_secret`s is one of the few methods that ignores the
// parts type.
assert!(pk.has_secret());

// Treat it like a secret key.  This only works if `pk` really
// has secret key material (which it does in this case, see above).
let sk = pk.parts_as_secret()?;
assert!(sk.has_secret());

// And back.
let pk = sk.parts_as_public();
// Yes, the secret key material is still there.
assert!(pk.has_secret());

The Cert data structure only returns public keys. To work with any secret key material, the Key first needs to be converted to a secret key. This is necessary, for instance, when creating a Signer:

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

let p = &StandardPolicy::new();

let the_past = time::SystemTime::now() - time::Duration::from_secs(1);
let (cert, _) = CertBuilder::new()
    .set_creation_time(the_past)
    .generate()?;

// Set the certificate to expire now.  To do this, we need
// to create a new self-signature, and sign it using a
// certification-capable key.  The primary key is always
// certification capable.
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)?;
// It's expired now.
assert!(cert.with_policy(p, None)?.alive().is_err());

Key Generation

Key is a wrapper around the different key formats. (Currently, Sequoia only supports version 4 keys, however, future versions may add limited support for version 3 keys to facilitate working with achieved messages, and RFC 4880bis includes a proposal for a new key format.) As such, it doesn’t provide a mechanism to generate keys or import existing key material. Instead, use the format-specific functions (e.g., Key4::generate_ecc) and then convert the result into a Key packet, as the following example demonstrates.

Examples

use sequoia_openpgp as openpgp;
use openpgp::packet::prelude::*;
use openpgp::types::Curve;

let key: Key<key::SecretParts, key::PrimaryRole>
    = Key::from(Key4::generate_ecc(true, Curve::Ed25519)?);

Password Protection

OpenPGP provides a mechanism to password protect keys. If a key is password protected, you need to decrypt the password using Key::decrypt_secret before using its secret key material (e.g., to decrypt a message, or to generate a signature).

A note on equality

The implementation of Eq for Key compares the serialized form of Keys. Comparing or serializing values of Key<PublicParts, _> ignore secret key material, whereas the secret key material is considered and serialized for Key<SecretParts, _>, and for Key<UnspecifiedParts, _> if present. To explicitly exclude the secret key material from the comparison, use Key::public_cmp or Key::public_eq.

When merging in secret key material from untrusted sources, you need to be very careful: secret key material is not cryptographically protected by the key’s self signature. Thus, an attacker can provide a valid key with a valid self signature, but invalid secret key material. If naively merged, this could overwrite valid secret key material, and thereby render the key useless. Unfortunately, the only way to find out that the secret key material is bad is to actually try using it. But, because the secret key material is usually encrypted, this can’t always be done automatically.

Compare:

use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::packet::prelude::*;
use openpgp::packet::key::*;

// Generate a new certificate.  It has secret key material.
let (cert, _) = CertBuilder::new()
    .generate()?;

let sk: &Key<PublicParts, _> = cert.primary_key().key();
assert!(sk.has_secret());

// Strip the secret key material.
let cert = cert.clone().strip_secret_key_material();
let pk: &Key<PublicParts, _> = cert.primary_key().key();
assert!(! pk.has_secret());

// Eq on Key<PublicParts, _> compares only the public bits, so it
// considers pk and sk to be equal.
assert_eq!(pk, sk);

// Convert to Key<UnspecifiedParts, _>.
let sk: &Key<UnspecifiedParts, _> = sk.parts_as_unspecified();
let pk: &Key<UnspecifiedParts, _> = pk.parts_as_unspecified();

// Eq on Key<UnspecifiedParts, _> compares both the public and the
// secret bits, so it considers pk and sk to be different.
assert_ne!(pk, sk);

// In any case, Key::public_eq only compares the public bits,
// so it considers them to be equal.
assert!(Key::public_eq(pk, sk));

Variants (Non-exhaustive)

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.

V4(Key4<P, R>)

Tuple Fields

0: Key4<P, R>

A version 4 Key packet.

Implementations

Encrypts the given data with this key.

Verifies the given signature.

Changes the key’s parts tag to PublicParts.

Changes the key’s parts tag to PublicParts.

Changes the key’s parts tag to SecretParts.

Changes the key’s parts tag to SecretParts.

Changes the key’s parts tag to UnspecifiedParts.

Changes the key’s parts tag to UnspecifiedParts.

Changes the key’s role tag to PrimaryRole.

Changes the key’s role tag to PrimaryRole.

Changes the key’s role tag to SubordinateRole.

Changes the key’s role tag to SubordinateRole.

Changes the key’s role tag to UnspecifiedRole.

Changes the key’s role tag to UnspecifiedRole.

Gets the version.

Compares the public bits of two keys.

This returns Ordering::Equal if the public MPIs, version, creation time and algorithm of the two Keys match. This does not consider the packet’s encoding, packet’s tag or the secret key material.

This method tests for self and other values to be equal modulo the secret key material.

This returns true if the public MPIs, creation time and algorithm of the two Keys match. This does not consider the packet’s encoding, packet’s tag or the secret key material.

Creates a new key pair from a Key with an unencrypted secret key.

If the Key is password protected, you first need to decrypt it using Key::decrypt_secret.

Errors

Fails if the secret key is encrypted.

Examples

Revoke a certificate by signing a new revocation certificate:

use std::time;
use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::crypto::KeyPair;
use openpgp::types::ReasonForRevocation;

// Generate a certificate.
let (cert, _) =
    CertBuilder::general_purpose(None,
                                 Some("Alice Lovelace <alice@example.org>"))
        .generate()?;

// Use the secret key material to sign a revocation certificate.
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 :/")?;

Decrypts the secret key material.

In OpenPGP, secret key material can be protected with a password. The password is usually hardened using a KDF.

This function takes ownership of the Key, decrypts the secret key material using the password, and returns a new key whose secret key material is not password protected.

If the secret key material is not password protected or if the password is wrong, this function returns an error.

Examples

Sign a new revocation certificate using a password-protected key:

use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::types::ReasonForRevocation;

// Generate a certificate whose secret key material is
// password protected.
let (cert, _) =
    CertBuilder::general_purpose(None,
                                 Some("Alice Lovelace <alice@example.org>"))
        .set_password(Some("1234".into()))
        .generate()?;

// Use the secret key material to sign a revocation certificate.
let key = cert.primary_key().key().clone().parts_into_secret()?;

// We can't turn it into a keypair without decrypting it.
assert!(key.clone().into_keypair().is_err());

// And, we need to use the right password.
assert!(key.clone()
    .decrypt_secret(&"correct horse battery staple".into())
    .is_err());

// Let's do it right:
let mut keypair = key.decrypt_secret(&"1234".into())?.into_keypair()?;
let rev = cert.revoke(&mut keypair,
                      ReasonForRevocation::KeyCompromised,
                      b"It was the maid :/")?;

Encrypts the secret key material.

In OpenPGP, secret key material can be protected with a password. The password is usually hardened using a KDF.

This function takes ownership of the Key, encrypts the secret key material using the password, and returns a new key whose secret key material is protected with the password.

If the secret key material is already password protected, this function returns an error.

Examples

This example demonstrates how to encrypt the secret key material of every key in a certificate. Decryption can be done the same way with Key::decrypt_secret.

use sequoia_openpgp as openpgp;
use openpgp::cert::prelude::*;
use openpgp::packet::Packet;

// Generate a certificate whose secret key material is
// not password protected.
let (cert, _) =
    CertBuilder::general_purpose(None,
                                 Some("Alice Lovelace <alice@example.org>"))
        .generate()?;

// Encrypt every key.
let mut encrypted_keys: Vec<Packet> = Vec::new();
for ka in cert.keys().secret() {
    assert!(ka.has_unencrypted_secret());

    // Encrypt the key's secret key material.
    let key = ka.key().clone().encrypt_secret(&"1234".into())?;
    assert!(! key.has_unencrypted_secret());

    // We cannot merge it right now, because `cert` is borrowed.
    encrypted_keys.push(if ka.primary() {
        key.role_into_primary().into()
    } else {
        key.role_into_subordinate().into()
    });
}

// Merge the keys into the certificate.  Note: `Cert::insert_packets`
// prefers added versions of keys.  So, the encrypted version
// will override the decrypted version.
let cert = cert.insert_packets(encrypted_keys)?;

// Now the every key's secret key material is encrypted.  We'll
// demonstrate this using the primary key:
let key = cert.primary_key().key().parts_as_secret()?;
assert!(! key.has_unencrypted_secret());

// We can't turn it into a keypair without decrypting it.
assert!(key.clone().into_keypair().is_err());

// And, we need to use the right password.
assert!(key.clone()
    .decrypt_secret(&"correct horse battery staple".into())
    .is_err());

// Let's do it right:
let mut keypair = key.clone()
    .decrypt_secret(&"1234".into())?.into_keypair()?;

Secret key handling.

Takes the key packet’s SecretKeyMaterial, if any.

Adds SecretKeyMaterial to the packet, returning the old if any.

Secret key handling.

Takes the key packet’s SecretKeyMaterial, if any.

Adds SecretKeyMaterial to the packet, returning the old if any.

Secret key handling.

Takes the key packet’s SecretKeyMaterial.

Adds SecretKeyMaterial to the packet, returning the old.

Creates a binding signature.

The signature binds this subkey to cert. signer will be used to create a signature using signature as builder. Thehash_algo defaults to SHA512, creation_time to the current time.

Note that subkeys with signing capabilities need a primary key binding signature. If you are creating this binding signature from a previous binding signature, you can reuse the primary key binding signature if it is still valid and meets current algorithm requirements. Otherwise, you can create one using SignatureBuilder::sign_primary_key_binding.

This function adds a creation time subpacket, a issuer fingerprint subpacket, and a issuer subpacket to the signature.

Examples

This example demonstrates how to bind this key to a Cert. Note that in general, the CertBuilder is a better way to add subkeys to a Cert.

use sequoia_openpgp::policy::StandardPolicy;
let p = &StandardPolicy::new();

// Generate a Cert, and create a keypair from the primary key.
let (cert, _) = CertBuilder::new().generate()?;
let mut keypair = cert.primary_key().key().clone()
    .parts_into_secret()?.into_keypair()?;

// Let's add an encryption subkey.
let flags = KeyFlags::empty().set_storage_encryption();
assert_eq!(cert.keys().with_policy(p, None).alive().revoked(false)
               .key_flags(&flags).count(),
           0);

// Generate a subkey and a binding signature.
let subkey: Key<_, key::SubordinateRole> =
    Key4::generate_ecc(false, Curve::Cv25519)?
    .into();
let builder = signature::SignatureBuilder::new(SignatureType::SubkeyBinding)
    .set_key_flags(flags.clone())?;
let binding = subkey.bind(&mut keypair, &cert, builder)?;

// Now merge the key and binding signature into the Cert.
let cert = cert.insert_packets(vec![Packet::from(subkey),
                                   binding.into()])?;

// Check that we have an encryption subkey.
assert_eq!(cert.keys().with_policy(p, None).alive().revoked(false)
               .key_flags(flags).count(),
           1);

Methods from Deref<Target = Key4<P, R>>

Changes the key’s parts tag to PublicParts.

Changes the key’s parts tag to SecretParts.

Changes the key’s parts tag to UnspecifiedParts.

Changes the key’s role tag to PrimaryRole.

Changes the key’s role tag to SubordinateRole.

Changes the key’s role tag to UnspecifiedRole.

The security requirements of the hash algorithm for self-signatures.

A cryptographic hash algorithm usually has three security properties: pre-image resistance, second pre-image resistance, and collision resistance. If an attacker can influence the signed data, then the hash algorithm needs to have both second pre-image resistance, and collision resistance. If not, second pre-image resistance is sufficient.

In general, an attacker may be able to influence third-party signatures. But direct key signatures, and binding signatures are only over data fully determined by signer. And, an attacker’s control over self signatures over User IDs is limited due to their structure.

These observations can be used to extend the life of a hash algorithm after its collision resistance has been partially compromised, but not completely broken. For more details, please refer to the documentation for HashAlgoSecurity.

Compares the public bits of two keys.

This returns Ordering::Equal if the public MPIs, creation time, and algorithm of the two Key4s match. This does not consider the packets’ encodings, packets’ tags or their secret key material.

Tests whether two keys are equal modulo their secret key material.

This returns true if the public MPIs, creation time and algorithm of the two Key4s match. This does not consider the packets’ encodings, packets’ tags or their secret key material.

Hashes everything but any secret key material into state.

This is an alternate implementation of Hash, which never hashes the secret key material.

Gets the Key’s creation time.

Sets the Key’s creation time.

timestamp is converted to OpenPGP’s internal format, Timestamp: a 32-bit quantity containing the number of seconds since the Unix epoch.

timestamp is silently rounded to match the internal resolution. An error is returned if timestamp is out of range.

Gets the public key algorithm.

Sets the public key algorithm.

Returns the old public key algorithm.

Returns a reference to the Key’s MPIs.

Returns a mutable reference to the Key’s MPIs.

Sets the Key’s MPIs.

This function returns the old MPIs, if any.

Returns whether the Key contains secret key material.

Returns whether the Key contains unencrypted secret key material.

This returns false if the Key doesn’t contain any secret key material.

Returns Key’s secret key material, if any.

Computes and returns the Key’s Fingerprint and returns it as a KeyHandle.

See Section 12.2 of RFC 4880.

Computes and returns the Key’s Fingerprint.

See Section 12.2 of RFC 4880.

Computes and returns the Key’s Key ID.

See Section 12.2 of RFC 4880.

Gets the Key’s SecretKeyMaterial.

Gets a mutable reference to the Key’s SecretKeyMaterial.

Trait Implementations

Attempts to downcast to T, returning the packet if it fails. Read more

Attempts to downcast to &T, returning None if it fails. Read more

Attempts to downcast to &mut T, returning None if it fails. Read more

Attempts to downcast to T, returning the packet if it fails. Read more

Attempts to downcast to &T, returning None if it fails. Read more

Attempts to downcast to &mut T, returning None if it fails. Read more

Attempts to downcast to T, returning the packet if it fails. Read more

Attempts to downcast to &T, returning None if it fails. Read more

Attempts to downcast to &mut T, returning None if it fails. Read more

Attempts to downcast to T, returning the packet if it fails. Read more

Attempts to downcast to &T, returning None if it fails. Read more

Attempts to downcast to &mut T, returning None if it fails. Read more

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

The resulting type after dereferencing.

Dereferences the value.

Mutably dereferences the value.

Formats the value using the given formatter. Read more

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Convert the Key struct to a Packet.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Convert the Key struct to a Packet.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Convert the Key struct to a Packet.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Convert the Key struct to a Packet.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

Implement IntoIterator so that cert::insert_packets(sig) just works.

The type of the elements being iterated over.

Which kind of iterator are we turning this into?

Creates an iterator from a value. Read more

Writes a serialized version of the object to o.

Exports a serialized version of the object to o. Read more

Computes the maximal length of the serialized representation. Read more

Serializes into the given buffer. Read more

Serializes the packet to a vector.

Exports into the given buffer. Read more

Exports to a vector. Read more

Reads from the given reader.

Reads from the given file. Read more

Reads from the given slice. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Returns the valid amalgamation’s associated certificate. Read more

Returns the amalgamation’s reference time. Read more

Returns the amalgamation’s policy. Read more

Returns the component’s binding signature as of the reference time. Read more

Returns the component’s revocation status as of the amalgamation’s reference time. Read more

Returns a list of any designated revokers for this component. Read more

Maps the given function over binding and direct key signature. Read more

Returns the certificate’s direct key signature as of the reference time, if any. Read more

The type returned by with_policy. Read more

Uses the specified Policy and reference time with the amalgamation. Read more

The type returned by with_policy. Read more

Uses the specified Policy and reference time with the amalgamation. Read more

The type returned by with_policy. Read more

Uses the specified Policy and reference time with the amalgamation. Read more

The type returned by with_policy. Read more

Uses the specified Policy and reference time with the amalgamation. Read more

The type returned by with_policy. Read more

Uses the specified Policy and reference time with the amalgamation. Read more

The type returned by with_policy. Read more

Uses the specified Policy and reference time with the amalgamation. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

Should always be Self

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

Converts the given value to a String. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.