~gpanders/passage

ref: 849cef24e44e6b1979a78f9244c02a329a8ed634 passage/src/crypt.rs -rw-r--r-- 3.3 KiB
849cef24Gregory Anders Add uninstall target to Makefile 11 months ago
                                                                                
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use age::x25519::{Identity, Recipient};
use secrecy::Secret;
use std::io::prelude::*;
use std::iter;

use crate::error::Error;
use crate::input;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn encrypt_and_decrypt_with_keys() -> Result<(), Error> {
        let plaintext = "Hello world!";
        let key = Identity::generate();
        let pubkey = key.to_public();

        let encrypted = encrypt_with_keys(plaintext, &[pubkey])?;
        let decrypted = decrypt_with_key(&encrypted, &key)?;

        assert_eq!(decrypted, plaintext);

        Ok(())
    }

    #[test]
    fn encrypt_and_decrypt_with_passphrase() -> Result<(), Error> {
        let plaintext = "Testing encrypt_and_decrypt_with_passphrase";
        let passphrase = "correct horse battery staple";

        let encrypted = encrypt_with_passphrase(plaintext, passphrase)?;
        let decrypted = decrypt_with_passphrase(&encrypted, Some(passphrase))?;

        assert_eq!(decrypted, plaintext);

        Ok(())
    }
}

pub fn encrypt_with_passphrase(plaintext: &str, passphrase: &str) -> Result<Vec<u8>, Error> {
    let encryptor = age::Encryptor::with_user_passphrase(Secret::new(passphrase.to_owned()));
    let mut encrypted = vec![];
    let mut writer = encryptor.wrap_output(&mut encrypted)?;
    writer.write_all(plaintext.as_bytes())?;
    writer.finish()?;

    Ok(encrypted)
}

pub fn decrypt_with_passphrase(cypher: &[u8], passphrase: Option<&str>) -> Result<String, Error> {
    let decryptor = match age::Decryptor::new(cypher) {
        Ok(d) => match d {
            age::Decryptor::Passphrase(decryptor) => decryptor,
            _ => return Err(age::DecryptError::DecryptionFailed.into()),
        },
        _ => return Err(Error::KeyNotEncrypted),
    };

    let passphrase = match passphrase {
        Some(s) => s.to_owned(),
        None => input::read_secret("Passphrase", None)?,
    };

    let mut decrypted = vec![];
    let mut reader = decryptor.decrypt(&Secret::new(passphrase), None)?;
    reader.read_to_end(&mut decrypted)?;

    match String::from_utf8(decrypted) {
        Ok(e) => Ok(e),
        Err(_) => Err(age::DecryptError::DecryptionFailed.into()),
    }
}

pub fn encrypt_with_keys(plaintext: &str, recipients: &[Recipient]) -> Result<Vec<u8>, Error> {
    let encryptor = age::Encryptor::with_recipients(
        recipients
            .iter()
            .map(|r| Box::new(r.to_owned()) as Box<dyn age::Recipient>)
            .collect(),
    );

    let mut encrypted = vec![];
    let mut writer = encryptor.wrap_output(&mut encrypted)?;
    writer.write_all(plaintext.as_bytes())?;
    writer.finish()?;

    Ok(encrypted)
}

pub fn decrypt_with_key(cypher: &[u8], key: &Identity) -> Result<String, Error> {
    let decryptor = {
        match age::Decryptor::new(cypher) {
            Ok(d) => match d {
                age::Decryptor::Recipients(d) => d,
                _ => return Err(age::DecryptError::KeyDecryptionFailed.into()),
            },
            Err(e) => return Err(e.into()),
        }
    };

    let mut decrypted = vec![];
    let mut reader = decryptor.decrypt(iter::once(
        Box::new(key.to_owned()) as Box<dyn age::Identity>
    ))?;

    reader.read_to_end(&mut decrypted)?;

    match String::from_utf8(decrypted) {
        Ok(e) => Ok(e),
        Err(_) => Err(age::DecryptError::KeyDecryptionFailed.into()),
    }
}