use jsonwebtoken::EncodingKey;
use std::fs::File;
use std::io::Read;
use std::path::Path;
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,
"File not found",
));
}
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>) -> EncodingKey {
EncodingKey::from_rsa_pem(&bytes).unwrap_or_else(|_| {
panic!("Invalid key format - ensure the file contains a valid RSA PEM key")
})
}
pub fn read_private_key(path: &str) -> Result<EncodingKey, std::io::Error> {
let bytes = read_file(path)?;
Ok(bytes_to_encoding_key(bytes))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "No such file or directory")]
fn test_invalid_path() {
read_private_key("nonexistent.key").unwrap();
}
}