rocket_webhook/webhooks/interface/public_key/
algorithms.rs

1/// ECDSA P256 Algorithm
2#[cfg(feature = "p256")]
3pub mod p256 {
4    use p256::ecdsa::{Signature, VerifyingKey, signature::Verifier};
5    use tokio_util::bytes::Bytes;
6
7    use super::super::WebhookPublicKeyAlgorithm;
8
9    pub struct EcdsaP256Asn1;
10    impl WebhookPublicKeyAlgorithm for EcdsaP256Asn1 {
11        fn verify(public_key: &Bytes, message: &[u8], signature: &[u8]) -> Result<(), String> {
12            let key = VerifyingKey::from_sec1_bytes(&public_key)
13                .map_err(|e| format!("Public key is invalid: {e}"))?;
14            let signature = Signature::from_der(signature)
15                .map_err(|e| format!("Expected signature is invalid: {e}"))?;
16            key.verify(message, &signature)
17                .map_err(|e| format!("ECDSA P-256 verification failed: {e}"))
18        }
19    }
20}
21
22/// ED25519 Algorithm
23#[cfg(feature = "ed25519")]
24pub mod ed25519 {
25    use ed25519_dalek::{Signature, Verifier, VerifyingKey};
26    use tokio_util::bytes::Bytes;
27
28    use super::super::WebhookPublicKeyAlgorithm;
29
30    pub struct Ed25519;
31    impl WebhookPublicKeyAlgorithm for Ed25519 {
32        fn verify(public_key: &Bytes, message: &[u8], signature: &[u8]) -> Result<(), String> {
33            let key = VerifyingKey::try_from(public_key.as_ref())
34                .map_err(|e| format!("Public key is invalid: {e}"))?;
35            let signature = Signature::from_slice(signature)
36                .map_err(|e| format!("Expected signature is invalid: {e}"))?;
37            key.verify(message, &signature)
38                .map_err(|e| format!("Ed25519 verification failed: {e}"))
39        }
40    }
41}