Skip to main content

Signer

Struct Signer 

Source
pub struct Signer<'a> { /* private fields */ }
Expand description

Signs a message.

Signs a message with every crypto::Signer added to the streaming signer.

Implementations§

Source§

impl<'a> Signer<'a>

Source

pub fn new<S>(inner: Message<'a>, signer: S) -> Result<Signer<'a>, Error>
where S: Signer + Send + Sync + 'a,

Creates a signer.

Signs the message with the given crypto::Signer. To create more than one signature, add more crypto::Signers using Signer::add_signer. Properties of the signatures can be tweaked using the methods of this type. Notably, to generate a detached signature (see Section 10.4 of RFC 9580), use Signer::detached. For even more control over the generated signatures, use Signer::with_template.

§Examples
use std::io::{Read, Write};
use sequoia_openpgp as openpgp;
use openpgp::serialize::stream::{Message, Signer, LiteralWriter};
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();
let cert: Cert = // ...
let signing_keypair = cert.keys().secret()
    .with_policy(p, None).supported().alive().revoked(false).for_signing()
    .nth(0).unwrap()
    .key().clone().into_keypair()?;

let mut sink = vec![];
{
    let message = Message::new(&mut sink);
    let message = Signer::new(message, signing_keypair)?
        // Customize the `Signer` here.
        .build()?;
    let mut message = LiteralWriter::new(message).build()?;
    message.write_all(b"Make it so, number one!")?;
    message.finalize()?;
}

// Now check the signature.
struct Helper<'a>(&'a openpgp::Cert);
impl<'a> VerificationHelper for Helper<'a> {
    fn get_certs(&mut self, _: &[openpgp::KeyHandle])
                       -> openpgp::Result<Vec<openpgp::Cert>> {
        Ok(vec![self.0.clone()])
    }

    fn check(&mut self, structure: MessageStructure)
             -> openpgp::Result<()> {
        if let MessageLayer::SignatureGroup { ref results } =
            structure.iter().nth(0).unwrap()
        {
            results.get(0).unwrap().as_ref().unwrap();
            Ok(())
        } else { panic!() }
    }
}

let mut verifier = VerifierBuilder::from_bytes(&sink)?
    .with_policy(p, None, Helper(&cert))?;

let mut message = String::new();
verifier.read_to_string(&mut message)?;
assert_eq!(&message, "Make it so, number one!");
Source

pub fn with_template<S, T>( inner: Message<'a>, signer: S, template: T, ) -> Result<Signer<'a>, Error>
where S: Signer + Send + Sync + 'a, T: Into<SignatureBuilder>,

Creates a signer with a given signature template.

Signs the message with the given crypto::Signer like Signer::new, but allows more control over the generated signatures. The given signature::SignatureBuilder is used to create all the signatures.

For every signature, the creation time is set to the current time or the one specified using Signer::creation_time, the intended recipients are added (see Signer::add_intended_recipient), the issuer and issuer fingerprint subpackets are set according to the signing key, and the hash algorithm set using Signer::hash_algo is used to create the signature.

§Examples
use std::io::{Read, Write};
use sequoia_openpgp as openpgp;
use openpgp::types::SignatureType;
use openpgp::packet::signature;
use openpgp::serialize::stream::{Message, Signer, LiteralWriter};

let message = Message::new(&mut sink);
let message = Signer::with_template(
    message, signing_keypair,
    signature::SignatureBuilder::new(SignatureType::Text)
        .add_notation("issuer@starfleet.command", "Jean-Luc Picard",
                      None, true)?)?
    // Further customize the `Signer` here.
    .build()?;
let mut message = LiteralWriter::new(message).build()?;
message.write_all(b"Make it so, number one!")?;
message.finalize()?;
Source

pub fn detached(self) -> Signer<'a> ⓘ

Creates a signer for a detached signature.

Changes the Signer to create a detached signature (see Section 10.4 of RFC 9580). Note that the literal data must not be wrapped using the LiteralWriter.

This overrides any prior call to Signer::cleartext.

§Examples
use std::io::Write;
use sequoia_openpgp as openpgp;
use openpgp::serialize::stream::{Message, Signer};
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let mut sink = vec![];
{
    let message = Message::new(&mut sink);
    let mut signer = Signer::new(message, signing_keypair)?
        .detached()
        // Customize the `Signer` here.
        .build()?;

    // Write the data directly to the `Signer`.
    signer.write_all(b"Make it so, number one!")?;
    // In reality, just io::copy() the file to be signed.
    signer.finalize()?;
}

// Now check the signature.
struct Helper<'a>(&'a openpgp::Cert);
impl<'a> VerificationHelper for Helper<'a> {
    fn get_certs(&mut self, _: &[openpgp::KeyHandle])
                       -> openpgp::Result<Vec<openpgp::Cert>> {
        Ok(vec![self.0.clone()])
    }

