feat: encryption configuration properties

This commit is contained in:
huzibaca
2024-11-20 07:27:42 +08:00
parent bb44fc51bd
commit 15bd7324fe
6 changed files with 494 additions and 127 deletions

View File

@@ -1,6 +1,7 @@
use crate::core::handle;
use anyhow::Result;
use once_cell::sync::OnceCell;
use std::fs;
use std::path::PathBuf;
use tauri::Manager;
@@ -125,3 +126,27 @@ pub fn path_to_str(path: &PathBuf) -> Result<&str> {
.ok_or(anyhow::anyhow!("failed to get path from {:?}", path))?;
Ok(path_str)
}
pub fn get_encryption_key() -> Result<Vec<u8>> {
let app_dir = app_home_dir()?;
let key_path = app_dir.join(".encryption_key");
if key_path.exists() {
// Read existing key
fs::read(&key_path).map_err(|e| anyhow::anyhow!("Failed to read encryption key: {}", e))
} else {
// Generate and save new key
let mut key = vec![0u8; 32];
getrandom::getrandom(&mut key)?;
// Ensure directory exists
if let Some(parent) = key_path.parent() {
fs::create_dir_all(parent)
.map_err(|e| anyhow::anyhow!("Failed to create key directory: {}", e))?;
}
// Save key
fs::write(&key_path, &key)
.map_err(|e| anyhow::anyhow!("Failed to save encryption key: {}", e))?;
Ok(key)
}
}