summaryrefslogtreecommitdiff
path: root/src/openpgp/trusted.rs
blob: 6d118b3216d727669bb358cc0f05ab06eb725669 (plain)
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
use gpgme::{Context, Data, Key};
use std::fs::File;
use std::io::BufReader;
use std::path::Path;

pub enum ScanResult {
    Trusted,
    Unsigned,
    Untrusted,
}

pub trait OpenPGPOpertaions {
    fn get_trusted_keys(&self, keys: &[Key]) -> Vec<Key>;
    fn check_sign(
        &self,
        sig_path: &Path,
        context: &Context,
        file: &Path,
    ) -> Result<ScanResult, gpgme::Error>;
}

impl OpenPGPOpertaions for Key {
    fn get_trusted_keys(&self, keys: &[Key]) -> Vec<Key> {
        let mut trusted_keys = Vec::new();
        for key in keys {
            if key.can_encrypt() || key.can_sign() {
                trusted_keys.push(key.clone());
            }
        }
        trusted_keys
    }
    fn check_sign(
        &self,
        sig_path: &Path,
        _context: &Context,
        file: &Path,
    ) -> Result<ScanResult, gpgme::Error> {
        let mut ctx = Context::from_protocol(gpgme::Protocol::OpenPgp)?;

        let file_reader = BufReader::new(File::open(file)?);
        let sig_reader = BufReader::new(File::open(sig_path)?);
        let sig_data = Data::from_reader(sig_reader)
            .map_err(|e| gpgme::Error::from(std::io::Error::other(e)))?;
        let file_data = Data::from_reader(file_reader)
            .map_err(|e| gpgme::Error::from(std::io::Error::other(e)))?;

        let result = ctx.verify_detached(sig_data, file_data);

        if result.is_ok() {
            Ok(ScanResult::Trusted)
        } else {
            Ok(ScanResult::Unsigned)
        }
    }
}