1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
// Copyright 2022 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use mas_iana::jose::JsonWebSignatureAlg;
use thiserror::Error;

use super::signature::Signature;

// An enum of all supported symmetric signing algorithms keys
#[non_exhaustive]
pub enum SymmetricKey {
    Hs256(super::Hs256Key),
    Hs384(super::Hs384Key),
    Hs512(super::Hs512Key),
}

#[derive(Debug, Error)]
#[error("Invalid algorithm {alg} used for symetric key")]
pub struct InvalidAlgorithm {
    pub alg: JsonWebSignatureAlg,
    pub key: Vec<u8>,
}

impl SymmetricKey {
    /// Create a new symmetric key for the given algorithm with the given key.
    ///
    /// # Errors
    ///
    /// Returns an error if the algorithm is not supported.
    pub fn new_for_alg(key: Vec<u8>, alg: &JsonWebSignatureAlg) -> Result<Self, InvalidAlgorithm> {
        match alg {
            JsonWebSignatureAlg::Hs256 => Ok(Self::hs256(key)),
            JsonWebSignatureAlg::Hs384 => Ok(Self::hs384(key)),
            JsonWebSignatureAlg::Hs512 => Ok(Self::hs512(key)),
            _ => Err(InvalidAlgorithm {
                alg: alg.clone(),
                key,
            }),
        }
    }

    /// Create a new symmetric key using the HS256 algorithm with the given key.
    #[must_use]
    pub const fn hs256(key: Vec<u8>) -> Self {
        Self::Hs256(super::Hs256Key::new(key))
    }

    /// Create a new symmetric key using the HS384 algorithm with the given key.
    #[must_use]
    pub const fn hs384(key: Vec<u8>) -> Self {
        Self::Hs384(super::Hs384Key::new(key))
    }

    /// Create a new symmetric key using the HS512 algorithm with the given key.
    #[must_use]
    pub const fn hs512(key: Vec<u8>) -> Self {
        Self::Hs512(super::Hs512Key::new(key))
    }
}

impl From<super::Hs256Key> for SymmetricKey {
    fn from(key: super::Hs256Key) -> Self {
        Self::Hs256(key)
    }
}

impl From<super::Hs384Key> for SymmetricKey {
    fn from(key: super::Hs384Key) -> Self {
        Self::Hs384(key)
    }
}

impl From<super::Hs512Key> for SymmetricKey {
    fn from(key: super::Hs512Key) -> Self {
        Self::Hs512(key)
    }
}

impl signature::RandomizedSigner<Signature> for SymmetricKey {
    fn try_sign_with_rng(
        &self,
        _rng: &mut (impl rand::CryptoRng + rand::RngCore),
        msg: &[u8],
    ) -> Result<Signature, signature::Error> {
        // XXX: is that implementation alright?
        signature::Signer::try_sign(self, msg)
    }
}

impl signature::Signer<Signature> for SymmetricKey {
    fn try_sign(&self, msg: &[u8]) -> Result<Signature, signature::Error> {
        match self {
            Self::Hs256(key) => {
                let signature = key.try_sign(msg)?;
                Ok(Signature::from_signature(&signature))
            }
            Self::Hs384(key) => {
                let signature = key.try_sign(msg)?;
                Ok(Signature::from_signature(&signature))
            }
            Self::Hs512(key) => {
                let signature = key.try_sign(msg)?;
                Ok(Signature::from_signature(&signature))
            }
        }
    }
}

impl signature::Verifier<Signature> for SymmetricKey {
    fn verify(&self, msg: &[u8], signature: &Signature) -> Result<(), signature::Error> {
        match self {
            Self::Hs256(key) => {
                let signature = signature.to_signature()?;
                key.verify(msg, &signature)
            }
            Self::Hs384(key) => {
                let signature = signature.to_signature()?;
                key.verify(msg, &signature)
            }
            Self::Hs512(key) => {
                let signature = signature.to_signature()?;
                key.verify(msg, &signature)
            }
        }
    }
}