signature verification
This commit is contained in:
@@ -1,4 +1,8 @@
|
||||
use std::io::Read;
|
||||
|
||||
use crate::messages_structure::HandshakeMessage;
|
||||
use bytes::Bytes;
|
||||
use p256::EncodedPoint;
|
||||
use p256::ecdsa::{
|
||||
Signature, SigningKey, VerifyingKey,
|
||||
signature::{Signer, Verifier},
|
||||
@@ -9,6 +13,7 @@ use sha2::{Digest, Sha256};
|
||||
///
|
||||
/// contains the ecdsa private key, the ecdsa public key and the username
|
||||
///
|
||||
///
|
||||
pub struct CryptographicSignature {
|
||||
priv_key: SigningKey,
|
||||
pub pub_key: VerifyingKey,
|
||||
@@ -42,6 +47,53 @@ pub fn formatPubKey(crypto_pair: CryptographicSignature) -> String {
|
||||
hex::encode(pubkey_bytes)
|
||||
}
|
||||
|
||||
pub async fn get_peer_key(username: &String) -> Result<VerifyingKey, reqwest::Error> {
|
||||
let client = reqwest::Client::new();
|
||||
let uri = format!("https://jch.irif.fr:8443/peers/{}/key", username);
|
||||
let res = client.get(uri).send().await?;
|
||||
if res.status().is_success() {
|
||||
println!("Successfully retreived the peers key.");
|
||||
} else {
|
||||
eprintln!(
|
||||
"Failed to get the peers key from the server. Status: {}",
|
||||
res.status()
|
||||
);
|
||||
}
|
||||
let body: Bytes = res.bytes().await?;
|
||||
let slice: &[u8] = body.as_ref();
|
||||
let body_bytes: &[u8; 64] = slice.try_into().expect("size error");
|
||||
let received_key = convert_verifyingkey(body_bytes);
|
||||
Ok(received_key)
|
||||
}
|
||||
|
||||
fn convert_verifyingkey(raw_xy: &[u8; 64]) -> VerifyingKey {
|
||||
let mut sec1 = [0u8; 65];
|
||||
sec1[0] = 0x04;
|
||||
sec1[1..].copy_from_slice(raw_xy);
|
||||
|
||||
let ep = EncodedPoint::from_bytes(&sec1).expect("invalid point bytes");
|
||||
let pk = VerifyingKey::from_encoded_point(&ep).expect("invalid encoded point");
|
||||
VerifyingKey::from(pk)
|
||||
}
|
||||
|
||||
pub fn verify_signature(pubkey: VerifyingKey, message: &Vec<u8>) -> bool {
|
||||
let length_bytes: [u8; 2] = message[5..7].try_into().expect("Taille incorrecte");
|
||||
let length = u16::from_be_bytes(length_bytes);
|
||||
println!("message length: {}", length);
|
||||
let msg_to_hash = &message[..length as usize + 7];
|
||||
let signature_bytes = &message[length as usize + 7..length as usize + 7 + 64];
|
||||
println!("conversion start");
|
||||
let sig = match Signature::from_bytes(signature_bytes.try_into().expect("conversion error")) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return false,
|
||||
};
|
||||
println!("conversion done");
|
||||
match pubkey.verify(&msg_to_hash, &sig) {
|
||||
Ok(()) => true,
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// takes a serialized message and adds the signature using the private key
|
||||
///
|
||||
|
||||
Reference in New Issue
Block a user