hickory_proto/dnssec/
public_key.rs

1// Copyright 2015-2016 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! Public Key implementations for supported key types
9
10use alloc::vec::Vec;
11
12#[cfg(feature = "serde")]
13use serde::{Deserialize, Serialize};
14
15use super::{Algorithm, crypto::decode_public_key};
16use crate::error::ProtoResult;
17
18/// PublicKeys implement the ability to ideally be zero copy abstractions over public keys for verifying signed content.
19///
20/// In DNS the KEY and DNSKEY types are generally the RData types which store public key material.
21pub trait PublicKey {
22    /// Returns the public bytes of the public key, in DNS format
23    fn public_bytes(&self) -> &[u8];
24
25    /// Verifies the hash matches the signature with the current `key`.
26    ///
27    /// # Arguments
28    ///
29    /// * `message` - the message to be validated, see `hash_rrset`
30    /// * `signature` - the signature to use to verify the hash, extracted from an `RData::RRSIG`
31    ///                 for example.
32    ///
33    /// # Return value
34    ///
35    /// True if and only if the signature is valid for the hash. This will always return
36    /// false if the `key`.
37    #[allow(unused)]
38    fn verify(&self, message: &[u8], signature: &[u8]) -> ProtoResult<()>;
39
40    /// The algorithm associated with this key.
41    fn algorithm(&self) -> Algorithm;
42}
43
44/// An owned variant of PublicKey
45#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
46#[derive(Clone, Debug, Eq, Hash, PartialEq)]
47pub struct PublicKeyBuf {
48    key_buf: Vec<u8>,
49    algorithm: Algorithm,
50}
51
52impl PublicKeyBuf {
53    /// Constructs a new PublicKey from the specified bytes, these should be in DNSKEY form.
54    pub fn new(key_buf: Vec<u8>, algorithm: Algorithm) -> Self {
55        Self { key_buf, algorithm }
56    }
57
58    /// Extract the inner buffer of public key bytes.
59    pub fn into_inner(self) -> Vec<u8> {
60        self.key_buf
61    }
62}
63
64impl PublicKey for PublicKeyBuf {
65    fn public_bytes(&self) -> &[u8] {
66        &self.key_buf
67    }
68
69    fn verify(&self, message: &[u8], signature: &[u8]) -> ProtoResult<()> {
70        decode_public_key(&self.key_buf, self.algorithm)?.verify(message, signature)
71    }
72
73    fn algorithm(&self) -> Algorithm {
74        self.algorithm
75    }
76}