#![cfg(feature = "crypto")]
#![cfg_attr(docsrs, doc(cfg(feature = "crypto")))]
use std::fmt;
use aes_gcm::aead::Aead;
use aes_gcm::aes::cipher::consts::U12;
use aes_gcm::{Aes256Gcm, Nonce, KeyInit};
pub use ed25519_dalek::{SigningKey, VerifyingKey, Signature};
use crate::global::error::{InternalError, InternalResult};
pub(crate) struct Encryptor {
cipher: Aes256Gcm,
nonce: Nonce<U12>,
}
impl fmt::Debug for Encryptor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Encryptor")
.field("cipher", &"Aes256Gcm")
.field("nonce", &self.nonce)
.finish()
}
}
impl Encryptor {
pub(crate) fn new(vk: &VerifyingKey) -> Encryptor {
let bytes = &vk.to_bytes();
let mut v = [178, 5, 239, 228, 165, 44, 169, 0, 0, 0, 0, 0];
v[7..12].copy_from_slice(&crate::MAGIC);
Encryptor {
cipher: Aes256Gcm::new_from_slice(bytes).unwrap(),
nonce: *Nonce::from_slice(v.as_slice()),
}
}
pub(crate) fn encrypt(&self, data: &[u8]) -> InternalResult<Vec<u8>> {
self.cipher
.encrypt(&self.nonce, data)
.map_err(InternalError::CryptoError)
}
pub(crate) fn decrypt(&self, data: &[u8]) -> InternalResult<Vec<u8>> {
self.cipher
.decrypt(&self.nonce, data)
.map_err(InternalError::CryptoError)
}
}