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
197
198
199
200
201
202
#[cfg(feature = "std")]
use std::fmt::Debug;

#[cfg(not(feature = "std"))]
use alloc::fmt::Debug;

use cryptraits::{
    convert::{FromBytes, Len, ToVec},
    key::{Generate, KeyPair as KeypairTrait, SecretKey},
    key_exchange::DiffieHellman,
    signature::{Sign, Verify},
};
use rand_core::{CryptoRng, OsRng, RngCore};

use zeroize::Zeroize;

use crate::errors::{KeyPairError, SignatureError};

pub mod ed25519;
pub mod util;
pub mod x25519_ristretto;

#[derive(Clone, PartialEq)]
pub struct KeyPair<SK>
where
    SK: SecretKey,
{
    secret: SK,
    public: SK::PK,
}

impl<SK> Len for KeyPair<SK>
where
    SK: SecretKey + Len,
    SK::PK: Len,
{
    const LEN: usize = SK::LEN + <<SK as SecretKey>::PK as Len>::LEN;
}

impl<SK> KeypairTrait for KeyPair<SK>
where
    SK: SecretKey,
{
    type SK = SK;

    fn public(&self) -> &<Self::SK as SecretKey>::PK {
        &self.public
    }

    fn to_public(&self) -> SK::PK {
        self.public
    }

    fn secret(&self) -> &Self::SK {
        &self.secret
    }
}

impl<SK> Generate for KeyPair<SK>
where
    SK: SecretKey + Generate,
{
    fn generate_with<R>(csprng: R) -> Self
    where
        R: CryptoRng + RngCore,
    {
        let secret: SK = SK::generate_with(csprng);
        let public = secret.to_public();

        KeyPair { secret, public }
    }

    fn generate() -> Self {
        Self::generate_with(&mut OsRng)
    }
}

impl<SK> Zeroize for KeyPair<SK>
where
    SK: SecretKey,
{
    fn zeroize(&mut self) {
        self.secret.zeroize();
    }
}

impl<SK> Drop for KeyPair<SK>
where
    SK: SecretKey,
{
    fn drop(&mut self) {
        self.zeroize();
    }
}

impl<SK> FromBytes for KeyPair<SK>
where
    SK: SecretKey + FromBytes + Len,
    SK::PK: FromBytes + Len,
    KeyPairError: From<<SK as FromBytes>::E> + From<<<SK as SecretKey>::PK as FromBytes>::E>,
{
    type E = KeyPairError;
    fn from_bytes(bytes: &[u8]) -> Result<Self, Self::E> {
        if bytes.len() != Self::LEN {
            return Err(KeyPairError::BytesLengthError);
        }

        let secret = SK::from_bytes(&bytes[..SK::LEN])?;
        let public = SK::PK::from_bytes(&bytes[SK::LEN..])?;

        Ok(KeyPair { secret, public })
    }
}

impl<SK> ToVec for KeyPair<SK>
where
    SK: SecretKey + ToVec + Len,
    SK::PK: ToVec + Len,
{
    fn to_vec(&self) -> Vec<u8> {
        let mut bytes: Vec<u8> = Vec::new();

        bytes.extend(self.secret.to_vec());
        bytes.extend(self.public.to_vec());

        bytes
    }
}

impl<SK> Sign for KeyPair<SK>
where
    SK: SecretKey + Sign,
{
    type SIG = <SK as Sign>::SIG;

    fn sign(&self, data: &[u8]) -> Self::SIG
    where
        Self: Sized,
    {
        self.secret.sign(data)
    }
}

impl<SK> DiffieHellman for KeyPair<SK>
where
    SK: SecretKey + Sign + DiffieHellman,
{
    type SSK = <SK as DiffieHellman>::SSK;
    type PK = <SK as DiffieHellman>::PK;

    fn diffie_hellman(&self, peer_public: &Self::PK) -> <SK as DiffieHellman>::SSK {
        self.secret.diffie_hellman(peer_public)
    }
}

impl<SK> Verify for KeyPair<SK>
where
    SK: SecretKey,
    SK::PK: Verify<E = SignatureError>,
{
    type E = SignatureError;
    type SIG = <SK::PK as Verify>::SIG;

    fn verify(&self, data: &[u8], signature: &Self::SIG) -> Result<(), Self::E> {
        self.public.verify(data, signature)
    }
}

impl<SK> Debug for KeyPair<SK>
where
    SK: SecretKey,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("KeyPair")
            .field("secret", &String::from("<erased>"))
            .field("public", &self.public)
            .finish()
    }
}

impl<SK> Default for KeyPair<SK>
where
    SK: SecretKey + Generate,
{
    fn default() -> Self {
        let secret = SK::generate_with(OsRng);
        let public = secret.to_public();

        Self { secret, public }
    }
}

impl<SK> From<SK> for KeyPair<SK>
where
    SK: SecretKey,
{
    fn from(secret: SK) -> Self {
        let public = secret.to_public();

        Self { secret, public }
    }
}