use base64::engine::general_purpose::{STANDARD, URL_SAFE};
use base64::Engine;
use serde::{Deserialize, Serialize};
use crate::error::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Signature {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub keyid: Option<String>,
pub sig: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Envelope {
pub payload: String,
#[serde(rename = "payloadType")]
pub payload_type: String,
pub signatures: Vec<Signature>,
}
impl Envelope {
pub fn from_json(bytes: &[u8]) -> Result<Self> {
serde_json::from_slice(bytes).map_err(|e| Error::MalformedEnvelope(e.to_string()))
}
pub fn to_json(&self) -> Result<Vec<u8>> {
serde_json::to_vec(self).map_err(|e| Error::MalformedEnvelope(e.to_string()))
}
}
pub(crate) fn decode_b64(s: &str, field: &'static str) -> Result<Vec<u8>> {
if let Ok(v) = STANDARD.decode(s) {
return Ok(v);
}
if let Ok(v) = URL_SAFE.decode(s) {
return Ok(v);
}
Err(Error::NonCanonicalBase64 { field })
}
pub(crate) fn encode_b64(b: &[u8]) -> String {
STANDARD.encode(b)
}