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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#[cfg(test)]
mod sumrec;

#[cfg(not(feature = "with-bench"))]
mod common;
#[cfg(not(feature = "with-bench"))]
mod sum;

#[cfg(feature = "with-bench")]
pub mod common;
#[cfg(feature = "with-bench")]
pub mod sum;

use crate::evolving::{EvolvingStatus, KeyEvolvingAlgorithm};
use crate::kes::KeyEvolvingSignatureAlgorithm;
use crate::key::{
    AsymmetricKey, AsymmetricPublicKey, PublicKeyError, SecretKeyError, SecretKeySizeStatic,
};
use crate::sign::{SignatureError, SigningAlgorithm, Verification, VerificationAlgorithm};
use rand_core::{CryptoRng, RngCore};

// MMM sum scheme instanciated over the Ed25519 signature system
// and a specific depth of 12
#[cfg_attr(
    any(test, feature = "property-test-api"),
    derive(test_strategy::Arbitrary, Debug)
)]
pub struct SumEd25519_12;

const DEPTH: common::Depth = common::Depth(12);

impl AsymmetricPublicKey for SumEd25519_12 {
    type Public = sum::PublicKey;
    const PUBLIC_BECH32_HRP: &'static str = "kes25519-12-pk";
    const PUBLIC_KEY_SIZE: usize = 32;
    fn public_from_binary(data: &[u8]) -> Result<Self::Public, PublicKeyError> {
        sum::PublicKey::from_bytes(data).map_err(|e| match e {
            sum::Error::InvalidPublicKeySize(_) => PublicKeyError::SizeInvalid,
            _ => PublicKeyError::StructureInvalid,
        })
    }
}

impl AsymmetricKey for SumEd25519_12 {
    type Secret = sum::SecretKey;
    type PubAlg = SumEd25519_12;

    const SECRET_BECH32_HRP: &'static str = "kes25519-12-sk";
    fn generate<T: RngCore + CryptoRng>(mut rng: T) -> Self::Secret {
        let mut priv_bytes = [0u8; common::Seed::SIZE];
        rng.fill_bytes(&mut priv_bytes);

        let seed = common::Seed::from_bytes(priv_bytes);

        let (sk, _) = sum::keygen(DEPTH, &seed);
        sk
    }

    fn compute_public(key: &Self::Secret) -> sum::PublicKey {
        key.compute_public()
    }

    fn secret_from_binary(data: &[u8]) -> Result<Self::Secret, SecretKeyError> {
        sum::SecretKey::from_bytes(DEPTH, data).map_err(|e| match e {
            sum::Error::InvalidSecretKeySize(_) => SecretKeyError::SizeInvalid,
            _ => SecretKeyError::StructureInvalid,
        })
    }
}

impl SecretKeySizeStatic for SumEd25519_12 {
    const SECRET_KEY_SIZE: usize = sum::maximum_secret_key_size(DEPTH);
}

impl VerificationAlgorithm for SumEd25519_12 {
    type Signature = sum::Signature;

    const SIGNATURE_SIZE: usize = sum::signature_size(DEPTH);
    const SIGNATURE_BECH32_HRP: &'static str = "kes25519-12-sig";

    fn signature_from_bytes(data: &[u8]) -> Result<Self::Signature, SignatureError> {
        sum::Signature::from_bytes(DEPTH, data).map_err(|e| match e {
            sum::Error::InvalidSignatureSize(_) => SignatureError::SizeInvalid {
                expected: Self::SIGNATURE_SIZE,
                got: data.len(),
            },
            _ => SignatureError::StructureInvalid,
        })
    }

    fn verify_bytes(
        pubkey: &Self::Public,
        signature: &Self::Signature,
        msg: &[u8],
    ) -> Verification {
        if sum::verify(pubkey, msg, signature) {
            Verification::Success
        } else {
            Verification::Failed
        }
    }
}

impl SigningAlgorithm for SumEd25519_12 {
    fn sign(key: &Self::Secret, msg: &[u8]) -> sum::Signature {
        sum::sign(key, msg)
    }
}

impl KeyEvolvingAlgorithm for SumEd25519_12 {
    fn get_period(sec: &Self::Secret) -> u32 {
        sec.t() as u32
    }
    fn update(key: &mut Self::Secret) -> EvolvingStatus {
        if sum::update(key).is_ok() {
            EvolvingStatus::Success
        } else {
            EvolvingStatus::Failed
        }
    }
}

impl KeyEvolvingSignatureAlgorithm for SumEd25519_12 {
    fn get_period(sig: &Self::Signature) -> u32 {
        sig.t() as u32
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use proptest::prelude::*;
    use test_strategy::proptest;

    #[test]
    fn public_from_binary_correct_size() {
        SumEd25519_12::public_from_binary(&[0; SumEd25519_12::PUBLIC_KEY_SIZE]).unwrap();
    }

    #[test]
    fn public_from_binary_empty_slice() {
        assert!(matches!(
            SumEd25519_12::public_from_binary(&[]),
            Err(PublicKeyError::SizeInvalid)
        ))
    }

    // `secret_from_binary` should fail if the provided byte array does not match the public key size
    #[proptest]
    fn public_from_binary_size_check(#[strategy(..SumEd25519_12::PUBLIC_KEY_SIZE * 10)] n: usize) {
        let public_key = SumEd25519_12::public_from_binary(&vec![0; n]);

        prop_assert_eq!(
            n != SumEd25519_12::PUBLIC_KEY_SIZE,
            matches!(public_key, Err(PublicKeyError::SizeInvalid))
        );
    }

    #[test]
    fn signature_from_binary_correct_size() {
        SumEd25519_12::signature_from_bytes(&vec![0; SumEd25519_12::SIGNATURE_SIZE]).unwrap();
    }

    #[test]
    fn signature_from_binary_empty_slice() {
        assert!(matches!(
            SumEd25519_12::signature_from_bytes(&[]),
            Err(SignatureError::SizeInvalid { .. })
        ))
    }

    // `secret_from_binary` should fail if the provided byte array does not match the public key size
    #[proptest]
    fn signature_from_binary_size_check(
        #[strategy(..SumEd25519_12::SIGNATURE_SIZE * 10)] n: usize,
    ) {
        let signature = SumEd25519_12::signature_from_bytes(&vec![0; n]);

        prop_assert_eq!(
            n != SumEd25519_12::SIGNATURE_SIZE,
            matches!(signature, Err(SignatureError::SizeInvalid { .. }))
        );
    }

    /// `secret_from_binary`should fail if the provided byte array does not match the secret key size
    #[proptest]
    fn secret_from_binary_size_check(#[strategy(..SumEd25519_12::SECRET_KEY_SIZE * 10)] n: usize) {
        let private_key = SumEd25519_12::secret_from_binary(&vec![0; n]);

        assert_eq!(
            n != SumEd25519_12::SECRET_KEY_SIZE,
            private_key.err() == Some(SecretKeyError::SizeInvalid)
        );
    }
}