add openpgp, dep oss rust

This commit is contained in:
2019-11-29 01:09:54 +08:00
parent 730b3b7728
commit 6891d4daf1
4 changed files with 191 additions and 12 deletions

65
src/pgp_util.rs Normal file
View File

@@ -0,0 +1,65 @@
extern crate sequoia_openpgp as openpgp;
use crate::openpgp::armor;
use std::{
fs::File,
io::{
Write,
BufWriter,
},
};
use rust_util::{
XResult,
new_box_error,
};
use openpgp::{
types::KeyFlags,
TPK,
parse::Parse,
serialize::stream::{
Recipient,
Message,
Encryptor,
LiteralWriter,
},
};
pub struct OpenPGPClient {
pub tpk: TPK,
}
impl OpenPGPClient {
pub fn from_file(file: &str) -> XResult<OpenPGPClient> {
Ok(OpenPGPClient{
tpk: TPK::from_file(std::path::Path::new(file))?,
})
}
pub fn from_bytes(bs: &[u8]) -> XResult<OpenPGPClient> {
Ok(OpenPGPClient{
tpk: TPK::from_bytes(&bs)?,
})
}
pub fn encrypt_file(&self, from_file: &str, to_file: &str, armor: bool) -> XResult<()> {
let recipient: Recipient = match self.tpk.keys_valid()
.key_flags(KeyFlags::default().set_encrypt_at_rest(true).set_encrypt_for_transport(true))
.map(|(_, _, key)| key.into())
.nth(0) {
None => return Err(new_box_error("Encryption key not found in TPK")),
Some(r) => r,
};
let message = if armor {
Message::new(armor::Writer::new(std::io::stdout(), armor::Kind::Message, &[])?)
} else {
Message::new(BufWriter::new(File::open(to_file)?))
};
let encryptor = Encryptor::for_recipient(message, recipient).build()?;
let mut pgp_encrypt_writer = LiteralWriter::new(encryptor).build()?;
// TODO read from from_file
pgp_encrypt_writer.write_all(b"Hello world.")?;
pgp_encrypt_writer.finalize()?;
Ok(())
}
}