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
//! Aes Encrypted communication and handshake process implementation

#![deny(missing_docs)]
use rand::RngCore;

pub use crate::{handshake::handshake_struct::PublicKey, peer_id::PeerId};

/// Encrypted and decrypted codec implementation, and stream handle
pub mod codec;
/// Symmetric ciphers algorithms
pub mod crypto;
mod dh_compat;
/// Error type
pub mod error;
/// Implementation of the handshake process
pub mod handshake;
/// Peer id
pub mod peer_id;
/// A little encapsulation of secp256k1
mod secp256k1_compat;
mod sha256_compat;
/// Supported algorithms
mod support;

/// Public key generated temporarily during the handshake
pub type EphemeralPublicKey = Vec<u8>;

/// Key pair of asymmetric encryption algorithm
#[derive(Clone, Debug)]
pub struct SecioKeyPair {
    inner: KeyPairInner,
}

impl SecioKeyPair {
    /// Generates a new random sec256k1 key pair.
    pub fn secp256k1_generated() -> SecioKeyPair {
        loop {
            let mut key = [0; crate::secp256k1_compat::SECRET_KEY_SIZE];
            rand::thread_rng().fill_bytes(&mut key);
            if let Ok(private) = crate::secp256k1_compat::secret_key_from_slice(&key) {
                return SecioKeyPair {
                    inner: KeyPairInner::Secp256k1 { private },
                };
            }
        }
    }

    /// Builds a `SecioKeyPair` from a raw secp256k1 32 bytes private key.
    pub fn secp256k1_raw_key<K>(key: K) -> Result<SecioKeyPair, error::SecioError>
    where
        K: AsRef<[u8]>,
    {
        let private = crate::secp256k1_compat::secret_key_from_slice(key.as_ref())
            .map_err(|_| error::SecioError::SecretGenerationFailed)?;

        Ok(SecioKeyPair {
            inner: KeyPairInner::Secp256k1 { private },
        })
    }

    /// Returns the public key corresponding to this key pair.
    pub fn public_key(&self) -> PublicKey {
        match self.inner {
            KeyPairInner::Secp256k1 { ref private } => {
                let pubkey = crate::secp256k1_compat::from_secret_key(private);
                PublicKey {
                    key: crate::secp256k1_compat::serialize_pubkey(&pubkey),
                }
            }
        }
    }

    /// Generate Peer id
    pub fn peer_id(&self) -> PeerId {
        self.public_key().peer_id()
    }
}

#[derive(Clone)]
enum KeyPairInner {
    Secp256k1 {
        private: crate::secp256k1_compat::SecretKey,
    },
}

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

/// Possible digest algorithms.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Digest {
    /// Sha256 digest
    Sha256,
    /// Sha512 digest
    Sha512,
}

impl Digest {
    /// Returns the size in bytes of a digest of this kind.
    #[inline]
    pub fn num_bytes(self) -> usize {
        match self {
            Digest::Sha256 => 256 / 8,
            Digest::Sha512 => 512 / 8,
        }
    }
}

/// KeyProvider on ecdh procedure
#[cfg_attr(all(target_arch = "wasm32", feature = "async-trait"), async_trait::async_trait(?Send))]
#[cfg_attr(
    all(not(target_arch = "wasm32"), feature = "async-trait"),
    async_trait::async_trait
)]
pub trait KeyProvider: std::clone::Clone + Send + Sync + 'static {
    /// Error
    type Error: Into<crate::error::SecioError>;

    /// Constructs a signature for `msg` using the secret key `sk`
    #[cfg(feature = "async-trait")]
    async fn sign_ecdsa_async<T: AsRef<[u8]> + Send>(
        &self,
        message: T,
    ) -> Result<Vec<u8>, Self::Error> {
        self.sign_ecdsa(message)
    }

    /// Constructs a signature for `msg` using the secret key `sk`
    fn sign_ecdsa<T: AsRef<[u8]>>(&self, message: T) -> Result<Vec<u8>, Self::Error>;

    /// Creates a new public key from the [`KeyProvider`].
    fn pubkey(&self) -> Vec<u8>;

    /// Checks that `sig` is a valid ECDSA signature for `msg` using the pubkey.
    fn verify_ecdsa<P, T, F>(&self, pubkey: P, message: T, signature: F) -> bool
    where
        P: AsRef<[u8]>,
        T: AsRef<[u8]>,
        F: AsRef<[u8]>;
}

impl KeyProvider for SecioKeyPair {
    type Error = error::SecioError;

    fn sign_ecdsa<T: AsRef<[u8]>>(&self, message: T) -> Result<Vec<u8>, Self::Error> {
        let msg = match crate::secp256k1_compat::message_from_slice(message.as_ref()) {
            Ok(m) => m,
            Err(_) => {
                log::debug!("message has wrong format");
                return Err(error::SecioError::InvalidMessage);
            }
        };
        let signature = match self.inner {
            KeyPairInner::Secp256k1 { ref private } => crate::secp256k1_compat::sign(&msg, private),
        };

        Ok(crate::secp256k1_compat::signature_to_vec(signature))
    }

    fn pubkey(&self) -> Vec<u8> {
        match self.inner {
            KeyPairInner::Secp256k1 { ref private } => crate::secp256k1_compat::serialize_pubkey(
                &crate::secp256k1_compat::from_secret_key(private),
            ),
        }
    }

    fn verify_ecdsa<P, T, F>(&self, pubkey: P, message: T, signature: F) -> bool
    where
        P: AsRef<[u8]>,
        T: AsRef<[u8]>,
        F: AsRef<[u8]>,
    {
        let signature = crate::secp256k1_compat::signature_from_der(signature.as_ref());
        let msg = crate::secp256k1_compat::message_from_slice(message.as_ref());
        let pubkey = crate::secp256k1_compat::pubkey_from_slice(pubkey.as_ref());

        if let (Ok(signature), Ok(message), Ok(pubkey)) = (signature, msg, pubkey) {
            if !crate::secp256k1_compat::verify(&message, &signature, &pubkey) {
                log::debug!("failed to verify the remote's signature");
                return false;
            }
        } else {
            log::debug!("remote's secp256k1 signature has wrong format");
            return false;
        }
        true
    }
}
/// Empty key provider
#[derive(Debug, Clone)]
pub struct NoopKeyProvider;

impl KeyProvider for NoopKeyProvider {
    type Error = error::SecioError;

    fn sign_ecdsa<T: AsRef<[u8]>>(&self, _message: T) -> Result<Vec<u8>, Self::Error> {
        Err(error::SecioError::NotSupportKeyProvider)
    }

    fn pubkey(&self) -> Vec<u8> {
        Vec::new()
    }

    fn verify_ecdsa<P, T, F>(&self, _pubkey: P, _message: T, _signature: F) -> bool
    where
        P: AsRef<[u8]>,
        T: AsRef<[u8]>,
        F: AsRef<[u8]>,
    {
        false
    }
}