Generate keys without the wg binary

This commit is contained in:
Andrey Golovizin 2023-04-10 22:21:24 +02:00
parent ebccc59bf0
commit c282177afb
3 changed files with 113 additions and 17 deletions

View file

@ -1,12 +1,14 @@
use base64::prelude::{Engine as _, BASE64_STANDARD};
use gethostname::gethostname;
use log::debug;
use std::io::Write;
use x25519_dalek::{PublicKey, StaticSecret};
use std::path::PathBuf;
use std::process;
use crate::dirs::get_data_dir;
const KEY_SIZE: usize = 32;
#[derive(Debug)]
pub(crate) struct WireguardKeyPair {
pub public_key: String,
@ -47,21 +49,16 @@ pub(crate) fn get_keys(machine: Option<&PathBuf>) -> Result<WireguardKeyPair, an
}
fn generate_private_key() -> anyhow::Result<String> {
let privkey = process::Command::new("wg").arg("genkey").output()?.stdout;
Ok(String::from_utf8(privkey)?.trim_end().to_string())
let private_key = StaticSecret::random();
Ok(BASE64_STANDARD.encode(private_key.to_bytes()))
}
fn generate_public_key(private_key: &str) -> anyhow::Result<String> {
let mut pubkey_cmd = process::Command::new("wg")
.arg("pubkey")
.stdin(process::Stdio::piped())
.stdout(process::Stdio::piped())
.spawn()?;
pubkey_cmd
.stdin
.as_mut()
.expect("no stdin")
.write_all(private_key.as_bytes())?;
let pubkey = pubkey_cmd.wait_with_output()?.stdout;
Ok(String::from_utf8(pubkey)?.trim_end().to_string())
let mut key_data = [0u8; KEY_SIZE];
let key_bytes = BASE64_STANDARD.decode(private_key)?;
assert_eq!(key_bytes.len(), KEY_SIZE);
key_data[0..KEY_SIZE].copy_from_slice(&key_bytes);
let key = StaticSecret::from(key_data);
let pubkey = PublicKey::from(&key);
Ok(BASE64_STANDARD.encode(pubkey.to_bytes()))
}