const BASE64_ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#[must_use]
pub fn base64_encode(data: &[u8]) -> String {
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
let (chunks, remainder) = data.as_chunks::<3>();
for &[b0, b1, b2] in chunks {
out.push(BASE64_ALPHABET[(b0 >> 2) as usize] as char);
out.push(BASE64_ALPHABET[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
out.push(BASE64_ALPHABET[(((b1 & 0x0f) << 2) | (b2 >> 6)) as usize] as char);
out.push(BASE64_ALPHABET[(b2 & 0x3f) as usize] as char);
}
match remainder.len() {
1 => {
let b0 = remainder[0];
out.push(BASE64_ALPHABET[(b0 >> 2) as usize] as char);
out.push(BASE64_ALPHABET[((b0 & 0x03) << 4) as usize] as char);
out.push('=');
out.push('=');
}
2 => {
let b0 = remainder[0];
let b1 = remainder[1];
out.push(BASE64_ALPHABET[(b0 >> 2) as usize] as char);
out.push(BASE64_ALPHABET[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
out.push(BASE64_ALPHABET[((b1 & 0x0f) << 2) as usize] as char);
out.push('=');
}
_ => {}
}
out
}
#[must_use]
pub fn base64_decode(input: &str) -> Option<Vec<u8>> {
fn decode_char(c: u8) -> Option<u8> {
match c {
b'A'..=b'Z' => Some(c - b'A'),
b'a'..=b'z' => Some(c - b'a' + 26),
b'0'..=b'9' => Some(c - b'0' + 52),
b'+' => Some(62),
b'/' => Some(63),
_ => None,
}
}
let bytes = input.trim().as_bytes();
if bytes.is_empty() {
return Some(Vec::new());
}
let unpadded = match bytes.strip_suffix(b"==") {
Some(s) => s,
None => bytes.strip_suffix(b"=").unwrap_or(bytes),
};
let mut out = Vec::with_capacity(unpadded.len() * 3 / 4);
let (chunks, remainder) = unpadded.as_chunks::<4>();
for &[c0, c1, c2, c3] in chunks {
let n0 = decode_char(c0)?;
let n1 = decode_char(c1)?;
let n2 = decode_char(c2)?;
let n3 = decode_char(c3)?;
out.push((n0 << 2) | (n1 >> 4));
out.push((n1 << 4) | (n2 >> 2));
out.push((n2 << 6) | n3);
}
match remainder.len() {
2 => {
let n0 = decode_char(remainder[0])?;
let n1 = decode_char(remainder[1])?;
out.push((n0 << 2) | (n1 >> 4));
}
3 => {
let n0 = decode_char(remainder[0])?;
let n1 = decode_char(remainder[1])?;
let n2 = decode_char(remainder[2])?;
out.push((n0 << 2) | (n1 >> 4));
out.push((n1 << 4) | (n2 >> 2));
}
0 => {}
_ => return None,
}
Some(out)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TlvEntry {
pub tag: u8,
pub value: Vec<u8>,
}
#[must_use]
pub fn decode_tlv(bytes: &[u8]) -> Vec<TlvEntry> {
let mut entries = Vec::new();
let mut idx = 0;
while idx + 2 <= bytes.len() {
let tag = bytes[idx];
let len = bytes[idx + 1] as usize;
idx += 2;
if idx + len <= bytes.len() {
entries.push(TlvEntry {
tag,
value: bytes[idx..idx + len].to_vec(),
});
idx += len;
} else {
break;
}
}
entries
}
fn append_tlv(buf: &mut Vec<u8>, tag: u8, value: &[u8]) {
buf.push(tag);
let len = value.len().min(255) as u8;
buf.push(len);
buf.extend_from_slice(&value[..len as usize]);
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZatcaInvoice {
pub seller_name: String,
pub vat_number: String,
pub timestamp: String,
pub total_amount: String,
pub vat_amount: String,
pub invoice_hash: Option<Vec<u8>>,
pub signature: Option<Vec<u8>>,
pub public_key: Option<Vec<u8>>,
pub stamp: Option<Vec<u8>>,
}
impl ZatcaInvoice {
#[must_use]
pub fn new(
seller_name: impl Into<String>,
vat_number: impl Into<String>,
timestamp: impl Into<String>,
total_amount: impl Into<String>,
vat_amount: impl Into<String>,
) -> Self {
Self {
seller_name: seller_name.into(),
vat_number: vat_number.into(),
timestamp: timestamp.into(),
total_amount: total_amount.into(),
vat_amount: vat_amount.into(),
invoice_hash: None,
signature: None,
public_key: None,
stamp: None,
}
}
#[must_use]
pub fn with_invoice_hash(mut self, hash: impl Into<Vec<u8>>) -> Self {
self.invoice_hash = Some(hash.into());
self
}
#[must_use]
pub fn with_signature(mut self, signature: impl Into<Vec<u8>>) -> Self {
self.signature = Some(signature.into());
self
}
#[must_use]
pub fn with_public_key(mut self, public_key: impl Into<Vec<u8>>) -> Self {
self.public_key = Some(public_key.into());
self
}
#[must_use]
pub fn with_stamp(mut self, stamp: impl Into<Vec<u8>>) -> Self {
self.stamp = Some(stamp.into());
self
}
#[must_use]
pub fn to_tlv_bytes(&self) -> Vec<u8> {
encode_zatca_tlv(self)
}
#[must_use]
pub fn to_qr_base64(&self) -> String {
zatca_qr_base64(self)
}
}
#[must_use]
pub fn encode_zatca_tlv(invoice: &ZatcaInvoice) -> Vec<u8> {
let mut buf = Vec::with_capacity(128);
append_tlv(&mut buf, 1, invoice.seller_name.as_bytes());
append_tlv(&mut buf, 2, invoice.vat_number.as_bytes());
append_tlv(&mut buf, 3, invoice.timestamp.as_bytes());
append_tlv(&mut buf, 4, invoice.total_amount.as_bytes());
append_tlv(&mut buf, 5, invoice.vat_amount.as_bytes());
if let Some(hash) = &invoice.invoice_hash {
append_tlv(&mut buf, 6, hash);
}
if let Some(sig) = &invoice.signature {
append_tlv(&mut buf, 7, sig);
}
if let Some(key) = &invoice.public_key {
append_tlv(&mut buf, 8, key);
}
if let Some(stamp) = &invoice.stamp {
append_tlv(&mut buf, 9, stamp);
}
buf
}
#[must_use]
pub fn zatca_qr_base64(invoice: &ZatcaInvoice) -> String {
let tlv_bytes = encode_zatca_tlv(invoice);
base64_encode(&tlv_bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_base64_encode_decode() {
let cases = [
("", ""),
("f", "Zg=="),
("fo", "Zm8="),
("foo", "Zm9v"),
("foob", "Zm9vYg=="),
("fooba", "Zm9vYmE="),
("foobar", "Zm9vYmFy"),
("Hello, World!", "SGVsbG8sIFdvcmxkIQ=="),
];
for (plain, expected_b64) in cases {
let encoded = base64_encode(plain.as_bytes());
assert_eq!(encoded, expected_b64, "Encoding mismatch for '{plain}'");
let decoded = base64_decode(&encoded).expect("Decode should succeed");
assert_eq!(
String::from_utf8(decoded).unwrap(),
plain,
"Decoded mismatch for '{plain}'"
);
}
}
#[test]
fn test_zatca_tlv_roundtrip() {
let invoice = ZatcaInvoice::new(
"Bob's Fashions",
"310122393500003",
"2022-04-25T15:30:00Z",
"1000.00",
"150.00",
);
let tlv = invoice.to_tlv_bytes();
let entries = decode_tlv(&tlv);
assert_eq!(entries.len(), 5);
assert_eq!(entries[0].tag, 1);
assert_eq!(
std::str::from_utf8(&entries[0].value).unwrap(),
"Bob's Fashions"
);
assert_eq!(entries[1].tag, 2);
assert_eq!(
std::str::from_utf8(&entries[1].value).unwrap(),
"310122393500003"
);
assert_eq!(entries[2].tag, 3);
assert_eq!(
std::str::from_utf8(&entries[2].value).unwrap(),
"2022-04-25T15:30:00Z"
);
assert_eq!(entries[3].tag, 4);
assert_eq!(std::str::from_utf8(&entries[3].value).unwrap(), "1000.00");
assert_eq!(entries[4].tag, 5);
assert_eq!(std::str::from_utf8(&entries[4].value).unwrap(), "150.00");
let b64 = invoice.to_qr_base64();
let decoded_b64 = base64_decode(&b64).unwrap();
assert_eq!(decoded_b64, tlv);
}
#[test]
fn test_zatca_phase_2_fields() {
let hash = vec![0xAB; 32];
let sig = vec![0xCD; 64];
let invoice = ZatcaInvoice::new(
"Saudi Tech Co",
"300000000000003",
"2026-09-10T12:00:00Z",
"500.00",
"75.00",
)
.with_invoice_hash(hash.clone())
.with_signature(sig.clone());
let tlv = invoice.to_tlv_bytes();
let entries = decode_tlv(&tlv);
assert_eq!(entries.len(), 7);
assert_eq!(entries[5].tag, 6);
assert_eq!(entries[5].value, hash);
assert_eq!(entries[6].tag, 7);
assert_eq!(entries[6].value, sig);
}
}