Added signing and verify
This commit is contained in:
parent
9c01e4a74f
commit
a53c7dc2c1
|
@ -1,4 +1,5 @@
|
|||
use crate::crypto::errors::CryptoError;
|
||||
use rsa::signature::{Error, SignatureEncoding};
|
||||
use rsa::{
|
||||
pkcs1::DecodeRsaPrivateKey,
|
||||
pkcs1::DecodeRsaPublicKey,
|
||||
|
@ -18,8 +19,8 @@ pub trait Decrypt {
|
|||
}
|
||||
|
||||
pub trait Signature {
|
||||
fn sign(&self, data: Vec<u8>) -> Result<Vec<u8>, CryptoError>;
|
||||
fn verify(&self, data: &[u8]) -> Result<Vec<u8>, CryptoError>;
|
||||
fn sign(&self, data: &[u8]) -> Vec<u8>;
|
||||
fn verify(&self, data: &[u8], signature: &[u8]) -> Result<bool, CryptoError>;
|
||||
}
|
||||
|
||||
// TODO: This is an UGLY name. Rename it something other than Handler. Almost everything is a handler
|
||||
|
@ -91,6 +92,34 @@ impl Decrypt for RSACryptoHandler {
|
|||
}
|
||||
}
|
||||
|
||||
impl Signature for RSACryptoHandler {
|
||||
fn sign(&self, data: &[u8]) -> Vec<u8> {
|
||||
// TODO: should this be called every time?
|
||||
let mut rng = rand::thread_rng();
|
||||
|
||||
// TODO: is it stupid to use clone here?
|
||||
let signing_key = SigningKey::<Sha256>::new(self.private_key.clone());
|
||||
let signature = signing_key.sign_with_rng(&mut rng, data);
|
||||
|
||||
signature.to_vec()
|
||||
}
|
||||
|
||||
fn verify(&self, data: &[u8], signature: &[u8]) -> Result<bool, CryptoError> {
|
||||
let signature = match rsa::pkcs1v15::Signature::try_from(signature) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Err(CryptoError::InvalidSignature),
|
||||
};
|
||||
|
||||
// TODO: is it stupid to use clone here?
|
||||
let verifying_key = VerifyingKey::<Sha256>::new(self.public_key.clone());
|
||||
|
||||
match verifying_key.verify(data, &signature) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(_) => Err(CryptoError::SignatureVerification),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod errors {
|
||||
#[derive(Debug)]
|
||||
pub enum CryptoError {
|
||||
|
@ -102,6 +131,8 @@ mod errors {
|
|||
PublicKeyNotFound,
|
||||
PrivateKeyInvalid,
|
||||
PublicKeyInvalid,
|
||||
InvalidSignature,
|
||||
SignatureVerification,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -164,7 +195,7 @@ m/A1vde9ULfntRXDT+44rL5BfsLB9oNfknDtLSk/TsE9zQ6f/zghzw==
|
|||
let encrypted_data = crypto_handler.encrypt(data).unwrap();
|
||||
let encrypted_data = &encrypted_data[..];
|
||||
|
||||
assert!(data.into_iter().ne(encrypted_data.into_iter()))
|
||||
assert!(data.iter().ne(encrypted_data.iter()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -180,6 +211,6 @@ m/A1vde9ULfntRXDT+44rL5BfsLB9oNfknDtLSk/TsE9zQ6f/zghzw==
|
|||
let decrypted_data = crypto_handler.decrypt(encrypted_data).unwrap();
|
||||
let decrypted_data = &decrypted_data[..];
|
||||
|
||||
assert!(data.into_iter().eq(decrypted_data.into_iter()))
|
||||
assert!(data.iter().eq(decrypted_data.iter()))
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue