feat(server):完成加载加密证书功能。

This commit is contained in:
徐涛 2024-04-03 10:57:27 +08:00
parent 0b6896e3a1
commit 1f87086b45
2 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,36 @@
use std::{path::PathBuf, sync::OnceLock};
use anyhow::bail;
use openssl::{
pkey::{PKey, Private},
x509::X509,
};
static LICENSE_PUBKEY: OnceLock<X509> = OnceLock::new();
static LICENSE_PRIKEY: OnceLock<PKey<Private>> = OnceLock::new();
pub async fn load_certificates(certificate_filename: &str) -> anyhow::Result<()> {
let pubkey_file = PathBuf::from(".").join(format!("{}.pem", certificate_filename));
if !pubkey_file.exists() {
bail!("unable to load public key.");
}
let prikey_file = PathBuf::from(".").join(format!("{}.key", certificate_filename));
if !prikey_file.exists() {
bail!("unable to load private key.");
}
let pubkey = match cert_lib::load_certificate(pubkey_file) {
Ok(cert) => cert,
Err(e) => bail!("load certificate file failed: {}", e),
};
if let Err(_) = LICENSE_PUBKEY.set(pubkey) {
bail!("unable to store public key.");
}
let prikey = match cert_lib::load_private_key(prikey_file) {
Ok(key) => key,
Err(e) => bail!("load private key file failed: {}", e),
};
if let Err(_) = LICENSE_PRIKEY.set(prikey) {
bail!("unable to store private key.");
}
Ok(())
}

View File

@ -3,6 +3,7 @@
use tracing::{error, info};
mod certificate;
mod controllers;
mod logging;
mod products;
@ -21,6 +22,12 @@ async fn main() {
Ok(_) => info!("Products loaded successfully"),
}
// 加载用于加密的证书
match certificate::load_certificates("license").await {
Err(e) => error!("Failed to load certificates: {}", e),
Ok(_) => info!("Certificates loaded successfully"),
}
let main_route = server_routes::ServerMainRouter::new().registers(controllers::controllers());
// 启动服务
let bind_addr = String::from("0.0.0.0:3000");