use serde::{Deserialize, Serialize};
use crate::encoding::{from_b64u, to_b64u};
use crate::error::{Error, Result};
use super::identity::address_key_pair;
use super::primitives::{random_bytes, KEY_BYTES};
use super::sealedbox::{open_raw, seal_raw, RawSealedBox};
const MAGIC_V1: &[u8; 4] = b"MCA1";
const MAGIC_V2: &[u8; 4] = b"MCA2";
const ATTACHMENT_HEADER: usize = 4 + KEY_BYTES + 12 + 32;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsymmetricBox {
#[serde(default = "one")]
pub v: u8,
pub epk: String,
pub n: String,
pub c: String,
pub t: String,
}
fn one() -> u8 {
1
}
impl AsymmetricBox {
fn version(&self) -> u8 {
if self.v == 2 {
2
} else {
1
}
}
fn decode(&self) -> Result<RawSealedBox> {
Ok(RawSealedBox {
ephemeral_public_key: from_b64u(&self.epk).map_err(|_| Error::Decryption)?,
nonce: from_b64u(&self.n).map_err(|_| Error::Decryption)?,
ciphertext: from_b64u(&self.c).map_err(|_| Error::Decryption)?,
tag: from_b64u(&self.t).map_err(|_| Error::Decryption)?,
})
}
}
pub fn seal_to_public_key(
recipient_public_key: &[u8],
plaintext: &[u8],
aad: &str,
version: u8,
) -> Result<AsymmetricBox> {
let mut random = |length: usize| random_bytes(length);
let box_ = seal_raw(recipient_public_key, plaintext, aad.as_bytes(), &mut random, version)?;
Ok(AsymmetricBox {
v: version,
epk: to_b64u(&box_.ephemeral_public_key),
n: to_b64u(&box_.nonce),
c: to_b64u(&box_.ciphertext),
t: to_b64u(&box_.tag),
})
}
pub fn open_with_private_key(private_key: &[u8], box_: &AsymmetricBox, aad: &str) -> Result<Vec<u8>> {
open_raw(private_key, &box_.decode()?, aad.as_bytes(), box_.version())
}
pub fn open_json_with_private_key<T: serde::de::DeserializeOwned>(
private_key: &[u8],
box_: &AsymmetricBox,
aad: &str,
) -> Result<T> {
serde_json::from_slice(&open_with_private_key(private_key, box_, aad)?).map_err(|_| Error::Decryption)
}
pub fn open_inbound_mail(
vault_key: &[u8],
address_id: &str,
message_id: &str,
box_: &AsymmetricBox,
) -> Result<Vec<u8>> {
let (private_key, _) = address_key_pair(vault_key, address_id).ok_or(Error::Decryption)?;
open_with_private_key(&private_key, box_, &format!("{address_id}:{message_id}"))
}
pub fn open_attachment_with_key(
private_key: &[u8],
address_id: &str,
object_key: &str,
data: &[u8],
) -> Result<Vec<u8>> {
if data.len() < ATTACHMENT_HEADER {
return Err(Error::Decryption);
}
let version = match &data[..4] {
m if m == MAGIC_V1 => 1,
m if m == MAGIC_V2 => 2,
_ => return Err(Error::Decryption),
};
let box_ = RawSealedBox {
ephemeral_public_key: data[4..36].to_vec(),
nonce: data[36..48].to_vec(),
tag: data[48..80].to_vec(),
ciphertext: data[ATTACHMENT_HEADER..].to_vec(),
};
open_raw(private_key, &box_, format!("{address_id}:{object_key}").as_bytes(), version)
}
pub fn open_attachment(vault_key: &[u8], address_id: &str, object_key: &str, data: &[u8]) -> Result<Vec<u8>> {
let (private_key, _) = address_key_pair(vault_key, address_id).ok_or(Error::Decryption)?;
open_attachment_with_key(&private_key, address_id, object_key, data)
}