fkm_proxy/utils/
certs.rs

1use anyhow::Result;
2use std::{fs::File, io::BufReader, path::Path};
3use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer};
4
5pub fn load_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
6    if !path.exists() {
7        return Err(anyhow::anyhow!("Cert not found in path: {path:?}"));
8    }
9
10    rustls_pemfile::certs(&mut BufReader::new(File::open(path)?))
11        .collect::<std::io::Result<_>>()
12        .map_err(anyhow::Error::from)
13}
14
15pub fn load_keys(path: &Path) -> Result<PrivateKeyDer<'static>> {
16    if !path.exists() {
17        return Err(anyhow::anyhow!("Private key not found in path: {path:?}"));
18    }
19
20    rustls_pemfile::private_key(&mut BufReader::new(File::open(path)?))?
21        .ok_or_else(|| anyhow::anyhow!("Private key returned None"))
22}
23
24pub fn cert_from_str(cert: &str) -> Result<Vec<CertificateDer<'static>>> {
25    rustls_pemfile::certs(&mut cert.as_bytes())
26        .collect::<std::io::Result<_>>()
27        .map_err(anyhow::Error::from)
28}
29
30pub fn key_from_str(key: &str) -> Result<PrivateKeyDer<'static>> {
31    rustls_pemfile::private_key(&mut key.as_bytes())?
32        .ok_or_else(|| anyhow::anyhow!("Private ket returned None"))
33}