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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
//! Ed25519 private keys.
//!
//! Edwards Digital Signature Algorithm (EdDSA) over Curve25519.

use crate::{
    checked::CheckedSum, decode::Decode, encode::Encode, public::Ed25519PublicKey, reader::Reader,
    writer::Writer, Error, Result,
};
use core::fmt;
use zeroize::{Zeroize, Zeroizing};

#[cfg(feature = "rand_core")]
use rand_core::{CryptoRng, RngCore};

#[cfg(feature = "subtle")]
use subtle::{Choice, ConstantTimeEq};

/// Ed25519 private key.
// TODO(tarcieri): use `ed25519::PrivateKey`? (doesn't exist yet)
#[derive(Clone)]
pub struct Ed25519PrivateKey([u8; Self::BYTE_SIZE]);

impl Ed25519PrivateKey {
    /// Size of an Ed25519 private key in bytes.
    pub const BYTE_SIZE: usize = 32;

    /// Generate a random Ed25519 private key.
    #[cfg(feature = "rand_core")]
    #[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
    pub fn random(mut rng: impl CryptoRng + RngCore) -> Self {
        let mut key_bytes = [0u8; Self::BYTE_SIZE];
        rng.fill_bytes(&mut key_bytes);
        Self(key_bytes)
    }

    /// Parse Ed25519 private key from bytes.
    pub fn from_bytes(bytes: &[u8; Self::BYTE_SIZE]) -> Self {
        Self(*bytes)
    }

    /// Convert to the inner byte array.
    pub fn to_bytes(&self) -> [u8; Self::BYTE_SIZE] {
        self.0
    }
}

impl AsRef<[u8; Self::BYTE_SIZE]> for Ed25519PrivateKey {
    fn as_ref(&self) -> &[u8; Self::BYTE_SIZE] {
        &self.0
    }
}

impl Drop for Ed25519PrivateKey {
    fn drop(&mut self) {
        self.0.zeroize();
    }
}

impl TryFrom<&[u8]> for Ed25519PrivateKey {
    type Error = Error;

    fn try_from(bytes: &[u8]) -> Result<Self> {
        Ok(Ed25519PrivateKey::from_bytes(bytes.try_into()?))
    }
}

impl fmt::Debug for Ed25519PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Ed25519PrivateKey").finish_non_exhaustive()
    }
}

impl fmt::LowerHex for Ed25519PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.as_ref() {
            write!(f, "{:02x}", byte)?;
        }
        Ok(())
    }
}

impl fmt::UpperHex for Ed25519PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.as_ref() {
            write!(f, "{:02X}", byte)?;
        }
        Ok(())
    }
}

#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
impl From<Ed25519PrivateKey> for ed25519_dalek::SecretKey {
    fn from(key: Ed25519PrivateKey) -> ed25519_dalek::SecretKey {
        ed25519_dalek::SecretKey::from(&key)
    }
}

#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
impl From<&Ed25519PrivateKey> for ed25519_dalek::SecretKey {
    fn from(key: &Ed25519PrivateKey) -> ed25519_dalek::SecretKey {
        ed25519_dalek::SecretKey::from_bytes(key.as_ref()).expect("invalid Ed25519 key")
    }
}

#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
impl From<ed25519_dalek::SecretKey> for Ed25519PrivateKey {
    fn from(key: ed25519_dalek::SecretKey) -> Ed25519PrivateKey {
        Ed25519PrivateKey::from(&key)
    }
}

#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
impl From<&ed25519_dalek::SecretKey> for Ed25519PrivateKey {
    fn from(key: &ed25519_dalek::SecretKey) -> Ed25519PrivateKey {
        Ed25519PrivateKey(key.to_bytes())
    }
}

#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
impl From<Ed25519PrivateKey> for Ed25519PublicKey {
    fn from(private: Ed25519PrivateKey) -> Ed25519PublicKey {
        Ed25519PublicKey::from(&private)
    }
}

#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
impl From<&Ed25519PrivateKey> for Ed25519PublicKey {
    fn from(private: &Ed25519PrivateKey) -> Ed25519PublicKey {
        let secret = ed25519_dalek::SecretKey::from(private);
        ed25519_dalek::PublicKey::from(&secret).into()
    }
}

#[cfg(feature = "subtle")]
#[cfg_attr(docsrs, doc(cfg(feature = "subtle")))]
impl ConstantTimeEq for Ed25519PrivateKey {
    fn ct_eq(&self, other: &Self) -> Choice {
        self.as_ref().ct_eq(other.as_ref())
    }
}

#[cfg(feature = "subtle")]
#[cfg_attr(docsrs, doc(cfg(feature = "subtle")))]
impl PartialEq for Ed25519PrivateKey {
    fn eq(&self, other: &Self) -> bool {
        self.ct_eq(other).into()
    }
}

#[cfg(feature = "subtle")]
#[cfg_attr(docsrs, doc(cfg(feature = "subtle")))]
impl Eq for Ed25519PrivateKey {}

/// Ed25519 private/public keypair.
#[derive(Clone)]
pub struct Ed25519Keypair {
    /// Public key.
    pub public: Ed25519PublicKey,

    /// Private key.
    pub private: Ed25519PrivateKey,
}

impl Ed25519Keypair {
    /// Size of an Ed25519 keypair in bytes.
    pub const BYTE_SIZE: usize = 64;

    /// Generate a random Ed25519 private keypair.
    #[cfg(feature = "ed25519")]
    #[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
    pub fn random(rng: impl CryptoRng + RngCore) -> Self {
        Ed25519PrivateKey::random(rng).into()
    }