    fn check(&mut self, structure: MessageStructure)
             -> openpgp::Result<()> {
        if let MessageLayer::SignatureGroup { ref results } =
            structure.iter().nth(0).unwrap()
        {
            results.get(0).unwrap().as_ref().unwrap();
            Ok(())
        } else { panic!() }
    }
}

let mut verifier = DetachedVerifierBuilder::from_bytes(&sink)?
    .with_policy(p, None, Helper(&cert))?;

verifier.verify_bytes(b"Make it so, number one!")?;
Source

pub fn cleartext(self) -> Signer<'a> ⓘ

Creates a signer for a cleartext signed message.

Changes the Signer to create a cleartext signed message (see Section 7 of RFC 9580). Note that the literal data must not be wrapped using the LiteralWriter. This implies ASCII armored output, do not add an Armorer to the stack.

Note:

  • The cleartext signature framework does not hash trailing whitespace (in this case, space and tab, see Section 7.2 of RFC 9580 for more information). We align what we emit and what is being signed by trimming whitespace off of line endings.

  • That means that you can not recover a byte-accurate copy of the signed message if your message contains either a line with trailing whitespace, or no final newline. This is a limitation of the Cleartext Signature Framework, which is not designed to be reversible (see Section 7 of RFC 9580).

This overrides any prior call to Signer::detached.

§Examples
use std::io::{Write, Read};
use sequoia_openpgp as openpgp;
use openpgp::serialize::stream::{Message, Signer};
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();

let mut sink = vec![];
{
    let message = Message::new(&mut sink);
    let mut signer = Signer::new(message, signing_keypair)?
        .cleartext()
        // Customize the `Signer` here.
        .build()?;

    // Write the data directly to the `Signer`.
    signer.write_all(b"Make it so, number one!")?;
    // In reality, just io::copy() the file to be signed.
    signer.finalize()?;
}

// Now check the signature.
struct Helper<'a>(&'a openpgp::Cert);
impl<'a> VerificationHelper for Helper<'a> {
    fn get_certs(&mut self, _: &[openpgp::KeyHandle])
                       -> openpgp::Result<Vec<openpgp::Cert>> {
        Ok(vec![self.0.clone()])
    }

    fn check(&mut self, structure: MessageStructure)
             -> openpgp::Result<()> {
        if let MessageLayer::SignatureGroup { ref results } =
            structure.iter().nth(0).unwrap()
        {
            results.get(0).unwrap().as_ref().unwrap();
            Ok(())
        } else { panic!() }
    }
}

let mut verifier = VerifierBuilder::from_bytes(&sink)?
    .with_policy(p, None, Helper(&cert))?;

let mut content = Vec::new();
verifier.read_to_end(&mut content)?;
assert_eq!(content, b"Make it so, number one!");
Source

pub fn add_signer<S>(self, signer: S) -> Result<Signer<'a>, Error>
where S: Signer + Send + Sync + 'a,

Adds an additional signer.

Can be used multiple times.

Note that some signers only support a subset of hash algorithms, see [crate::crypto::Signer.acceptable_hashes]. If the given signer supports at least one hash from the current set of acceptable hashes, the signer is added and all algorithms not supported by it are removed from the set of acceptable hashes. Otherwise, an error is returned.

§Examples
use std::io::Write;
use sequoia_openpgp as openpgp;
use openpgp::serialize::stream::{Message, Signer, LiteralWriter};


let message = Message::new(&mut sink);
let message = Signer::new(message, signing_keypair)?
    .add_signer(additional_signing_keypair)?
    .build()?;
let mut message = LiteralWriter::new(message).build()?;
message.write_all(b"Make it so, number one!")?;
message.finalize()?;
Source

pub fn add_intended_recipient(self, recipient: &Cert) -> Signer<'a> ⓘ

Adds an intended recipient.

Indicates that the given certificate is an intended recipient of this message. Can be used multiple times. This prevents Surreptitious Forwarding of encrypted and signed messages, i.e. forwarding a signed message using a different encryption context.

§Examples
use std::io::Write;
use sequoia_openpgp as openpgp;
use openpgp::serialize::stream::{Message, Signer, LiteralWriter};

let recipient: Cert = // ...

let message = Message::new(&mut sink);
let message = Signer::new(message, signing_keypair)?
    .add_intended_recipient(&recipient)
    .build()?;
let mut message = LiteralWriter::new(message).build()?;
message.write_all(b"Make it so, number one!")?;
message.finalize()?;
Source

pub fn hash_algo(self, algo: HashAlgorithm) -> Result<Signer<'a>, Error>

Sets the preferred hash algorithm to use for the signatures.

