use crate::secure_stream::serialize::serialize;
use serde::{Deserialize, Serialize};
use sodiumoxide::crypto::box_::{PublicKey, PUBLICKEYBYTES};
use sodiumoxide::crypto::sealedbox;
use crate::secure_stream::crypto::error::EncryptionError;
use std::fmt;
#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Clone)]
pub struct PublicEncryptKey {
pub(crate) inner: PublicKey,
}
impl PublicEncryptKey {
pub fn from_bytes(public_key: [u8; PUBLICKEYBYTES]) -> Self {
Self {
inner: PublicKey(public_key),
}
}
pub fn into_bytes(self) -> [u8; PUBLICKEYBYTES] {
self.inner.0
}
pub fn anonymously_encrypt<T: Serialize>(
&self,
plaintext: &T,
) -> Result<Vec<u8>, EncryptionError> {
Ok(self.anonymously_encrypt_bytes(&serialize(plaintext)?))
}
pub fn anonymously_encrypt_bytes(&self, plaintext: &[u8]) -> Vec<u8> {
sealedbox::seal(plaintext, &self.inner)
}
}
impl fmt::Display for PublicEncryptKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{:02x}{:02x}{:02x}..",
&self.inner.0[0], &self.inner.0[1], &self.inner.0[2]
)
}
}