ksign/
verifying_key.rs

1use ed25519_dalek::Verifier;
2
3use crate::Error;
4use crate::Fingerprint;
5use crate::Signature;
6use crate::UntrustedComment;
7use crate::IO;
8use crate::PK_ALGO;
9use crate::VERIFYING_KEY_BYTES_LEN;
10
11/// Verifying (public) key.
12pub struct VerifyingKey {
13    pub(crate) verifying_key: ed25519_dalek::VerifyingKey,
14    pub(crate) fingerprint: Fingerprint,
15    pub(crate) comment: Option<String>,
16}
17
18impl VerifyingKey {
19    /// Verify the signature of the message using the veryfying key.
20    pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), Error> {
21        self.verifying_key
22            .verify(message, &signature.signature)
23            .map_err(|_| Error::Verification)
24    }
25
26    /// Get fingerprint.
27    pub fn fingerprint(&self) -> &Fingerprint {
28        &self.fingerprint
29    }
30}
31
32impl IO for VerifyingKey {
33    fn get_comment(&self) -> UntrustedComment {
34        match self.comment.as_ref() {
35            Some(s) => UntrustedComment::String(s),
36            None => UntrustedComment::Fingerprint("public key", self.fingerprint),
37        }
38    }
39
40    fn to_bytes(&self) -> Vec<u8> {
41        let mut bytes = Vec::with_capacity(VERIFYING_KEY_BYTES_LEN);
42        bytes.extend_from_slice(PK_ALGO.as_bytes());
43        bytes.extend_from_slice(&self.fingerprint[..]);
44        bytes.extend_from_slice(self.verifying_key.as_bytes());
45        bytes
46    }
47
48    fn from_bytes(bytes: &[u8], comment: Option<String>) -> Result<Self, Error> {
49        let algo =
50            std::str::from_utf8(bytes.get(..2).ok_or(Error::Format)?).map_err(|_| Error::Format)?;
51        if algo != PK_ALGO {
52            return Err(Error::Algorithm);
53        }
54        const FINGERPRINT_OFFSET: usize = 2;
55        const VERIFYING_KEY_OFFSET: usize = FINGERPRINT_OFFSET + Fingerprint::LEN;
56        let fingerprint: Fingerprint = bytes
57            .get(FINGERPRINT_OFFSET..VERIFYING_KEY_OFFSET)
58            .ok_or(Error::Format)?
59            .try_into()?;
60        let verifying_key: ed25519_dalek::VerifyingKey = bytes
61            .get(VERIFYING_KEY_OFFSET..)
62            .ok_or(Error::Format)?
63            .try_into()
64            .map_err(|_| Error::Format)?;
65        Ok(Self {
66            verifying_key,
67            fingerprint,
68            comment,
69        })
70    }
71}