libp2prs_core/
identity.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//! A node's network identity keys.
22
23pub mod ed25519;
24#[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
25pub mod rsa;
26#[cfg(feature = "secp256k1")]
27pub mod secp256k1;
28
29pub mod error;
30
31use self::error::*;
32use crate::{keys_proto, PeerId};
33
34/// Identity keypair of a node.
35///
36/// # Example: Generating RSA keys with OpenSSL
37///
38/// ```text
39/// openssl genrsa -out private.pem 2048
40/// openssl pkcs8 -in private.pem -inform PEM -topk8 -out private.pk8 -outform DER -nocrypt
41/// rm private.pem      # optional
42/// ```
43///
44/// Loading the keys:
45///
46/// ```text
47/// let mut bytes = std::fs::read("private.pem").unwrap();
48/// let keypair = Keypair::rsa_from_pkcs8(&mut bytes);
49/// ```
50///
51#[allow(clippy::large_enum_variant)]
52#[derive(Clone)]
53pub enum Keypair {
54    /// An Ed25519 keypair.
55    Ed25519(ed25519::Keypair),
56    #[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
57    /// An RSA keypair.
58    Rsa(rsa::Keypair),
59    /// A Secp256k1 keypair.
60    #[cfg(feature = "secp256k1")]
61    Secp256k1(secp256k1::Keypair),
62}
63
64impl Keypair {
65    /// Generate a fixed Ed25519 keypair, used for test only.
66    pub fn generate_ed25519_fixed() -> Keypair {
67        Keypair::Ed25519(ed25519::Keypair::generate_fixed())
68    }
69
70    /// Generate a new Ed25519 keypair.
71    pub fn generate_ed25519() -> Keypair {
72        Keypair::Ed25519(ed25519::Keypair::generate())
73    }
74
75    /// Generate a new Secp256k1 keypair.
76    #[cfg(feature = "secp256k1")]
77    pub fn generate_secp256k1() -> Keypair {
78        Keypair::Secp256k1(secp256k1::Keypair::generate())
79    }
80
81    /// Decode an keypair from a DER-encoded secret key in PKCS#8 PrivateKeyInfo
82    /// format (i.e. unencrypted) as defined in [RFC5208].
83    ///
84    /// [RFC5208]: https://tools.ietf.org/html/rfc5208#section-5
85    #[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
86    pub fn rsa_from_pkcs8(pkcs8_der: &mut [u8]) -> Result<Keypair, DecodingError> {
87        rsa::Keypair::from_pkcs8(pkcs8_der).map(Keypair::Rsa)
88    }
89
90    /// Decode a keypair from a DER-encoded Secp256k1 secret key in an ECPrivateKey
91    /// structure as defined in [RFC5915].
92    ///
93    /// [RFC5915]: https://tools.ietf.org/html/rfc5915
94    #[cfg(feature = "secp256k1")]
95    pub fn secp256k1_from_der(der: &mut [u8]) -> Result<Keypair, DecodingError> {
96        secp256k1::SecretKey::from_der(der).map(|sk| Keypair::Secp256k1(secp256k1::Keypair::from(sk)))
97    }
98
99    /// Sign a message using the private key of this keypair, producing
100    /// a signature that can be verified using the corresponding public key.
101    pub fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError> {
102        use Keypair::*;
103        match self {
104            Ed25519(ref pair) => Ok(pair.sign(msg)),
105            #[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
106            Rsa(ref pair) => pair.sign(msg),
107            #[cfg(feature = "secp256k1")]
108            Secp256k1(ref pair) => pair.secret().sign(msg),
109        }
110    }
111
112    /// Get the public key of this keypair.
113    pub fn public(&self) -> PublicKey {
114        use Keypair::*;
115        match self {
116            Ed25519(pair) => PublicKey::Ed25519(pair.public()),
117            #[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
118            Rsa(pair) => PublicKey::Rsa(pair.public()),
119            #[cfg(feature = "secp256k1")]
120            Secp256k1(pair) => PublicKey::Secp256k1(pair.public().clone()),
121        }
122    }
123}
124
125/// The public key of a node's identity keypair.
126#[derive(Clone, Debug, PartialEq, Eq)]
127pub enum PublicKey {
128    /// A public Ed25519 key.
129    Ed25519(ed25519::PublicKey),
130    #[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
131    /// A public RSA key.
132    Rsa(rsa::PublicKey),
133    #[cfg(feature = "secp256k1")]
134    /// A public Secp256k1 key.
135    Secp256k1(secp256k1::PublicKey),
136}
137
138impl PublicKey {
139    /// Verify a signature for a message using this public key, i.e. check
140    /// that the signature has been produced by the corresponding
141    /// private key (authenticity), and that the message has not been
142    /// tampered with (integrity).
143    pub fn verify(&self, msg: &[u8], sig: &[u8]) -> bool {
144        use PublicKey::*;
145        match self {
146            Ed25519(pk) => pk.verify(msg, sig),
147            #[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
148            Rsa(pk) => pk.verify(msg, sig),
149            #[cfg(feature = "secp256k1")]
150            Secp256k1(pk) => pk.verify(msg, sig),
151        }
152    }
153
154    /// Encode the public key into a protobuf structure for storage or
155    /// exchange with other nodes.
156    pub fn into_protobuf_encoding(self) -> Vec<u8> {
157        use prost::Message;
158
159        let public_key = match self {
160            PublicKey::Ed25519(key) => keys_proto::PublicKey {
161                r#type: keys_proto::KeyType::Ed25519 as i32,
162                data: key.encode().to_vec(),
163            },
164            #[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
165            PublicKey::Rsa(key) => keys_proto::PublicKey {
166                r#type: keys_proto::KeyType::Rsa as i32,
167                data: key.encode_x509(),
168            },
169            #[cfg(feature = "secp256k1")]
170            PublicKey::Secp256k1(key) => keys_proto::PublicKey {
171                r#type: keys_proto::KeyType::Secp256k1 as i32,
172                data: key.encode().to_vec(),
173            },
174        };
175
176        let mut buf = Vec::with_capacity(public_key.encoded_len());
177        public_key.encode(&mut buf).expect("Vec<u8> provides capacity as needed");
178        buf
179    }
180
181    /// Decode a public key from a protobuf structure, e.g. read from storage
182    /// or received from another node.
183    pub fn from_protobuf_encoding(bytes: &[u8]) -> Result<PublicKey, DecodingError> {
184        use prost::Message;
185
186        #[allow(unused_mut)] // Due to conditional compilation.
187        let mut pubkey = keys_proto::PublicKey::decode(bytes).map_err(|e| DecodingError::new("Protobuf").source(e))?;
188
189        let key_type = keys_proto::KeyType::from_i32(pubkey.r#type)
190            .ok_or_else(|| DecodingError::new(format!("unknown key type: {}", pubkey.r#type)))?;
191
192        match key_type {
193            keys_proto::KeyType::Ed25519 => ed25519::PublicKey::decode(&pubkey.data).map(PublicKey::Ed25519),
194            #[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
195            keys_proto::KeyType::Rsa => rsa::PublicKey::decode_x509(&pubkey.data).map(PublicKey::Rsa),
196            #[cfg(any(target_os = "emscripten", target_os = "unknown"))]
197            keys_proto::KeyType::Rsa => {
198                log::debug!("support for RSA was disabled at compile-time");
199                Err(DecodingError::new("Unsupported"))
200            }
201            #[cfg(feature = "secp256k1")]
202            keys_proto::KeyType::Secp256k1 => secp256k1::PublicKey::decode(&pubkey.data).map(PublicKey::Secp256k1),
203            #[cfg(not(feature = "secp256k1"))]
204            keys_proto::KeyType::Secp256k1 => {
205                log::debug!("support for secp256k1 was disabled at compile-time");
206                Err("Unsupported".to_string().into())
207            }
208        }
209    }
210
211    /// Convert the `PublicKey` into the corresponding `PeerId`.
212    pub fn into_peer_id(self) -> PeerId {
213        self.into()
214    }
215}