Add a newline when saving keys to files

This commit is contained in:
Andrey Golovizin 2023-04-11 20:33:03 +02:00
parent d9080af78a
commit af9ebfb9e5

View file

@ -3,7 +3,10 @@ use gethostname::gethostname;
use log::debug; use log::debug;
use x25519_dalek::{PublicKey, StaticSecret}; use x25519_dalek::{PublicKey, StaticSecret};
use std::path::{Path, PathBuf}; use std::{
io::Write,
path::{Path, PathBuf},
};
use crate::dirs::get_data_dir; use crate::dirs::get_data_dir;
@ -25,13 +28,14 @@ impl Key {
BASE64_STANDARD.encode(self.0) BASE64_STANDARD.encode(self.0)
} }
fn read(path: &Path) -> anyhow::Result<Self> { fn load(path: &Path) -> anyhow::Result<Self> {
let key_data = std::fs::read_to_string(path)?; let key_data = std::fs::read_to_string(path)?;
Self::try_from_base64(&key_data) Self::try_from_base64(&key_data.trim_end())
} }
fn write(&self, path: &Path) -> anyhow::Result<()> { fn save(&self, path: &Path) -> anyhow::Result<()> {
std::fs::write(path, self.to_base64())?; let mut file = std::fs::File::create(path)?;
writeln!(file, "{}", self.to_base64())?;
Ok(()) Ok(())
} }
} }
@ -55,18 +59,18 @@ pub(crate) fn get_keys(machine: Option<&PathBuf>) -> Result<WireguardKeyPair, an
std::fs::create_dir_all(&key_path)?; std::fs::create_dir_all(&key_path)?;
let private_key_path = key_path.join("key"); let private_key_path = key_path.join("key");
let private_key = if private_key_path.is_file() { let private_key = if private_key_path.is_file() {
Key::read(&private_key_path)? Key::load(&private_key_path)?
} else { } else {
let key = generate_private_key(); let key = generate_private_key();
key.write(&private_key_path)?; key.save(&private_key_path)?;
key key
}; };
let public_key_path = key_path.join("pubkey"); let public_key_path = key_path.join("pubkey");
let public_key = if public_key_path.is_file() { let public_key = if public_key_path.is_file() {
Key::read(&public_key_path)? Key::load(&public_key_path)?
} else { } else {
let key = generate_public_key(&private_key); let key = generate_public_key(&private_key);
key.write(&public_key_path)?; key.save(&public_key_path)?;
key key
}; };
Ok(WireguardKeyPair { Ok(WireguardKeyPair {