Struct sequoia_openpgp::types::Timestamp

source ·
pub struct Timestamp(/* private fields */);
Expand description

A timestamp representable by OpenPGP.

OpenPGP timestamps are represented as u32 containing the number of seconds elapsed since midnight, 1 January 1970 UTC (Section 3.5 of RFC 4880).

They cannot express dates further than 7th February of 2106 or earlier than the UNIX epoch. Unlike Unix’s time_t, OpenPGP’s timestamp is unsigned so it rolls over in 2106, not 2038.

§Examples

Signature creation time is internally stored as a Timestamp:

Note that this example retrieves raw packet value. Use SubpacketAreas::signature_creation_time to get the signature creation time.

use sequoia_openpgp as openpgp;
use std::convert::From;
use std::time::SystemTime;
use openpgp::cert::prelude::*;
use openpgp::policy::StandardPolicy;
use openpgp::packet::signature::subpacket::{SubpacketTag, SubpacketValue};

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

let subkey = cert.keys().subkeys().next().unwrap();
let packets = subkey.bundle().self_signatures2().next().unwrap().hashed_area();

match packets.subpacket(SubpacketTag::SignatureCreationTime).unwrap().value() {
    SubpacketValue::SignatureCreationTime(ts) => assert!(u32::from(*ts) > 0),
    v => panic!("Unexpected subpacket: {:?}", v),
}

let p = &StandardPolicy::new();
let now = SystemTime::now();
assert!(subkey.binding_signature(p, now)?.signature_creation_time().is_some());

Implementations§

source§

impl Timestamp

source

pub fn now() -> Timestamp

Returns the current time.

source

pub fn checked_add(&self, d: Duration) -> Option<Timestamp>

Adds a duration to this timestamp.

Returns None if the resulting timestamp is not representable.

source

pub fn checked_sub(&self, d: Duration) -> Option<Timestamp>

Subtracts a duration from this timestamp.

Returns None if the resulting timestamp is not representable.

source

pub fn round_down<P, F>(&self, precision: P, floor: F) -> Result<Timestamp>
where P: Into<Option<u8>>, F: Into<Option<SystemTime>>,

Rounds down to the given level of precision.

This can be used to reduce the metadata leak resulting from time stamps. For example, a group of people attending a key signing event could be identified by comparing the time stamps of resulting certifications. By rounding the creation time of these signatures down, all of them, and others, fall into the same bucket.

The given level p determines the resulting resolution of 2^p seconds. The default is 21, which results in a resolution of 24 days, or roughly a month. p must be lower than 32.

The lower limit floor represents the earliest time the timestamp will be rounded down to.

See also Duration::round_up.

§Important note

If we create a signature, it is important that the signature’s creation time does not predate the signing keys creation time, or otherwise violate the key’s validity constraints. This can be achieved by using the floor parameter.

To ensure validity, use this function to round the time down, using the latest known relevant timestamp as a floor. Then, lookup all keys and other objects like userids using this timestamp, and on success create the signature:

use sequoia_openpgp::policy::StandardPolicy;

let policy = &StandardPolicy::new();

// Let's fix a time.
let now = Timestamp::from(1583436160);

let cert_creation_alice = now.checked_sub(Duration::weeks(2)?).unwrap();
let cert_creation_bob = now.checked_sub(Duration::weeks(1)?).unwrap();

// Generate a Cert for Alice.
let (alice, _) = CertBuilder::new()
    .set_creation_time(cert_creation_alice)
    .set_primary_key_flags(KeyFlags::empty().set_certification())
    .add_userid("alice@example.org")
    .generate()?;

// Generate a Cert for Bob.
let (bob, _) = CertBuilder::new()
    .set_creation_time(cert_creation_bob)
    .set_primary_key_flags(KeyFlags::empty().set_certification())
    .add_userid("bob@example.org")
    .generate()?;

let sign_with_p = |p| -> Result<Signature> {
    // Round `now` down, then use `t` for all lookups.
    // Use the creation time of Bob's Cert as lower bound for rounding.
    let t: std::time::SystemTime = now.round_down(p, cert_creation_bob)?.into();

    // First, get the certification key.
    let mut keypair =
        alice.keys().with_policy(policy, t).secret().for_certification()
        .nth(0).ok_or_else(|| anyhow::anyhow!("no valid key at"))?
        .key().clone().into_keypair()?;

    // Then, lookup the binding between `bob@example.org` and
    // `bob` at `t`.
    let ca = bob.userids().with_policy(policy, t)
        .filter(|ca| ca.userid().value() == b"bob@example.org")
        .nth(0).ok_or_else(|| anyhow::anyhow!("no valid userid"))?;

    // Finally, Alice certifies the binding between
    // `bob@example.org` and `bob` at `t`.
    ca.userid().certify(&mut keypair, &bob,
                        SignatureType::PositiveCertification, None, t)
};

assert!(sign_with_p(21).is_ok());
assert!(sign_with_p(22).is_ok());  // Rounded to bob's cert's creation time.
assert!(sign_with_p(32).is_err()); // Invalid precision

Trait Implementations§

source§

impl Clone for Timestamp

source§

fn clone(&self) -> Timestamp

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 Debug for Timestamp

source§

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

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

impl Display for Timestamp

source§

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

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

impl From<Timestamp> for Option<SystemTime>

source§

fn from(t: Timestamp) -> Self

Converts to this type from the input type.
source§

impl From<Timestamp> for SystemTime

SystemTime’s underlying datatype may be only i32, e.g. on 32bit Unix. As OpenPGP’s timestamp datatype is u32, there are timestamps (i32::MAX + 1 to u32::MAX) which are not representable on such systems.

In this case, the result is clamped to i32::MAX.

source§

fn from(t: Timestamp) -> Self

Converts to this type from the input type.
source§

impl From<Timestamp> for u32

source§

fn from(t: Timestamp) -> Self

Converts to this type from the input type.
source§

impl From<u32> for Timestamp

source§

fn from(t: u32) -> Self

Converts to this type from the input type.
source§

impl Hash for Timestamp

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

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

impl Ord for Timestamp

source§

fn cmp(&self, other: &Timestamp) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl PartialEq for Timestamp

source§

fn eq(&self, other: &Timestamp) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd for Timestamp

source§

fn partial_cmp(&self, other: &Timestamp) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl TryFrom<SystemTime> for Timestamp

§

type Error = Error

The type returned in the event of a conversion error.
source§

fn try_from(t: SystemTime) -> Result<Self>

Performs the conversion.
source§

impl Copy for Timestamp

source§

impl Eq for Timestamp

source§

impl StructuralPartialEq for Timestamp

Auto Trait Implementations§

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> CloneToUninit for T
where T: Copy,

source§

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