Skip to main content

mldsa_native_rs/wrapper/
verifying_key.rs

1pub use signature::Verifier;
2
3use generic_array::GenericArray;
4
5use super::EMPTY_CTX;
6use super::ParameterSet;
7
8use crate::ffi;
9use crate::utils;
10use utils::transcoding;
11use utils::transcoding::AsBytes;
12use utils::typenum::Unsigned;
13
14/// Public key for signature verification.
15#[derive(Clone, Debug, PartialEq)]
16#[repr(transparent)]
17pub struct VerifyingKey<P: ParameterSet> {
18    pub(super) pk: GenericArray<u8, <P as crate::VerifyingKeyLen>::LEN>,
19}
20
21pub type PublicKey<P> = VerifyingKey<P>;
22
23impl<P: ParameterSet> VerifyingKey<P> {
24    /// Use [`Self`] to verify that the provided `signature`
25    /// for a given `message` bytestring is authentic
26    /// under the associated `context` bytestring.
27    ///
28    /// # Errors
29    ///
30    /// Returns [`signature::Error`] if it is inauthentic,
31    /// or otherwise returns `()`.
32    pub fn verify_with_ctx(
33        &self,
34        message: &[u8],
35        context: &[u8],
36        signature: &super::Signature<P>,
37    ) -> Result<(), signature::Error> {
38        let ret = {
39            let pk = self.pk.as_ptr();
40            let sig = signature.as_bytes();
41
42            unsafe {
43                P::VERIFY_FN(
44                    sig.as_ptr(),
45                    sig.len(),
46                    message.as_ptr(),
47                    message.len(),
48                    context.as_ptr(),
49                    context.len(),
50                    pk,
51                )
52            }
53        };
54        if ret != ffi::SUCCESS {
55            return Err(signature::Error::default());
56        }
57        Ok(())
58    }
59}
60
61impl<P: ParameterSet> signature::Verifier<super::Signature<P>> for VerifyingKey<P> {
62    fn verify(&self, msg: &[u8], signature: &super::Signature<P>) -> Result<(), signature::Error> {
63        self.verify_with_ctx(msg, EMPTY_CTX, signature)
64    }
65}
66
67impl<P: ParameterSet> From<VerifyingKey<P>>
68    for GenericArray<u8, <P as crate::VerifyingKeyLen>::LEN>
69{
70    fn from(vk: VerifyingKey<P>) -> Self {
71        vk.pk
72    }
73}
74
75impl<P: ParameterSet> TryFrom<&[u8]> for VerifyingKey<P> {
76    type Error = transcoding::TranscodingError;
77
78    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
79        if bytes.len() != <<P as crate::VerifyingKeyLen>::LEN>::USIZE {
80            return Err(transcoding::TranscodingError {});
81        }
82        let arr = GenericArray::from_slice(bytes).clone();
83        Ok(Self { pk: arr })
84    }
85}
86
87impl<P: ParameterSet> AsRef<[u8]> for VerifyingKey<P> {
88    fn as_ref(&self) -> &[u8] {
89        self.pk.as_ref()
90    }
91}