summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorEmīls Piņķis <emils@mullvad.net>2019-02-21 20:35:00 +0000
committerEmīls Piņķis <emils@mullvad.net>2019-02-27 14:33:05 +0000
commit82e758726128fa9e088c968764413c70098a65b3 (patch)
tree772df64f59a287d03ba9c77fdfea346b6ff3943e
parent068b0bdea9bad08c9ade30fa70d7619db89344d8 (diff)
downloadmullvadvpn-82e758726128fa9e088c968764413c70098a65b3.tar.xz
mullvadvpn-82e758726128fa9e088c968764413c70098a65b3.zip
Add key generation for wireguard::PrivateKey in talpid-types
-rw-r--r--talpid-types/Cargo.toml2
-rw-r--r--talpid-types/src/net/wireguard.rs26
2 files changed, 27 insertions, 1 deletions
diff --git a/talpid-types/Cargo.toml b/talpid-types/Cargo.toml
index 9ef4fa89b3..678a7832fc 100644
--- a/talpid-types/Cargo.toml
+++ b/talpid-types/Cargo.toml
@@ -12,3 +12,5 @@ ipnetwork = "0.14"
base64 = "0.10"
hex = "0.3"
error-chain = "0.12"
+x25519-dalek = { version = "0.4.5", features = [ "std", "u64_backend" ], default-features = false }
+rand = "0.6"
diff --git a/talpid-types/src/net/wireguard.rs b/talpid-types/src/net/wireguard.rs
index d24ffee0e3..fe596fe475 100644
--- a/talpid-types/src/net/wireguard.rs
+++ b/talpid-types/src/net/wireguard.rs
@@ -6,6 +6,8 @@ use std::{
net::{IpAddr, SocketAddr},
};
+use rand::RngCore;
+
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize, Debug)]
/// Wireguard tunnel parameters
@@ -67,10 +69,32 @@ impl PrivateKey {
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
+
+ /// Normalizing a private key as per the specification - https://cr.yp.to/ecdh.html
+ fn normalize_key(bytes: &mut [u8; 32]) {
+ bytes[0] &= 248;
+ bytes[31] &= 127;
+ bytes[31] |= 64;
+ }
+
+ pub fn new_from_random() -> Result<Self, rand::Error> {
+ let mut bytes = [0u8; 32];
+ rand::rngs::OsRng::new()?.fill_bytes(&mut bytes);
+ Ok(Self::from(bytes))
+ }
+
+ /// Generate public key from private key
+ pub fn public_key(&self) -> PublicKey {
+ PublicKey::from(x25519_dalek::x25519(
+ self.0,
+ x25519_dalek::X25519_BASEPOINT_BYTES,
+ ))
+ }
}
impl From<[u8; 32]> for PrivateKey {
- fn from(private_key: [u8; 32]) -> PrivateKey {
+ fn from(mut private_key: [u8; 32]) -> PrivateKey {
+ Self::normalize_key(&mut private_key);
PrivateKey(private_key)
}
}