tet_libp2p_core/identity/
ed25519.rs

1// Copyright 2019 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21//! Ed25519 keys.
22
23use ed25519_dalek::{self as ed25519, Signer as _, Verifier as _};
24use rand::RngCore;
25use std::convert::TryFrom;
26use super::error::DecodingError;
27use zeroize::Zeroize;
28use core::fmt;
29
30/// An Ed25519 keypair.
31pub struct Keypair(ed25519::Keypair);
32
33impl Keypair {
34    /// Generate a new Ed25519 keypair.
35    pub fn generate() -> Keypair {
36        Keypair::from(SecretKey::generate())
37    }
38
39    /// Encode the keypair into a byte array by concatenating the bytes
40    /// of the secret scalar and the compressed public point,
41    /// an informal standard for encoding Ed25519 keypairs.
42    pub fn encode(&self) -> [u8; 64] {
43        self.0.to_bytes()
44    }
45
46    /// Decode a keypair from the format produced by `encode`,
47    /// zeroing the input on success.
48    pub fn decode(kp: &mut [u8]) -> Result<Keypair, DecodingError> {
49        ed25519::Keypair::from_bytes(kp)
50            .map(|k| { kp.zeroize(); Keypair(k) })
51            .map_err(|e| DecodingError::new("Ed25519 keypair").source(e))
52    }
53
54    /// Sign a message using the private key of this keypair.
55    pub fn sign(&self, msg: &[u8]) -> Vec<u8> {
56        self.0.sign(msg).to_bytes().to_vec()
57    }
58
59    /// Get the public key of this keypair.
60    pub fn public(&self) -> PublicKey {
61        PublicKey(self.0.public)
62    }
63
64    /// Get the secret key of this keypair.
65    pub fn secret(&self) -> SecretKey {
66        SecretKey::from_bytes(&mut self.0.secret.to_bytes())
67            .expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k")
68    }
69}
70
71impl fmt::Debug for Keypair {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.debug_struct("Keypair").field("public", &self.0.public).finish()
74    }
75}
76
77impl Clone for Keypair {
78    fn clone(&self) -> Keypair {
79        let mut sk_bytes = self.0.secret.to_bytes();
80        let secret = SecretKey::from_bytes(&mut sk_bytes)
81            .expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k").0;
82        let public = ed25519::PublicKey::from_bytes(&self.0.public.to_bytes())
83            .expect("ed25519::PublicKey::from_bytes(to_bytes(k)) != k");
84        Keypair(ed25519::Keypair { secret, public })
85    }
86}
87
88/// Demote an Ed25519 keypair to a secret key.
89impl From<Keypair> for SecretKey {
90    fn from(kp: Keypair) -> SecretKey {
91        SecretKey(kp.0.secret)
92    }
93}
94
95/// Promote an Ed25519 secret key into a keypair.
96impl From<SecretKey> for Keypair {
97    fn from(sk: SecretKey) -> Keypair {
98        let secret: ed25519::ExpandedSecretKey = (&sk.0).into();
99        let public = ed25519::PublicKey::from(&secret);
100        Keypair(ed25519::Keypair { secret: sk.0, public })
101    }
102}
103
104/// An Ed25519 public key.
105#[derive(PartialEq, Eq, Debug, Clone)]
106pub struct PublicKey(ed25519::PublicKey);
107
108impl PublicKey {
109    /// Verify the Ed25519 signature on a message using the public key.
110    pub fn verify(&self, msg: &[u8], sig: &[u8]) -> bool {
111        ed25519::Signature::try_from(sig).and_then(|s| self.0.verify(msg, &s)).is_ok()
112    }
113
114    /// Encode the public key into a byte array in compressed form, i.e.
115    /// where one coordinate is represented by a single bit.
116    pub fn encode(&self) -> [u8; 32] {
117        self.0.to_bytes()
118    }
119
120    /// Decode a public key from a byte array as produced by `encode`.
121    pub fn decode(k: &[u8]) -> Result<PublicKey, DecodingError> {
122        ed25519::PublicKey::from_bytes(k)
123            .map_err(|e| DecodingError::new("Ed25519 public key").source(e))
124            .map(PublicKey)
125    }
126}
127
128/// An Ed25519 secret key.
129pub struct SecretKey(ed25519::SecretKey);
130
131/// View the bytes of the secret key.
132impl AsRef<[u8]> for SecretKey {
133    fn as_ref(&self) -> &[u8] {
134        self.0.as_bytes()
135    }
136}
137
138impl Clone for SecretKey {
139    fn clone(&self) -> SecretKey {
140        let mut sk_bytes = self.0.to_bytes();
141        Self::from_bytes(&mut sk_bytes)
142            .expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k")
143    }
144}
145
146impl fmt::Debug for SecretKey {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        write!(f, "SecretKey")
149    }
150}
151
152impl SecretKey {
153    /// Generate a new Ed25519 secret key.
154    pub fn generate() -> SecretKey {
155        let mut bytes = [0u8; 32];
156        rand::thread_rng().fill_bytes(&mut bytes);
157        SecretKey(ed25519::SecretKey::from_bytes(&bytes)
158            .expect("this returns `Err` only if the length is wrong; the length is correct; qed"))
159    }
160
161    /// Create an Ed25519 secret key from a byte slice, zeroing the input on success.
162    /// If the bytes do not constitute a valid Ed25519 secret key, an error is
163    /// returned.
164    pub fn from_bytes(mut sk_bytes: impl AsMut<[u8]>) -> Result<SecretKey, DecodingError> {
165        let sk_bytes = sk_bytes.as_mut();
166        let secret = ed25519::SecretKey::from_bytes(&*sk_bytes)
167            .map_err(|e| DecodingError::new("Ed25519 secret key").source(e))?;
168        sk_bytes.zeroize();
169        Ok(SecretKey(secret))
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use quickcheck::*;
177
178    fn eq_keypairs(kp1: &Keypair, kp2: &Keypair) -> bool {
179        kp1.public() == kp2.public()
180            &&
181        kp1.0.secret.as_bytes() == kp2.0.secret.as_bytes()
182    }
183
184    #[test]
185    fn ed25519_keypair_encode_decode() {
186        fn prop() -> bool {
187            let kp1 = Keypair::generate();
188            let mut kp1_enc = kp1.encode();
189            let kp2 = Keypair::decode(&mut kp1_enc).unwrap();
190            eq_keypairs(&kp1, &kp2)
191                &&
192            kp1_enc.iter().all(|b| *b == 0)
193        }
194        QuickCheck::new().tests(10).quickcheck(prop as fn() -> _);
195    }
196
197    #[test]
198    fn ed25519_keypair_from_secret() {
199        fn prop() -> bool {
200            let kp1 = Keypair::generate();
201            let mut sk = kp1.0.secret.to_bytes();
202            let kp2 = Keypair::from(SecretKey::from_bytes(&mut sk).unwrap());
203            eq_keypairs(&kp1, &kp2)
204                &&
205            sk == [0u8; 32]
206        }
207        QuickCheck::new().tests(10).quickcheck(prop as fn() -> _);
208    }
209
210    #[test]
211    fn ed25519_signature() {
212        let kp = Keypair::generate();
213        let pk = kp.public();
214
215        let msg = "hello world".as_bytes();
216        let sig = kp.sign(msg);
217        assert!(pk.verify(msg, &sig));
218
219        let mut invalid_sig = sig.clone();
220        invalid_sig[3..6].copy_from_slice(&[10, 23, 42]);
221        assert!(!pk.verify(msg, &invalid_sig));
222
223        let invalid_msg = "h3ll0 w0rld".as_bytes();
224        assert!(!pk.verify(invalid_msg, &sig));
225    }
226}