Skip to main content

mas_jose/jwa/
symmetric.rs

1// Copyright 2025, 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2022-2024 The Matrix.org Foundation C.I.C.
4//
5// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
6// Please see LICENSE files in the repository root for full details.
7
8use mas_iana::jose::JsonWebSignatureAlg;
9use thiserror::Error;
10
11use super::signature::Signature;
12
13// An enum of all supported symmetric signing algorithms keys
14#[non_exhaustive]
15pub enum SymmetricKey {
16    Hs256(super::Hs256Key),
17    Hs384(super::Hs384Key),
18    Hs512(super::Hs512Key),
19}
20
21#[derive(Debug, Error)]
22#[error("Invalid algorithm {alg} used for symetric key")]
23pub struct InvalidAlgorithm {
24    pub alg: JsonWebSignatureAlg,
25    pub key: Vec<u8>,
26}
27
28impl SymmetricKey {
29    /// Create a new symmetric key for the given algorithm with the given key.
30    ///
31    /// # Errors
32    ///
33    /// Returns an error if the algorithm is not supported.
34    pub fn new_for_alg(key: Vec<u8>, alg: &JsonWebSignatureAlg) -> Result<Self, InvalidAlgorithm> {
35        match alg {
36            JsonWebSignatureAlg::Hs256 => Ok(Self::hs256(key)),
37            JsonWebSignatureAlg::Hs384 => Ok(Self::hs384(key)),
38            JsonWebSignatureAlg::Hs512 => Ok(Self::hs512(key)),
39            _ => Err(InvalidAlgorithm {
40                alg: alg.clone(),
41                key,
42            }),
43        }
44    }
45
46    /// Create a new symmetric key using the HS256 algorithm with the given key.
47    #[must_use]
48    pub const fn hs256(key: Vec<u8>) -> Self {
49        Self::Hs256(super::Hs256Key::new(key))
50    }
51
52    /// Create a new symmetric key using the HS384 algorithm with the given key.
53    #[must_use]
54    pub const fn hs384(key: Vec<u8>) -> Self {
55        Self::Hs384(super::Hs384Key::new(key))
56    }
57
58    /// Create a new symmetric key using the HS512 algorithm with the given key.
59    #[must_use]
60    pub const fn hs512(key: Vec<u8>) -> Self {
61        Self::Hs512(super::Hs512Key::new(key))
62    }
63}
64
65impl From<super::Hs256Key> for SymmetricKey {
66    fn from(key: super::Hs256Key) -> Self {
67        Self::Hs256(key)
68    }
69}
70
71impl From<super::Hs384Key> for SymmetricKey {
72    fn from(key: super::Hs384Key) -> Self {
73        Self::Hs384(key)
74    }
75}
76
77impl From<super::Hs512Key> for SymmetricKey {
78    fn from(key: super::Hs512Key) -> Self {
79        Self::Hs512(key)
80    }
81}
82
83impl signature::RandomizedSigner<Signature> for SymmetricKey {
84    fn try_sign_with_rng<R: signature::rand_core::TryCryptoRng + ?Sized>(
85        &self,
86        _rng: &mut R,
87        msg: &[u8],
88    ) -> Result<Signature, signature::Error> {
89        // XXX: is that implementation alright?
90        signature::Signer::try_sign(self, msg)
91    }
92}
93
94impl signature::Signer<Signature> for SymmetricKey {
95    fn try_sign(&self, msg: &[u8]) -> Result<Signature, signature::Error> {
96        match self {
97            Self::Hs256(key) => {
98                let signature = key.try_sign(msg)?;
99                Ok(Signature::from_signature(&signature))
100            }
101            Self::Hs384(key) => {
102                let signature = key.try_sign(msg)?;
103                Ok(Signature::from_signature(&signature))
104            }
105            Self::Hs512(key) => {
106                let signature = key.try_sign(msg)?;
107                Ok(Signature::from_signature(&signature))
108            }
109        }
110    }
111}
112
113impl signature::Verifier<Signature> for SymmetricKey {
114    fn verify(&self, msg: &[u8], signature: &Signature) -> Result<(), signature::Error> {
115        match self {
116            Self::Hs256(key) => {
117                let signature = signature.to_signature()?;
118                key.verify(msg, &signature)
119            }
120            Self::Hs384(key) => {
121                let signature = signature.to_signature()?;
122                key.verify(msg, &signature)
123            }
124            Self::Hs512(key) => {
125                let signature = signature.to_signature()?;
126                key.verify(msg, &signature)
127            }
128        }
129    }
130}