added convesion from and to hex [CI SKIP]
This commit is contained in:
parent
5976ddecdf
commit
e3815e3198
@ -1,4 +1,5 @@
|
||||
use base64::{decode, encode};
|
||||
use hex;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::hash::{Hash, Hasher};
|
||||
@ -21,6 +22,31 @@ impl fmt::Display for ECCKey {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait HexBackend {
|
||||
fn from_bytes(bytes: Vec<u8>) -> Self;
|
||||
fn bytes(&self) -> &Vec<u8>;
|
||||
fn from_hex<I: AsRef<str>>(key: I) -> io::Result<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Ok(Self::from_bytes(hex::decode(key.as_ref()).map_err(
|
||||
|_| io::Error::new(io::ErrorKind::InvalidData, "Failed to decode hexstring"),
|
||||
)?))
|
||||
}
|
||||
fn as_hex(&self) -> io::Result<String> {
|
||||
Ok(hex::encode(&self.bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Base64Backed> HexBackend for T {
|
||||
fn from_bytes(bytes: Vec<u8>) -> Self {
|
||||
<Self as Base64Backed>::from_bytes(bytes)
|
||||
}
|
||||
fn bytes(&self) -> &Vec<u8> {
|
||||
<Self as Base64Backed>::bytes(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Base64Backed {
|
||||
fn from_bytes(bytes: Vec<u8>) -> Self;
|
||||
fn bytes(&self) -> &Vec<u8>;
|
||||
@ -34,7 +60,7 @@ pub trait Base64Backed {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Failed to decode base64",
|
||||
))
|
||||
));
|
||||
}
|
||||
}; /*.map_err(|err| {
|
||||
|
||||
@ -203,3 +229,15 @@ pub trait WireguardController {
|
||||
|
||||
fn update_peer(&mut self, peer: &Peer) -> io::Result<()>;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
|
||||
use super::*;
|
||||
#[test]
|
||||
fn key_encoding() {
|
||||
let key_encoded = "08df3bebd54217eb769d607f8673e1c3c53bb55d6ac689348a9227c8c4dd8857";
|
||||
let key = ECCKey::from_hex(key_encoded).unwrap();
|
||||
assert_eq!(&key.as_hex().unwrap(), key_encoded);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user