false-bottom/src/fbkey.rs

57 lines
1.5 KiB
Rust

// SPDX-License-Identifier: GPL-3.0-or-later
use crate::FbError;
use bincode::{Options, DefaultOptions};
#[cfg(feature = "base64")]
use base64::prelude::{BASE64_STANDARD, Engine};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// An object that represents a message specific key.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FbKey(pub(crate) Vec<Vec<(usize, usize)>>);
impl FbKey {
/// Returns the byte representation of the message specific key.
pub fn to_bytes(&self) -> Vec<u8> {
let binc = DefaultOptions::new();
binc.serialize(&self.0)
.expect("Should be fine")
}
/// Constructs the message specific key from the provided bytes.
/// # Errors
/// [DecodeError](FbError::DecodeError)
pub fn from_bytes(fbkey: &[u8]) -> Result<FbKey, FbError> {
let binc = DefaultOptions::new();
let indices: Vec<_> = binc.deserialize(&fbkey)
.map_err(|_| FbError::DecodeError)?;
if indices.len() < 2 {
return Err(FbError::DecodeError);
}
Ok (FbKey(indices))
}
/// Returns the base64 encoded representation of the message specific key.
#[cfg(feature = "base64")]
pub fn to_base64(&self) -> String {
BASE64_STANDARD.encode(&self.to_bytes())
}
/// Constructs the message specific key from the provided base64 encoded form.
/// # Errors
/// [DecodeError](FbError::DecodeError)
#[cfg(feature = "base64")]
pub fn from_base64(key_str: &str) -> Result<FbKey, FbError> {
let indice_bytes = BASE64_STANDARD.decode(key_str)
.map_err(|_| FbError::DecodeError)?;
Self::from_bytes(&indice_bytes)
}
}