You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.4 KiB
63 lines
1.4 KiB
extern crate rand; |
|
|
|
use crate::ed25519_dalek::ed25519::signature::Signature; |
|
use crate::ed25519_dalek::Signer; |
|
use crate::ed25519_dalek::Verifier; |
|
use alloc::vec::Vec; |
|
use ed25519_dalek::{Keypair, PublicKey as PK}; |
|
use rand::rngs::OsRng; |
|
use serde::{Deserialize, Serialize}; |
|
|
|
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] |
|
pub struct PublicKey { |
|
pub key: [u8; 32], |
|
} |
|
|
|
impl PublicKey { |
|
pub fn verify_sign(&self, raw: &Vec<u8>, sign: &Vec<u8>) -> bool { |
|
PK::from_bytes(&self.key) |
|
.unwrap() |
|
.verify( |
|
raw, |
|
&Signature::from_bytes(sign.clone().into_boxed_slice().as_ref()).unwrap(), |
|
) |
|
.is_ok() |
|
} |
|
} |
|
|
|
pub struct Keys { |
|
pub pair: Keypair, |
|
} |
|
|
|
impl Keys { |
|
pub fn gen() -> Keys { |
|
Keys { |
|
pair: Keypair::generate(&mut OsRng {}), |
|
} |
|
} |
|
} |
|
|
|
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] |
|
pub enum Sign { |
|
NoSign, |
|
Signed(PublicKey /* source */, Vec<u8> /* sign */), |
|
} |
|
|
|
pub fn verify_sign(data: &Vec<u8>, sign: &Sign) -> bool { |
|
match sign { |
|
Sign::NoSign => true, |
|
Sign::Signed(key, sign) => key.verify_sign(data, sign), |
|
} |
|
} |
|
|
|
impl Keys { |
|
pub fn sign(&self, content: &Vec<u8>) -> Vec<u8> { |
|
self.pair.sign(content.as_ref()).to_bytes().to_vec() |
|
} |
|
|
|
pub fn get_public(&self) -> PublicKey { |
|
PublicKey { |
|
key: *self.clone().pair.public.as_bytes(), |
|
} |
|
} |
|
}
|
|
|