Note that some signers only support a subset of hash algorithms, see [crate::crypto::Signer.acceptable_hashes]. If the given algorithm is not supported by all signers, an error is returned.

§Examples
use std::io::Write;
use sequoia_openpgp as openpgp;
use openpgp::types::HashAlgorithm;
use openpgp::serialize::stream::{Message, Signer, LiteralWriter};


let message = Message::new(&mut sink);
let message = Signer::new(message, signing_keypair)?
    .hash_algo(HashAlgorithm::SHA384)?
    .build()?;
let mut message = LiteralWriter::new(message).build()?;
message.write_all(b"Make it so, number one!")?;
message.finalize()?;
Source

pub fn creation_time<T>(self, creation_time: T) -> Signer<'a> ⓘ
where T: Into<SystemTime>,

Sets the signature’s creation time to time.

Note: it is up to the caller to make sure the signing keys are actually valid as of time.

§Examples
use std::io::Write;
use sequoia_openpgp as openpgp;
use openpgp::types::Timestamp;
use openpgp::serialize::stream::{Message, Signer, LiteralWriter};
use openpgp::policy::StandardPolicy;

let p = &StandardPolicy::new();
let cert: Cert = // ...
let signing_key = cert.keys().secret()
    .with_policy(p, None).supported().alive().revoked(false).for_signing()
    .nth(0).unwrap()
    .key();
let signing_keypair = signing_key.clone().into_keypair()?;

let message = Message::new(&mut sink);
let message = Signer::new(message, signing_keypair)?
    .creation_time(Timestamp::now()
                   .round_down(None, signing_key.creation_time())?)
    .build()?;
let mut message = LiteralWriter::new(message).build()?;
message.write_all(b"Make it so, number one!")?;
message.finalize()?;
Source

pub fn build(self) -> Result<Message<'a>, Error>

Builds the signer, returning the writer stack.

The most useful filter to push to the writer stack next is the LiteralWriter. Note, if you are creating a signed OpenPGP message (see Section 10.3 of RFC 9580), literal data must be wrapped using the LiteralWriter. On the other hand, if you are creating a detached signature (see Section 10.4 of RFC 9580), the literal data must not be wrapped using the LiteralWriter.

§Examples
use std::io::Write;
use sequoia_openpgp as openpgp;
use openpgp::types::Timestamp;
use openpgp::serialize::stream::{Message, Signer};

let message = Message::new(&mut sink);
let message = Signer::new(message, signing_keypair)?
    // Customize the `Signer` here.
    .build()?;

Trait Implementations§

Source§

impl<'a> Debug for Signer<'a>

Source§

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

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

impl<'a> Write for Signer<'a>

Source§

fn write(&mut self, buf: &[u8]) -> Result<usize, Error>

Writes a buffer into this writer, returning how many bytes were written. Read more
Source§

fn flush(&mut self) -> Result<(), Error>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

§

impl<'a> !Freeze for Signer<'a>

§

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

§

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

§

impl<'a> Send for Signer<'a>

§

impl<'a> Sync for Signer<'a>

§

impl<'a> Unpin for Signer<'a>

§

impl<'a> UnsafeUnpin for Signer<'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<W> ElfWrite for W
where W: Write + ?Sized,

Source§

fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Error>

Write all bytes. Read more
Source§

fn write_u8(&mut self, value: u8) -> Result<(), Error>

Write one byte as u8.
Source§

fn write_i8(&mut self, value: i8) -> Result<(), Error>

Write one byte as i8.
Source§

fn write_u16(&mut self, byte_order: ByteOrder, value: u16) -> Result<(), Error>

Write u16.
Source§

fn write_u32(&mut self, byte_order: ByteOrder, value: u32) -> Result<(), Error>

Write u32.
Source§

fn write_u64(&mut self, byte_order: ByteOrder, value: u64) -> Result<(), Error>

Write u64.
Source§

fn write_i16(&mut self, byte_order: ByteOrder, value: i16) -> Result<(), Error>

Write i16.
Source§

fn write_i32(&mut self, byte_order: ByteOrder, value: i32) -> Result<(), Error>

Write i32.
Source§

fn write_i64(&mut self, byte_order: ByteOrder, value: i64) -> Result<(), Error>

Write i64.
Source§

fn write_word( &mut self, class: Class, byte_order: ByteOrder, value: u64, ) -> Result<(), Error>

Write one word. Read more
Source§

fn write_word_as_u32( &mut self, class: Class, byte_order: ByteOrder, value: u32, ) -> Result<(), Error>

Write a word specified by value.
Source§

fn write_u32_as_u64( &mut self, byte_order: ByteOrder, value: u64, ) -> Result<(), Error>

Write value as u64.
Source§

fn write_i32_as_i64( &mut self, byte_order: ByteOrder, value: i64, ) -> Result<(), Error>

