diff options
author | Justus Winter <justus@sequoia-pgp.org> | 2018-05-31 12:50:19 +0200 |
---|---|---|
committer | Justus Winter <justus@sequoia-pgp.org> | 2018-05-31 12:50:19 +0200 |
commit | 6ca5dcf8e52a282079dc8825f73c9b69f6d3e7e5 (patch) | |
tree | 516a6b604951bf7e2f4fe5f79695f601ec9fcd52 /openpgp/examples | |
parent | fd7d02ca8d49573940475625bf22e5ea63858ac6 (diff) |
openpgp: Improve and document encryption example.
- Encrypt to multiple recipients.
- Add comments.
Diffstat (limited to 'openpgp/examples')
-rw-r--r-- | openpgp/examples/encrypt-for.rs | 33 |
1 files changed, 26 insertions, 7 deletions
diff --git a/openpgp/examples/encrypt-for.rs b/openpgp/examples/encrypt-for.rs index 8d704296..fa5f81c1 100644 --- a/openpgp/examples/encrypt-for.rs +++ b/openpgp/examples/encrypt-for.rs @@ -1,3 +1,5 @@ +/// This program demonstrates how to encrypt a stream of data. + use std::env; use std::io; @@ -9,21 +11,38 @@ use openpgp::serialize::stream::{ fn main() { let args: Vec<String> = env::args().collect(); - if args.len() != 2 { + if args.len() < 2 { panic!("A simple encryption filter.\n\n\ - Usage: {} <keyfile> <input >output\n", args[0]); + Usage: {} <keyfile> [<keyfile>...] <input >output\n", args[0]); } - let keyfile = &args[1]; - let tpk = openpgp::TPK::from_reader( - openpgp::Reader::from_file(keyfile).expect("Failed to open file")) - .expect("Failed to read key"); + // Read the transferable public keys from the given files. + let tpks: Vec<openpgp::TPK> = args[1..].iter().map(|f| { + openpgp::TPK::from_reader( + // Use an openpgp::Reader so that we accept both armored + // and plain PGP data. + openpgp::Reader::from_file(f) + .expect("Failed to open file")) + .expect("Failed to read key") + }).collect(); + // Build a vector of references to hand to Encryptor. + let recipients: Vec<&openpgp::TPK> = tpks.iter().collect(); + + // Compose a writer stack corresponding to the output format and + // packet structure we want. First, we want the output to be as + // armored. let sink = armor::Writer::new(io::stdout(), armor::Kind::Message); - let encryptor = Encryptor::new(wrap(sink), &[], &[&tpk], + + // We want to encrypt a literal data packet. + let encryptor = Encryptor::new(wrap(sink), + &[], // No symmetric encryption. + &recipients, EncryptionMode::AtRest) .expect("Failed to create encryptor"); let mut literal_writer = LiteralWriter::new(encryptor, 't', None, 0) .expect("Failed to create literal writer"); + + // Finally, copy stdin to our writer stack to encrypt the data. io::copy(&mut io::stdin(), &mut literal_writer) .expect("Failed to encrypt"); } |