diff options
author | Wiktor Kwapisiewicz <wiktor@metacode.biz> | 2020-09-18 10:10:39 +0200 |
---|---|---|
committer | Wiktor Kwapisiewicz <wiktor@metacode.biz> | 2020-09-21 09:33:19 +0200 |
commit | 1ef1c3fbaf97f8b4470024ae1f681b2534af9ed5 (patch) | |
tree | bcc36a44cf218ab12b9921f11cf89509a37a7e34 /openpgp | |
parent | ba79017328ce7dc444ee05a83f3a04f4f6ba9310 (diff) |
openpgp: Adjust examples to use try operator.
- Change `expect` to `context(...)?`,
- Change `unwrap` to `?`.
Diffstat (limited to 'openpgp')
-rw-r--r-- | openpgp/examples/decrypt-with.rs | 18 | ||||
-rw-r--r-- | openpgp/examples/encrypt-for.rs | 30 | ||||
-rw-r--r-- | openpgp/examples/generate-encrypt-decrypt.rs | 12 | ||||
-rw-r--r-- | openpgp/examples/generate-sign-verify.rs | 10 | ||||
-rw-r--r-- | openpgp/examples/notarize.rs | 50 | ||||
-rw-r--r-- | openpgp/examples/pad.rs | 31 | ||||
-rw-r--r-- | openpgp/examples/sign-detached.rs | 33 | ||||
-rw-r--r-- | openpgp/examples/sign.rs | 34 | ||||
-rw-r--r-- | openpgp/examples/statistics.rs | 17 | ||||
-rw-r--r-- | openpgp/examples/web-of-trust.rs | 16 | ||||
-rw-r--r-- | openpgp/examples/wrap-literal.rs | 20 |
11 files changed, 156 insertions, 115 deletions
diff --git a/openpgp/examples/decrypt-with.rs b/openpgp/examples/decrypt-with.rs index f50d2102..fdda1cea 100644 --- a/openpgp/examples/decrypt-with.rs +++ b/openpgp/examples/decrypt-with.rs @@ -5,6 +5,8 @@ use std::collections::HashMap; use std::env; use std::io; +use anyhow::Context; + extern crate sequoia_openpgp as openpgp; use crate::openpgp::cert::prelude::*; @@ -24,30 +26,32 @@ use crate::openpgp::parse::{ use crate::openpgp::policy::Policy; use crate::openpgp::policy::StandardPolicy as P; -pub fn main() { +pub fn main() -> openpgp::Result<()> { let p = &P::new(); let args: Vec<String> = env::args().collect(); if args.len() < 2 { - panic!("A simple decryption filter.\n\n\ - Usage: {} <keyfile> [<keyfile>...] <input >output\n", args[0]); + return Err(anyhow::anyhow!("A simple decryption filter.\n\n\ + Usage: {} <keyfile> [<keyfile>...] <input >output\n", args[0])); } // Read the transferable secret keys from the given files. let certs = args[1..].iter().map(|f| { openpgp::Cert::from_file(f) - .expect("Failed to read key") - }).collect(); + }).collect::<openpgp::Result<Vec<_>>>() + .context("Failed to read key")?; // Now, create a decryptor with a helper using the given Certs. let mut decryptor = DecryptorBuilder::from_reader(io::stdin()).unwrap() - .with_policy(p, None, Helper::new(p, certs)).unwrap(); + .with_policy(p, None, Helper::new(p, certs))?; // Finally, stream the decrypted data to stdout. io::copy(&mut decryptor, &mut io::stdout()) - .expect("Decryption failed"); + .context("Decryption failed")?; + + Ok(()) } /// This helper provides secrets for the decryption, fetches public diff --git a/openpgp/examples/encrypt-for.rs b/openpgp/examples/encrypt-for.rs index 80fe52e5..28f63934 100644 --- a/openpgp/examples/encrypt-for.rs +++ b/openpgp/examples/encrypt-for.rs @@ -4,6 +4,8 @@ use std::env; use std::io; +use anyhow::Context; + extern crate sequoia_openpgp as openpgp; use crate::openpgp::armor; use crate::openpgp::types::KeyFlags; @@ -13,29 +15,29 @@ use crate::openpgp::serialize::stream::{ }; use crate::openpgp::policy::StandardPolicy as P; -fn main() { +fn main() -> openpgp::Result<()> { let p = &P::new(); let args: Vec<String> = env::args().collect(); if args.len() < 3 { - panic!("A simple encryption filter.\n\n\ + return Err(anyhow::anyhow!("A simple encryption filter.\n\n\ Usage: {} [at-rest|for-transport] <keyfile> [<keyfile>...] \ - <input >output\n", args[0]); + <input >output\n", args[0])); } let mode = match args[1].as_ref() { "at-rest" => KeyFlags::empty().set_storage_encryption(), "for-transport" => KeyFlags::empty().set_transport_encryption(), - x => panic!("invalid mode: {:?}, \ + x => return Err(anyhow::anyhow!("invalid mode: {:?}, \ must be either 'at-rest' or 'for-transport'", - x), + x)), }; // Read the certificates from the given files. let certs: Vec<openpgp::Cert> = args[2..].iter().map(|f| { openpgp::Cert::from_file(f) - .expect("Failed to read key") - }).collect(); + }).collect::<openpgp::Result<Vec<_>>>() + .context("Failed to read key")?; let recipients = certs.iter() @@ -48,27 +50,29 @@ fn main() { // packet structure we want. First, we want the output to be // ASCII armored. let mut sink = armor::Writer::new(io::stdout(), armor::Kind::Message) - .expect("Failed to create an armored writer"); + .context("Failed to create an armored writer")?; // Stream an OpenPGP message. let message = Message::new(&mut sink); // We want to encrypt a literal data packet. let encryptor = Encryptor::for_recipients(message, recipients) - .build().expect("Failed to create encryptor"); + .build().context("Failed to create encryptor")?; let mut literal_writer = LiteralWriter::new(encryptor).build() - .expect("Failed to create literal writer"); + .context("Failed to create literal writer")?; // Copy stdin to our writer stack to encrypt the data. io::copy(&mut io::stdin(), &mut literal_writer) - .expect("Failed to encrypt"); + .context("Failed to encrypt")?; // Finally, finalize the OpenPGP message by tearing down the // writer stack. - literal_writer.finalize().unwrap(); + literal_writer.finalize()?; // Finalize the armor writer. sink.finalize() - .expect("Failed to write data"); + .context("Failed to write data")?; + + Ok(()) } diff --git a/openpgp/examples/generate-encrypt-decrypt.rs b/openpgp/examples/generate-encrypt-decrypt.rs index 3a02f264..1b1e267b 100644 --- a/openpgp/examples/generate-encrypt-decrypt.rs +++ b/openpgp/examples/generate-encrypt-decrypt.rs @@ -13,21 +13,23 @@ use crate::openpgp::policy::StandardPolicy as P; const MESSAGE: &'static str = "дружба"; -fn main() { +fn main() -> openpgp::Result<()> { let p = &P::new(); // Generate a key. - let key = generate().unwrap(); + let key = generate()?; // Encrypt the message. let mut ciphertext = Vec::new(); - encrypt(p, &mut ciphertext, MESSAGE, &key).unwrap(); + encrypt(p, &mut ciphertext, MESSAGE, &key)?; // Decrypt the message. let mut plaintext = Vec::new(); - decrypt(p, &mut plaintext, &ciphertext, &key).unwrap(); + decrypt(p, &mut plaintext, &ciphertext, &key)?; assert_eq!(MESSAGE.as_bytes(), &plaintext[..]); + + Ok(()) } /// Generates an encryption-capable key. @@ -125,7 +127,7 @@ impl<'a> DecryptionHelper for Helper<'a> { .for_transport_encryption().nth(0).unwrap().key().clone(); // The secret key is not encrypted. - let mut pair = key.into_keypair().unwrap(); + let mut pair = key.into_keypair()?; pkesks[0].decrypt(&mut pair, sym_algo) .map(|(algo, session_key)| decrypt(algo, &session_key)); diff --git a/openpgp/examples/generate-sign-verify.rs b/openpgp/examples/generate-sign-verify.rs index f638b075..4517f8dc 100644 --- a/openpgp/examples/generate-sign-verify.rs +++ b/openpgp/examples/generate-sign-verify.rs @@ -11,21 +11,23 @@ use crate::openpgp::policy::StandardPolicy as P; const MESSAGE: &'static str = "дружба"; -fn main() { +fn main() -> openpgp::Result<()> { let p = &P::new(); // Generate a key. - let key = generate().unwrap(); + let key = generate()?; // Sign the message. let mut signed_message = Vec::new(); - sign(p, &mut signed_message, MESSAGE, &key).unwrap(); + sign(p, &mut signed_message, MESSAGE, &key)?; // Verify the message. let mut plaintext = Vec::new(); - verify(p, &mut plaintext, &signed_message, &key).unwrap(); + verify(p, &mut plaintext, &signed_message, &key)?; assert_eq!(MESSAGE.as_bytes(), &plaintext[..]); + + Ok(()) } /// Generates an signing-capable key. diff --git a/openpgp/examples/notarize.rs b/openpgp/examples/notarize.rs index d4243f2c..1e4939c6 100644 --- a/openpgp/examples/notarize.rs +++ b/openpgp/examples/notarize.rs @@ -4,6 +4,8 @@ use std::env; use std::io; +use anyhow::Context; + extern crate sequoia_openpgp as openpgp; use crate::openpgp::{ armor, @@ -14,20 +16,20 @@ use crate::openpgp::{ use crate::openpgp::serialize::stream::{Message, LiteralWriter, Signer}; use crate::openpgp::policy::StandardPolicy as P; -fn main() { +fn main() -> openpgp::Result<()> { let p = &P::new(); let args: Vec<String> = env::args().collect(); if args.len() < 2 { - panic!("A simple notarizing filter.\n\n\ + return Err(anyhow::anyhow!("A simple notarizing filter.\n\n\ Usage: {} <secret-keyfile> [<secret-keyfile>...] \ - <input >output\n", args[0]); + <input >output\n", args[0])); } // Read the transferable secret keys from the given files. let mut keys = Vec::new(); for filename in &args[1..] { let tsk = openpgp::Cert::from_file(filename) - .expect("Failed to read key"); + .context("Failed to read key")?; let mut n = 0; for key in tsk.keys() @@ -39,19 +41,19 @@ fn main() { if key.secret().is_encrypted() { let password = rpassword::read_password_from_tty( Some(&format!("Please enter password to decrypt \ - {}/{}: ",tsk, key))).unwrap(); + {}/{}: ",tsk, key)))?; let algo = key.pk_algo(); key.secret_mut() .decrypt_in_place(algo, &password.into()) - .expect("decryption failed"); + .context("decryption failed")?; } n += 1; - key.into_keypair().unwrap() + key.into_keypair()? }); } if n == 0 { - panic!("Found no suitable signing key on {}", tsk); + return Err(anyhow::anyhow!("Found no suitable signing key on {}", tsk)); } } @@ -59,60 +61,60 @@ fn main() { // packet structure we want. First, we want the output to be // ASCII armored. let mut sink = armor::Writer::new(io::stdout(), armor::Kind::Message) - .expect("Failed to create an armored writer."); + .context("Failed to create an armored writer.")?; // Stream an OpenPGP message. let message = Message::new(&mut sink); // Now, create a signer that emits the signature(s). let mut signer = - Signer::new(message, keys.pop().expect("No key for signing")); + Signer::new(message, keys.pop().context("No key for signing")?); for s in keys { signer = signer.add_signer(s); } - let mut signer = signer.build().expect("Failed to create signer"); + let mut signer = signer.build().context("Failed to create signer")?; // Create a parser for the message to be notarized. let mut input = io::stdin(); let mut ppr = openpgp::parse::PacketParser::from_reader(&mut input) - .expect("Failed to build parser"); + .context("Failed to build parser")?; while let PacketParserResult::Some(mut pp) = ppr { if let Err(err) = pp.possible_message() { - panic!("Malformed OpenPGP message: {}", err); + return Err(anyhow::anyhow!("Malformed OpenPGP message: {}", err)); } match pp.packet { Packet::PKESK(_) | Packet::SKESK(_) => - panic!("Encrypted messages are not supported"), + return Err(anyhow::anyhow!("Encrypted messages are not supported")), Packet::OnePassSig(ref ops) => - ops.serialize(&mut signer).expect("Failed to serialize"), + ops.serialize(&mut signer).context("Failed to serialize")?, Packet::Literal(_) => { // Then, create a literal writer to wrap the data in a // literal message packet. let mut literal = LiteralWriter::new(signer).build() - .expect("Failed to create literal writer"); + .context("Failed to create literal writer")?; // Copy all the data. io::copy(&mut pp, &mut literal) - .expect("Failed to sign data"); + .context("Failed to sign data")?; signer = literal.finalize_one() - .expect("Failed to sign data") + .context("Failed to sign data")? .unwrap(); }, Packet::Signature(ref sig) => - sig.serialize(&mut signer).expect("Failed to serialize"), + sig.serialize(&mut signer).context("Failed to serialize")?, _ => (), } - ppr = pp.recurse().expect("Failed to recurse").1; + ppr = pp.recurse().context("Failed to recurse")?.1; } if let PacketParserResult::EOF(eof) = ppr { if let Err(err) = eof.is_message() { - panic!("Malformed OpenPGP message: {}", err) + return Err(anyhow::anyhow!("Malformed OpenPGP message: {}", err)); } } else { unreachable!() @@ -120,9 +122,11 @@ fn main() { // Finally, teardown the stack to ensure all the data is written. signer.finalize() - .expect("Failed to write data"); + .context("Failed to write data")?; // Finalize the armor writer. sink.finalize() - .expect("Failed to write data"); + .context("Failed to write data")?; + + Ok(()) } diff --git a/openpgp/examples/pad.rs b/openpgp/examples/pad.rs index 5d31d969..825d7758 100644 --- a/openpgp/examples/pad.rs +++ b/openpgp/examples/pad.rs @@ -4,6 +4,8 @@ use std::env; use std::io; +use anyhow::Context; + extern crate sequoia_openpgp as openpgp; use crate::openpgp::armor; use crate::openpgp::KeyID; @@ -14,28 +16,27 @@ use crate::openpgp::serialize::stream::{ }; use crate::openpgp::policy::StandardPolicy as P; -fn main() { +fn main() -> openpgp::Result<()> { let p = &P::new(); let args: Vec<String> = env::args().collect(); if args.len() < 3 { - panic!("A simple encryption filter.\n\n\ + return Err(anyhow::anyhow!("A simple encryption filter.\n\n\ Usage: {} [at-rest|for-transport] <keyfile> [<keyfile>...] \ - <input >output\n", args[0]); + <input >output\n", args[0])); } let mode = match args[1].as_ref() { "at-rest" => KeyFlags::empty().set_storage_encryption(), "for-transport" => KeyFlags::empty().set_transport_encryption(), - x => panic!("invalid mode: {:?}, \ + x => return Err(anyhow::anyhow!("invalid mode: {:?}, \ must be either 'at-rest' or 'for-transport'", - x), + x)), }; // Read the certificates from the given files. let certs: Vec<openpgp::Cert> = args[2..].iter().map(|f| { openpgp::Cert::from_file(f) - .expect("Failed to read key") - }).collect(); + }).collect::<openpgp::Result<Vec<_>>>().context("Failed to read key")?; // Build a vector of recipients to hand to Encryptor. let recipients = certs @@ -51,30 +52,32 @@ fn main() { // packet structure we want. First, we want the output to be // ASCII armored. let mut sink = armor::Writer::new(io::stdout(), armor::Kind::Message) - .expect("Failed to create an armored writer"); + .context("Failed to create an armored writer")?; // Stream an OpenPGP message. let message = Message::new(&mut sink); // We want to encrypt a literal data packet. let encryptor = Encryptor::for_recipients(message, recipients) - .build().expect("Failed to create encryptor"); + .build().context("Failed to create encryptor")?; let padder = Padder::new(encryptor, padme) - .expect("Failed to create padder"); + .context("Failed to create padder")?; let mut literal_writer = LiteralWriter::new(padder).build() - .expect("Failed to create literal writer"); + .context("Failed to create literal writer")?; // Copy stdin to our writer stack to encrypt the data. io::copy(&mut io::stdin(), &mut literal_writer) - .expect("Failed to encrypt"); + .context("Failed to encrypt")?; // Finally, finalize the OpenPGP message by tearing down the // writer stack. - literal_writer.finalize().unwrap(); + literal_writer.finalize()?; // Finalize the armor writer. sink.finalize() - .expect("Failed to write data"); + .context("Failed to write data")?; + + Ok(()) } diff --git a/openpgp/examples/sign-detached.rs b/openpgp/examples/sign-detached.rs index 30da708b..f16b1e93 100644 --- a/openpgp/examples/sign-detached.rs +++ b/openpgp/examples/sign-detached.rs @@ -2,6 +2,9 @@ use std::env; use std::io; + +use anyhow::Context; + extern crate rpassword; extern crate sequoia_openpgp as openpgp; @@ -10,20 +13,20 @@ use crate::openpgp::parse::Parse; use crate::openpgp::serialize::stream::{Message, Signer}; use crate::openpgp::policy::StandardPolicy as P; -fn main() { +fn main() -> openpgp::Result<()> { let p = &P::new(); let args: Vec<String> = env::args().collect(); if args.len() < 2 { - panic!("A simple filter creating a detached signature.\n\n\ + return Err(anyhow::anyhow!("A simple filter creating a detached signature.\n\n\ Usage: {} <secret-keyfile> [<secret-keyfile>...] \ - <input >output\n", args[0]); + <input >output\n", args[0])); } // Read the transferable secret keys from the given files. let mut keys = Vec::new(); for filename in &args[1..] { let tsk = openpgp::Cert::from_file(filename) - .expect("Failed to read key"); + .context("Failed to read key")?; let mut n = 0; for key in tsk @@ -35,19 +38,19 @@ fn main() { if key.secret().is_encrypted() { let password = rpassword::read_password_from_tty( Some(&format!("Please enter password to decrypt \ - {}/{}: ",tsk, key))).unwrap(); + {}/{}: ",tsk, key)))?; let algo = key.pk_algo(); key.secret_mut() .decrypt_in_place(algo, &password.into()) - .expect("decryption failed"); + .context("decryption failed")?; } n += 1; - key.into_keypair().unwrap() + key.into_keypair()? }); } if n == 0 { - panic!("Found no suitable signing key on {}", tsk); + return Err(anyhow::anyhow!("Found no suitable signing key on {}", tsk)); } } @@ -55,29 +58,31 @@ fn main() { // packet structure we want. First, we want the output to be // ASCII armored. let mut sink = armor::Writer::new(io::stdout(), armor::Kind::Signature) - .expect("Failed to create armored writer."); + .context("Failed to create armored writer.")?; // Stream an OpenPGP message. let message = Message::new(&mut sink); // Now, create a signer that emits the detached signature(s). let mut signer = - Signer::new(message, keys.pop().expect("No key for signing")); + Signer::new(message, keys.pop().context("No key for signing")?); for s in keys { signer = signer.add_signer(s); } let mut signer = - signer.detached().build().expect("Failed to create signer"); + signer.detached().build().context("Failed to create signer")?; // Copy all the data. io::copy(&mut io::stdin(), &mut signer) - .expect("Failed to sign data"); + .context("Failed to sign data")?; // Finally, teardown the stack to ensure all the data is written. signer.finalize() - .expect("Failed to write data"); + .context("Failed to write data")?; // Finalize the armor writer. sink.finalize() - .expect("Failed to write data"); + .context("Failed to write data")?; + + Ok(()) } diff --git a/openpgp/examples/sign.rs b/openpgp/examples/sign.rs index cb50a0bf..cee74940 100644 --- a/openpgp/examples/sign.rs +++ b/openpgp/examples/sign.rs @@ -3,26 +3,28 @@ use std::env; use std::io; +use anyhow::Context; + extern crate sequoia_openpgp as openpgp; use crate::openpgp::armor; use crate::openpgp::parse::Parse; use crate::openpgp::serialize::stream::{Message, LiteralWriter, Signer}; use crate::openpgp::policy::StandardPolicy as P; -fn main() { +fn main() -> openpgp::Result<()> { let p = &P::new(); let args: Vec<String> = env::args().collect(); if args.len() < 2 { - panic!("A simple signing filter.\n\n\ + return Err(anyhow::anyhow!("A simple signing filter.\n\n\ Usage: {} <secret-keyfile> [<secret-keyfile>...] \ - <input >output\n", args[0]); + <input >output\n", args[0])); } // Read the transferable secret keys from the given files. let mut keys = Vec::new(); for filename in &args[1..] { let tsk = openpgp::Cert::from_file(filename) - .expect("Failed to read key"); + .context("Failed to read key")?; let mut n = 0; for key in tsk.keys() @@ -34,19 +36,19 @@ fn main() { if key.secret().is_encrypted() { let password = rpassword::read_password_from_tty( Some(&format!("Please enter password to decrypt \ - {}/{}: ",tsk, key))).unwrap(); + {}/{}: ",tsk, key)))?; let algo = key.pk_algo(); key.secret_mut() .decrypt_in_place(algo, &password.into()) - .expect("decryption failed"); + .context("decryption failed")?; } n += 1; - key.into_keypair().unwrap() + key.into_keypair()? }); } if n == 0 { - panic!("Found no suitable signing key on {}", tsk); + return Err(anyhow::anyhow!("Found no suitable signing key on {}", tsk)); } } @@ -54,33 +56,35 @@ fn main() { // packet structure we want. First, we want the output to be // ASCII armored. let mut sink = armor::Writer::new(io::stdout(), armor::Kind::Message) - .expect("Failed to create an armored writer."); + .context("Failed to create an armored writer.")?; // Stream an OpenPGP message. let message = Message::new(&mut sink); // Now, create a signer that emits the signature(s). let mut signer = - Signer::new(message, keys.pop().expect("No key for signing")); + Signer::new(message, keys.pop().context("No key for signing")?); for s in keys { signer = signer.add_signer(s); } - let signer = signer.build().expect("Failed to create signer"); + let signer = signer.build().context("Failed to create signer")?; // Then, create a literal writer to wrap the data in a literal // message packet. let mut literal = LiteralWriter::new(signer).build() - .expect("Failed to create literal writer"); + .context("Failed to create literal writer")?; // Copy all the data. io::copy(&mut io::stdin(), &mut literal) - .expect("Failed to sign data"); + .context("Failed to sign data")?; // Finally, teardown the stack to ensure all the data is written. literal.finalize() - .expect("Failed to write data"); + .context("Failed to write data")?; // Finalize the armor writer. sink.finalize() - .expect("Failed to write data"); + .context("Failed to write data")?; + + Ok(()) } diff --git a/openpgp/examples/statistics.rs b/openpgp/examples/statistics.rs index cd2267ba..57117808 100644 --- a/openpgp/examples/statistics.rs +++ b/openpgp/examples/statistics.rs @@ -9,6 +9,9 @@ use std::env; use std::collections::HashMap; + +use anyhow::Context; + extern crate sequoia_openpgp as openpgp; use crate::openpgp::{Packet, Fingerprint, KeyID, KeyHandle}; use crate::openpgp::types::*; @@ -17,11 +20,11 @@ use crate::openpgp::packet::signature::subpacket::SubpacketTag; use crate::openpgp::parse::{Parse, PacketParserResult, PacketParser}; use crate::openpgp::serialize::MarshalInto; -fn main() { +fn main() -> openpgp::Result<()> { let args: Vec<String> = env::args().collect(); if args.len() < 2 { - panic!("Collects statistics about OpenPGP packet dumps.\n\n\ - Usage: {} & |