Compare commits

...

2 commits

Author SHA1 Message Date
bc2078fe24
Preshared keys 2023-11-11 16:02:01 +01:00
bb6d657ac8
Curve25519 KEY CLAMPING 2023-11-11 15:59:08 +01:00

View file

@ -15,6 +15,10 @@ pub struct PubKey {
data: [u8; 32], data: [u8; 32],
} }
pub struct PresharedKey {
data: [u8; 32],
}
impl Key for PrivKey { impl Key for PrivKey {
fn get_data(&self) -> [u8; 32] { fn get_data(&self) -> [u8; 32] {
self.data.to_owned() self.data.to_owned()
@ -27,6 +31,12 @@ impl Key for PubKey {
} }
} }
impl Key for PresharedKey {
fn get_data(&self) -> [u8; 32] {
self.data.to_owned()
}
}
impl Display for dyn Key { impl Display for dyn Key {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!( write!(
@ -54,6 +64,7 @@ impl Display for PrivKey {
) )
} }
} }
impl Display for PubKey { impl Display for PubKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!( write!(
@ -68,10 +79,28 @@ impl Display for PubKey {
} }
} }
impl Display for PresharedKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
base64::engine::GeneralPurpose::new(
&base64::alphabet::STANDARD,
base64::engine::general_purpose::GeneralPurposeConfig::new()
)
.encode(self.get_data())
)
}
}
impl PrivKey { impl PrivKey {
pub fn generate() -> Self { pub fn generate() -> Self {
let mut buf: [u8; 32] = [0; 32]; let mut buf: [u8; 32] = [0; 32];
StdRng::from_entropy().fill_bytes(&mut buf); StdRng::from_entropy().fill_bytes(&mut buf);
//Curve25519 clamping
buf[0] &= 248;
buf[31] &= 127;
buf[31] |= 64;
PrivKey { data: buf } PrivKey { data: buf }
} }
@ -83,6 +112,14 @@ impl PrivKey {
} }
} }
impl PresharedKey {
pub fn generate() -> Self {
let mut buf: [u8; 32] = [0; 32];
StdRng::from_entropy().fill_bytes(&mut buf);
PresharedKey { data: buf }
}
}
impl From<[u8; 32]> for PrivKey { impl From<[u8; 32]> for PrivKey {
fn from(value: [u8; 32]) -> Self { fn from(value: [u8; 32]) -> Self {
PrivKey { data: value } PrivKey { data: value }
@ -97,6 +134,20 @@ impl From<&[u8; 32]> for PrivKey {
} }
} }
impl From<[u8; 32]> for PresharedKey {
fn from(value: [u8; 32]) -> Self {
PresharedKey { data: value }
}
}
impl From<&[u8; 32]> for PresharedKey {
fn from(value: &[u8; 32]) -> Self {
PresharedKey {
data: value.clone(),
}
}
}
pub fn generate_key_pair() -> (PrivKey, PubKey) { pub fn generate_key_pair() -> (PrivKey, PubKey) {
let privkey = PrivKey::generate(); let privkey = PrivKey::generate();
let pubkey = privkey.derive_pubkey(); let pubkey = privkey.derive_pubkey();