Skip to main content

ssh_key/public/
opaque.rs

1//! Opaque public keys.
2//!
3//! [`OpaquePublicKey`] represents a public key meant to be used with an algorithm unknown to this
4//! crate, i.e. public keys that use a custom algorithm as specified in [RFC4251 § 6].
5//!
6//! They are said to be opaque, because the meaning of their underlying byte representation is not
7//! specified.
8//!
9//! [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
10
11use crate::{Algorithm, Error, Result};
12use alloc::vec::Vec;
13use encoding::{Decode, Encode, Reader, Writer};
14
15/// An opaque public key with a custom algorithm name.
16///
17/// The encoded representation of an `OpaquePublicKey` is the encoded representation of its
18/// [`OpaquePublicKeyBytes`].
19#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
20pub struct OpaquePublicKey {
21    /// The [`Algorithm`] of this public key.
22    pub algorithm: Algorithm,
23    /// The key data
24    pub key: OpaquePublicKeyBytes,
25}
26
27impl OpaquePublicKey {
28    /// Create a new `OpaquePublicKey`.
29    #[must_use]
30    pub fn new(key: Vec<u8>, algorithm: Algorithm) -> Self {
31        Self {
32            key: OpaquePublicKeyBytes(key),
33            algorithm,
34        }
35    }
36
37    /// Get the [`Algorithm`] for this public key type.
38    #[must_use]
39    pub fn algorithm(&self) -> Algorithm {
40        self.algorithm.clone()
41    }
42
43    /// Decode [`OpaquePublicKey`] for the specified algorithm.
44    pub(super) fn decode_as(reader: &mut impl Reader, algorithm: Algorithm) -> Result<Self> {
45        Ok(Self {
46            algorithm,
47            key: OpaquePublicKeyBytes::decode(reader)?,
48        })
49    }
50}
51
52impl AsRef<[u8]> for OpaquePublicKey {
53    fn as_ref(&self) -> &[u8] {
54        self.key.as_ref()
55    }
56}
57
58impl Encode for OpaquePublicKey {
59    fn encoded_len(&self) -> encoding::Result<usize> {
60        self.key.encoded_len()
61    }
62
63    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
64        self.key.encode(writer)
65    }
66}
67
68/// The underlying representation of an [`OpaquePublicKey`].
69///
70/// The encoded representation of an `OpaquePublicKeyBytes` consists of a 4-byte length prefix,
71/// followed by its byte representation.
72#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
73pub struct OpaquePublicKeyBytes(Vec<u8>);
74
75impl Decode for OpaquePublicKeyBytes {
76    type Error = Error;
77
78    fn decode(reader: &mut impl Reader) -> Result<Self> {
79        Ok(Self(Vec::decode(reader)?))
80    }
81}
82
83impl Encode for OpaquePublicKeyBytes {
84    fn encoded_len(&self) -> encoding::Result<usize> {
85        self.0.encoded_len()
86    }
87
88    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
89        self.0.encode(writer)
90    }
91}
92
93impl AsRef<[u8]> for OpaquePublicKeyBytes {
94    fn as_ref(&self) -> &[u8] {
95        &self.0
96    }
97}