use jsonwebtoken::EncodingKey;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use crate::errors::UtilsError;
fn read_file(path: &str) -> Result<Vec<u8>, std::io::Error> {
let path = Path::new(path);
if !path.exists() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("File not found: {}", path.display()),
));
}
let mut file = File::open(path)?;
let mut contents = Vec::new();
file.read_to_end(&mut contents)?;
Ok(contents)
}
fn bytes_to_encoding_key(bytes: Vec<u8>) -> Result<EncodingKey, UtilsError> {
EncodingKey::from_rsa_pem(&bytes)
.map_err(|e| UtilsError::InvalidPrivateKey(format!("Invalid RSA PEM key format: {}", e)))
}
pub fn read_private_key(path: &str) -> Result<EncodingKey, UtilsError> {
let bytes = read_file(path)?;
bytes_to_encoding_key(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_invalid_path() {
let result = read_private_key("nonexistent.key");
assert!(result.is_err());
match result {
Err(UtilsError::IoError(_)) => {}, _ => panic!("Expected IoError"),
}
}
}