    /// Expand a keypair from a 32-byte seed value.
    #[cfg(feature = "ed25519")]
    #[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
    pub fn from_seed(seed: &[u8; Ed25519PrivateKey::BYTE_SIZE]) -> Self {
        Ed25519PrivateKey::from_bytes(seed).into()
    }

    /// Parse Ed25519 keypair from 64-bytes which comprise the serialized
    /// private and public keys.
    pub fn from_bytes(bytes: &[u8; Self::BYTE_SIZE]) -> Result<Self> {
        let (priv_bytes, pub_bytes) = bytes.split_at(Ed25519PrivateKey::BYTE_SIZE);
        let private = Ed25519PrivateKey::try_from(priv_bytes)?;
        let public = Ed25519PublicKey::try_from(pub_bytes)?;

        // Validate the public key if possible
        #[cfg(feature = "ed25519")]
        if Ed25519PublicKey::from(&private) != public {
            return Err(Error::Crypto);
        }

        Ok(Ed25519Keypair { private, public })
    }

    /// Serialize an Ed25519 keypair as bytes.
    pub fn to_bytes(&self) -> [u8; Self::BYTE_SIZE] {
        let mut result = [0u8; Self::BYTE_SIZE];
        result[..(Self::BYTE_SIZE / 2)].copy_from_slice(self.private.as_ref());
        result[(Self::BYTE_SIZE / 2)..].copy_from_slice(self.public.as_ref());
        result
    }
}

impl Decode for Ed25519Keypair {
    fn decode(reader: &mut impl Reader) -> Result<Self> {
        // Decode private key
        let public = Ed25519PublicKey::decode(reader)?;

        // The OpenSSH serialization of Ed25519 keys is repetitive and includes
        // a serialization of `private_key[32] || public_key[32]` immediately
        // following the public key.
        let mut bytes = Zeroizing::new([0u8; Self::BYTE_SIZE]);
        reader.read_nested(|reader| reader.read(&mut *bytes))?;

        let keypair = Self::from_bytes(&*bytes)?;

        // Ensure public key matches the one one the keypair
        if keypair.public == public {
            Ok(keypair)
        } else {
            Err(Error::Crypto)
        }
    }
}

impl Encode for Ed25519Keypair {
    fn encoded_len(&self) -> Result<usize> {
        [4, self.public.encoded_len()?, Self::BYTE_SIZE].checked_sum()
    }

    fn encode(&self, writer: &mut impl Writer) -> Result<()> {
        self.public.encode(writer)?;
        Zeroizing::new(self.to_bytes()).as_ref().encode(writer)
    }
}

impl From<Ed25519Keypair> for Ed25519PublicKey {
    fn from(keypair: Ed25519Keypair) -> Ed25519PublicKey {
        keypair.public
    }
}

impl From<&Ed25519Keypair> for Ed25519PublicKey {
    fn from(keypair: &Ed25519Keypair) -> Ed25519PublicKey {
        keypair.public
    }
}

impl TryFrom<&[u8]> for Ed25519Keypair {
    type Error = Error;

    fn try_from(bytes: &[u8]) -> Result<Self> {
        Ed25519Keypair::from_bytes(bytes.try_into()?)
    }
}

impl fmt::Debug for Ed25519Keypair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Ed25519Keypair")
            .field("public", &self.public)
            .finish_non_exhaustive()
    }
}

#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
impl From<Ed25519PrivateKey> for Ed25519Keypair {
    fn from(private: Ed25519PrivateKey) -> Ed25519Keypair {
        let secret = ed25519_dalek::SecretKey::from(&private);
        let public = ed25519_dalek::PublicKey::from(&secret);

        Ed25519Keypair {
            private,
            public: public.into(),
        }
    }
}

#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
impl TryFrom<Ed25519Keypair> for ed25519_dalek::Keypair {
    type Error = Error;

    fn try_from(key: Ed25519Keypair) -> Result<ed25519_dalek::Keypair> {
        Ok(ed25519_dalek::Keypair {
            secret: key.private.into(),
            public: key.public.try_into()?,
        })
    }
}

#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
impl TryFrom<&Ed25519Keypair> for ed25519_dalek::Keypair {
    type Error = Error;

    fn try_from(key: &Ed25519Keypair) -> Result<ed25519_dalek::Keypair> {
        Ok(ed25519_dalek::Keypair {
            secret: (&key.private).into(),
            public: key.public.try_into()?,
        })
    }
}

#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
impl From<ed25519_dalek::Keypair> for Ed25519Keypair {
    fn from(key: ed25519_dalek::Keypair) -> Ed25519Keypair {
        Ed25519Keypair {
            private: key.secret.into(),
            public: key.public.into(),
        }
    }
}

#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
impl From<&ed25519_dalek::Keypair> for Ed25519Keypair {
    fn from(key: &ed25519_dalek::Keypair) -> Ed25519Keypair {
        Ed25519Keypair {
            private: (&key.secret).into(),
            public: key.public.into(),
        }
    }
}

#[cfg(feature = "subtle")]
#[cfg_attr(docsrs, doc(cfg(feature = "subtle")))]
impl ConstantTimeEq for Ed25519Keypair {
    fn ct_eq(&self, other: &Self) -> Choice {
        Choice::from((self.public == other.public) as u8) & self.private.ct_eq(&other.private)
    }
}

#[cfg(feature = "subtle")]
#[cfg_attr(docsrs, doc(cfg(feature = "subtle")))]
impl PartialEq for Ed25519Keypair {
    fn eq(&self, other: &Self) -> bool {
        self.ct_eq(other).into()
    }
}

#[cfg(feature = "subtle")]
#[cfg_attr(docsrs, doc(cfg(feature = "subtle")))]
impl Eq for Ed25519Keypair {}