use serde::{Deserialize, Serialize};
use crate::encoding::{be64, from_b64u, to_b64u};
use crate::error::{Error, Result};
use super::primitives::{chacha20, constant_time_equal, hmac_sha256, random_bytes, NONCE_BYTES};
pub const SEAL_VERSION: u8 = 2;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SealedBox {
#[serde(default = "one")]
pub v: u8,
pub n: String,
pub c: String,
pub t: String,
}
fn one() -> u8 {
1
}
impl SealedBox {
fn version(&self) -> u8 {
if self.v == 2 {
2
} else {
1
}
}
}
pub fn derive_subkeys(secret: &[u8]) -> Result<(&[u8], &[u8])> {
if secret.len() != 64 {
return Err(Error::Decryption);
}
Ok((&secret[..32], &secret[32..]))
}
pub fn mac_input(nonce: &[u8], ciphertext: &[u8], aad: &[u8], version: u8) -> Vec<u8> {
let mut out = Vec::with_capacity(nonce.len() + ciphertext.len() + aad.len() + 8);
out.extend_from_slice(nonce);
out.extend_from_slice(ciphertext);
out.extend_from_slice(aad);
if version != 1 {
out.extend_from_slice(&be64(aad.len()));
}
out
}
pub fn seal(secret: &[u8], plaintext: &[u8], aad: &str, version: u8) -> Result<SealedBox> {
let (encryption, mac) = derive_subkeys(secret)?;
let nonce = random_bytes(NONCE_BYTES);
let ciphertext = chacha20(encryption, &nonce, plaintext);
let tag = hmac_sha256(mac, &mac_input(&nonce, &ciphertext, aad.as_bytes(), version));
Ok(SealedBox { v: version, n: to_b64u(&nonce), c: to_b64u(&ciphertext), t: to_b64u(&tag) })
}
pub fn open(secret: &[u8], box_: &SealedBox, aad: &str) -> Result<Vec<u8>> {
let (encryption, mac) = derive_subkeys(secret)?;
let nonce = from_b64u(&box_.n).map_err(|_| Error::Decryption)?;
let ciphertext = from_b64u(&box_.c).map_err(|_| Error::Decryption)?;
let tag = from_b64u(&box_.t).map_err(|_| Error::Decryption)?;
if nonce.len() != NONCE_BYTES {
return Err(Error::Decryption);
}
let expected = hmac_sha256(mac, &mac_input(&nonce, &ciphertext, aad.as_bytes(), box_.version()));
if !constant_time_equal(&expected, &tag) {
return Err(Error::Decryption);
}
Ok(chacha20(encryption, &nonce, &ciphertext))
}
pub fn seal_json<T: Serialize>(secret: &[u8], value: &T, aad: &str, version: u8) -> Result<SealedBox> {
let text = serde_json::to_vec(value).map_err(|_| Error::Decryption)?;
seal(secret, &text, aad, version)
}
pub fn open_json<T: serde::de::DeserializeOwned>(secret: &[u8], box_: &SealedBox, aad: &str) -> Result<T> {
serde_json::from_slice(&open(secret, box_, aad)?).map_err(|_| Error::Decryption)
}