Write value as i32.
Source§

impl<T> ExecutableCommand for T
where T: Write + ?Sized,

Source§

fn execute(&mut self, command: impl Command) -> Result<&mut T, Error>

Executes the given command directly.

The given command its ANSI escape code will be written and flushed onto Self.

§Arguments
  • Command

    The command that you want to execute directly.

§Example
use std::io;
use crossterm::{ExecutableCommand, style::Print};

fn main() -> io::Result<()> {
     // will be executed directly
      io::stdout()
        .execute(Print("sum:\n".to_string()))?
        .execute(Print(format!("1 + 1= {} ", 1 + 1)))?;

      Ok(())

     // ==== Output ====
     // sum:
     // 1 + 1 = 2
}

Have a look over at the Command API for more details.

§Notes
  • In the case of UNIX and Windows 10, ANSI codes are written to the given ‘writer’.
  • In case of Windows versions lower than 10, a direct WinAPI call will be made. The reason for this is that Windows versions lower than 10 do not support ANSI codes, and can therefore not be written to the given writer. Therefore, there is no difference between execute and queue for those old Windows versions.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<W> LittleEndianWriteExt for W
where W: Write + ?Sized,

Source§

fn write_u16_le(&mut self, input: u16) -> Result<(), Error>

Source§

fn write_u32_le(&mut self, input: u32) -> Result<(), Error>

Source§

fn write_u64_le(&mut self, input: u64) -> Result<(), Error>

Source§

fn write_u128_le(&mut self, input: u128) -> Result<(), Error>

Source§

impl<T> MaybeSend for T

Source§

impl<T> MaybeSync for T

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> QueueableCommand for T
where T: Write + ?Sized,

Source§

fn queue(&mut self, command: impl Command) -> Result<&mut T, Error>

Queues the given command for further execution.

Queued commands will be executed in the following cases:

  • When flush is called manually on the given type implementing io::Write.
  • The terminal will flush automatically if the buffer is full.
  • Each line is flushed in case of stdout, because it is line buffered.
§Arguments
  • Command

    The command that you want to queue for later execution.

§Examples
use std::io::{self, Write};
use crossterm::{QueueableCommand, style::Print};

 fn main() -> io::Result<()> {
    let mut stdout = io::stdout();

    // `Print` will executed executed when `flush` is called.
    stdout
        .queue(Print("foo 1\n".to_string()))?
        .queue(Print("foo 2".to_string()))?;

    // some other code (no execution happening here) ...

    // when calling `flush` on `stdout`, all commands will be written to the stdout and therefore executed.
    stdout.flush()?;

    Ok(())

    // ==== Output ====
    // foo 1
    // foo 2
}

Have a look over at the Command API for more details.

§Notes
  • In the case of UNIX and Windows 10, ANSI codes are written to the given ‘writer’.
  • In case of Windows versions lower than 10, a direct WinAPI call will be made. The reason for this is that Windows versions lower than 10 do not support ANSI codes, and can therefore not be written to the given writer. Therefore, there is no difference between execute and queue for those old Windows versions.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<W> SynchronizedUpdate for W
where W: Write + ?Sized,

Source§

fn sync_update<T>( &mut self, operations: impl FnOnce(&mut W) -> T, ) -> Result<T, Error>

Performs a set of actions within a synchronous update.

Updates will be suspended in the terminal, the function will be executed against self, updates will be resumed, and a flush will be performed.

§Arguments
  • Function

    A function that performs the operations that must execute in a synchronized update.

§Examples
use std::io;
use crossterm::{ExecutableCommand, SynchronizedUpdate, style::Print};

fn main() -> io::Result<()> {
    let mut stdout = io::stdout();

    stdout.sync_update(|stdout| {
        stdout.execute(Print("foo 1\n".to_string()))?;
        stdout.execute(Print("foo 2".to_string()))?;
        // The effects of the print command will not be present in the terminal
        // buffer, but not visible in the terminal.
        std::io::Result::Ok(())
    })?;

    // The effects of the commands will be visible.

    Ok(())

    // ==== Output ====
    // foo 1
    // foo 2
}
§Notes

This command is performed only using ANSI codes, and will do nothing on terminals that do not support ANSI codes, or this specific extension.

When rendering the screen of the terminal, the Emulator usually iterates through each visible grid cell and renders its current state. With applications updating the screen a at higher frequency this can cause tearing.

This mode attempts to mitigate that.

When the synchronization mode is enabled following render calls will keep rendering the last rendered state. The terminal Emulator keeps processing incoming text and sequences. When the synchronized update mode is disabled again the renderer may fetch the latest screen buffer state again, effectively avoiding the tearing effect by unintentionally rendering in the middle a of an application screen update.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

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> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more