hessra_token/
utils.rs

1use base64::{engine::general_purpose::STANDARD, Engine};
2use std::fs::read_to_string;
3
4use crate::error::TokenError;
5
6pub use biscuit_auth::PublicKey;
7
8/// Encode binary token data to base64 string
9///
10/// # Arguments
11///
12/// * `token_bytes` - Binary token data
13///
14/// # Returns
15///
16/// Base64 encoded token string
17pub fn encode_token(token_bytes: &[u8]) -> String {
18    STANDARD.encode(token_bytes)
19}
20
21/// Decode a base64 encoded token string to binary
22///
23/// # Arguments
24///
25/// * `token_string` - Base64 encoded token string
26///
27/// # Returns
28///
29/// Binary token data or TokenError if decoding fails
30pub fn decode_token(token_string: &str) -> Result<Vec<u8>, TokenError> {
31    STANDARD
32        .decode(token_string)
33        .map_err(|e| TokenError::generic(format!("Failed to decode base64 token: {}", e)))
34}
35
36pub fn public_key_from_pem_file(path: &str) -> Result<PublicKey, TokenError> {
37    let key_string = read_to_string(path)
38        .map_err(|e| TokenError::generic(format!("Failed to read file: {}", e)))?;
39    let key = PublicKey::from_pem(&key_string)
40        .map_err(|e| TokenError::generic(format!("Failed to parse PEM: {}", e)))?;
41    Ok(key)
42}