30 lines
1.1 KiB
Rust
30 lines
1.1 KiB
Rust
use eyre::Result;
|
|
use pgp::crypto::sym::SymmetricKeyAlgorithm;
|
|
use pgp::ser::Serialize;
|
|
use pgp::{Deserializable, Message, SignedPublicKey, SignedSecretKey};
|
|
use rand::prelude::*;
|
|
|
|
pub fn encrypt(key: &SignedPublicKey, message: &str) -> Result<Vec<u8>, pgp::errors::Error> {
|
|
let message = Message::new_literal("none", message);
|
|
let mut rng = StdRng::from_entropy();
|
|
|
|
let message = message.encrypt_to_keys(&mut rng, SymmetricKeyAlgorithm::AES128, &[key])?;
|
|
|
|
Ok(message.to_bytes()?)
|
|
}
|
|
|
|
pub fn decrypt<'a>(
|
|
key: &'a SignedSecretKey,
|
|
message: &[u8],
|
|
password: &'a str,
|
|
) -> Result<String, pgp::errors::Error> {
|
|
let message = Message::from_bytes(message)?; // Convert message bytes to message object
|
|
let message = message.decrypt(|| password.to_string(), &[key])?.0; // Decrypt
|
|
let message = message.map(|x| x.unwrap()).collect::<Vec<Message>>(); // Get all messages
|
|
let message = &message[0]; // Get first message
|
|
let message = message.get_content()?.unwrap_or(Vec::new()); // Get message content as Vec<u8>
|
|
let message = String::from_utf8(message).unwrap(); // Convert to String
|
|
|
|
Ok(message)
|
|
}
|