File: encrypt.rs

package info (click to toggle)
rust-gpgme 0.11.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 552 kB
  • sloc: makefile: 2
file content (56 lines) | stat: -rw-r--r-- 1,378 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use structopt;

use gpgme::{Context, Protocol};
use std::{
    error::Error,
    fs::File,
    io::{self, prelude::*},
    path::PathBuf,
};
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
struct Cli {
    #[structopt(long)]
    /// Use the CMS protocol
    cms: bool,
    #[structopt(short, long = "recipient")]
    /// For whom to encrypt the messages
    recipients: Vec<String>,
    #[structopt(parse(from_os_str))]
    /// Files to encrypt
    filename: PathBuf,
}

fn main() -> Result<(), Box<dyn Error>> {
    let args = Cli::from_args();
    let proto = if args.cms {
        Protocol::Cms
    } else {
        Protocol::OpenPgp
    };

    let mut ctx = Context::from_protocol(proto)?;
    ctx.set_armor(true);

    let keys = if !args.recipients.is_empty() {
        ctx.find_keys(args.recipients)?
            .filter_map(|x| x.ok())
            .filter(|k| k.can_encrypt())
            .collect()
    } else {
        Vec::new()
    };

    let filename = &args.filename;
    let mut input = File::open(&args.filename)
        .map_err(|e| format!("can't open file `{}': {:?}", filename.display(), e))?;
    let mut output = Vec::new();
    ctx.encrypt(&keys, &mut input, &mut output)
        .map_err(|e| format!("encrypting failed: {:?}", e))?;

    println!("Begin Output:");
    io::stdout().write_all(&output)?;
    println!("End Output.");
    Ok(())
}