Last active
December 8, 2023 19:49
-
-
Save RGGH/2077bb146d67bb862a4a9c758997c345 to your computer and use it in GitHub Desktop.
digital_sig.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
[dependencies] | |
k256 = "0.13.2" | |
rand = "0.8.5" | |
*/ | |
#![allow(unused)] | |
use k256::ecdsa::{SigningKey, VerifyingKey}; | |
use k256::ecdsa::signature::{Signer, Verifier}; | |
use rand::rngs::OsRng; | |
fn generate_key_pair() -> (SigningKey, VerifyingKey) { | |
let private_key = SigningKey::random(&mut OsRng); | |
let public_key = VerifyingKey::from(&private_key); | |
(private_key, public_key) | |
} | |
fn sign_message(private_key: &SigningKey, message: &str) -> Vec<u8> { | |
let signature: k256::ecdsa::Signature = private_key.sign(message.as_bytes()); // explicitly specify as_bytes | |
let der_signature = signature.to_der(); | |
der_signature.as_bytes().to_vec() | |
} | |
fn verify_signature(public_key: &VerifyingKey, message: &str, signature: &[u8]) -> bool { | |
if let Ok(signature) = k256::ecdsa::Signature::from_der(signature) { | |
return public_key.verify(message.as_bytes(), &signature).is_ok(); | |
} | |
false | |
} | |
fn main() { | |
// Example usage | |
let (private_key, public_key) = generate_key_pair(); | |
let message = "Hello, OP_CHECKSIG!"; | |
// Signing the message | |
let signature = sign_message(&private_key, message); | |
println!("Signature: {:x?}\n", signature); | |
// Bad message will not verify, only the good message | |
let bad_message = "Hello, OP_CHECKSIG bad sig!"; | |
// Verifying the signature | |
let is_valid = verify_signature(&public_key, bad_message, &signature); | |
println!("Signature {} is valid: {}",bad_message, is_valid); | |
// Verifying the signature | |
let is_valid = verify_signature(&public_key, message, &signature); | |
println!("Signature {} is valid: {}",message, is_valid); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment