Consolidate keypairs in core. (#972)

* Consolidate keypairs in core.

Introduce the concept of a node's identity keypair in libp2p-core,
instead of only the public key:

  * New module: libp2p_core::identity with submodules for the currently
    supported key types. An identity::Keypair and identity::PublicKey
    support the creation and verification of signatures. The public key
    supports encoding/decoding according to the libp2p specs.

  * The secio protocol is simplified as a result of moving code to libp2p-core.

  * The noise protocol is slightly simplified by consolidating ed25519
    keypairs in libp2p-core and using x25519-dalek for DH. Furthermore,
    Ed25519 to X25519 keypair conversion is now complete and tested.

Generalise over the DH keys in the noise protocol.

Generalise over the DH keys and thus DH parameter in handshake patterns
of the Noise protocol, such that it is easy to support other DH schemes
in the future, e.g. X448.

* Address new review comments.
This commit is contained in:
Roman Borschel
2019-03-11 13:42:53 +01:00
committed by GitHub
parent 26df15641c
commit 2c66f82b11
37 changed files with 1742 additions and 1020 deletions

216
core/src/identity.rs Normal file
View File

@ -0,0 +1,216 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//! A node's network identity keys.
pub mod ed25519;
#[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
pub mod rsa;
#[cfg(feature = "secp256k1")]
pub mod secp256k1;
pub mod error;
use self::error::*;
use crate::{PeerId, keys_proto};
/// Identity keypair of a node.
///
/// # Example: Generating RSA keys with OpenSSL
///
/// ```text
/// openssl genrsa -out private.pem 2048
/// openssl pkcs8 -in private.pem -inform PEM -topk8 -out private.pk8 -outform DER -nocrypt
/// rm private.pem # optional
/// ```
///
/// Loading the keys:
///
/// ```text
/// let mut bytes = std::fs::read("private.pem").unwrap();
/// let keypair = Keypair::rsa_from_pkcs8(&mut bytes);
/// ```
///
#[derive(Clone)]
pub enum Keypair {
/// An Ed25519 keypair.
Ed25519(ed25519::Keypair),
#[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
/// An RSA keypair.
Rsa(rsa::Keypair),
/// A Secp256k1 keypair.
#[cfg(feature = "secp256k1")]
Secp256k1(secp256k1::Keypair)
}
impl Keypair {
/// Generate a new Ed25519 keypair.
pub fn generate_ed25519() -> Keypair {
Keypair::Ed25519(ed25519::Keypair::generate())
}
/// Generate a new Secp256k1 keypair.
#[cfg(feature = "secp256k1")]
pub fn generate_secp256k1() -> Keypair {
Keypair::Secp256k1(secp256k1::Keypair::generate())
}
/// Decode an keypair from a DER-encoded secret key in PKCS#8 PrivateKeyInfo
/// format (i.e. unencrypted) as defined in [RFC5208].
///
/// [RFC5208]: https://tools.ietf.org/html/rfc5208#section-5
#[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
pub fn rsa_from_pkcs8(pkcs8_der: &mut [u8]) -> Result<Keypair, DecodingError> {
rsa::Keypair::from_pkcs8(pkcs8_der).map(Keypair::Rsa)
}
/// Decode a keypair from a DER-encoded Secp256k1 secret key in an ECPrivateKey
/// structure as defined in [RFC5915].
///
/// [RFC5915]: https://tools.ietf.org/html/rfc5915
#[cfg(feature = "secp256k1")]
pub fn secp256k1_from_der(der: &mut [u8]) -> Result<Keypair, DecodingError> {
secp256k1::SecretKey::from_der(der)
.map(|sk| Keypair::Secp256k1(secp256k1::Keypair::from(sk)))
}
/// Sign a message using the private key of this keypair, producing
/// a signature that can be verified using the corresponding public key.
pub fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError> {
use Keypair::*;
match self {
Ed25519(ref pair) => Ok(pair.sign(msg)),
#[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
Rsa(ref pair) => pair.sign(msg),
#[cfg(feature = "secp256k1")]
Secp256k1(ref pair) => Ok(pair.secret().sign(msg)),
}
}
/// Get the public key of this keypair.
pub fn public(&self) -> PublicKey {
use Keypair::*;
match self {
Ed25519(pair) => PublicKey::Ed25519(pair.public()),
#[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
Rsa(pair) => PublicKey::Rsa(pair.public()),
#[cfg(feature = "secp256k1")]
Secp256k1(pair) => PublicKey::Secp256k1(pair.public().clone()),
}
}
}
/// The public key of a node's identity keypair.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PublicKey {
/// A public Ed25519 key.
Ed25519(ed25519::PublicKey),
#[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
/// A public RSA key.
Rsa(rsa::PublicKey),
#[cfg(feature = "secp256k1")]
/// A public Secp256k1 key.
Secp256k1(secp256k1::PublicKey)
}
impl PublicKey {
/// Verify a signature for a message using this public key, i.e. check
/// that the signature has been produced by the corresponding
/// private key (authenticity), and that the message has not been
/// tampered with (integrity).
pub fn verify(&self, msg: &[u8], sig: &[u8]) -> bool {
use PublicKey::*;
match self {
Ed25519(pk) => pk.verify(msg, sig),
#[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
Rsa(pk) => pk.verify(msg, sig),
#[cfg(feature = "secp256k1")]
Secp256k1(pk) => pk.verify(msg, sig)
}
}
/// Encode the public key into a protobuf structure for storage or
/// exchange with other nodes.
pub fn into_protobuf_encoding(self) -> Vec<u8> {
use protobuf::Message;
let mut public_key = keys_proto::PublicKey::new();
match self {
PublicKey::Ed25519(key) => {
public_key.set_Type(keys_proto::KeyType::Ed25519);
public_key.set_Data(key.encode().to_vec());
},
#[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
PublicKey::Rsa(key) => {
public_key.set_Type(keys_proto::KeyType::RSA);
public_key.set_Data(key.encode_x509());
},
#[cfg(feature = "secp256k1")]
PublicKey::Secp256k1(key) => {
public_key.set_Type(keys_proto::KeyType::Secp256k1);
public_key.set_Data(key.encode().to_vec());
},
};
public_key
.write_to_bytes()
.expect("Encoding public key into protobuf failed.")
}
/// Decode a public key from a protobuf structure, e.g. read from storage
/// or received from another node.
pub fn from_protobuf_encoding(bytes: &[u8]) -> Result<PublicKey, DecodingError> {
#[allow(unused_mut)] // Due to conditional compilation.
let mut pubkey = protobuf::parse_from_bytes::<keys_proto::PublicKey>(bytes)
.map_err(|e| DecodingError::new("Protobuf", e))?;
match pubkey.get_Type() {
keys_proto::KeyType::Ed25519 => {
ed25519::PublicKey::decode(pubkey.get_Data())
.map(PublicKey::Ed25519)
},
#[cfg(not(any(target_os = "emscripten", target_os = "unknown")))]
keys_proto::KeyType::RSA => {
rsa::PublicKey::decode_x509(&pubkey.take_Data())
.map(PublicKey::Rsa)
}
#[cfg(any(target_os = "emscripten", target_os = "unknown"))]
keys_proto::KeyType::RSA => {
log::debug!("support for RSA was disabled at compile-time");
Err("Unsupported".to_string().into())
},
#[cfg(feature = "secp256k1")]
keys_proto::KeyType::Secp256k1 => {
secp256k1::PublicKey::decode(pubkey.get_Data())
.map(PublicKey::Secp256k1)
}
#[cfg(not(feature = "secp256k1"))]
keys_proto::KeyType::Secp256k1 => {
log::debug!("support for secp256k1 was disabled at compile-time");
Err("Unsupported".to_string().into())
},
}
}
/// Convert the `PublicKey` into the corresponding `PeerId`.
pub fn into_peer_id(self) -> PeerId {
self.into()
}
}

View File

@ -0,0 +1,193 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//! Ed25519 keys.
use ed25519_dalek as ed25519;
use failure::Fail;
use super::error::DecodingError;
use zeroize::Zeroize;
/// An Ed25519 keypair.
pub struct Keypair(ed25519::Keypair);
impl Keypair {
/// Generate a new Ed25519 keypair.
pub fn generate() -> Keypair {
Keypair(ed25519::Keypair::generate(&mut rand::thread_rng()))
}
/// Encode the keypair into a byte array by concatenating the bytes
/// of the secret scalar and the compressed public point,
/// an informal standard for encoding Ed25519 keypairs.
pub fn encode(&self) -> [u8; 64] {
self.0.to_bytes()
}
/// Decode a keypair from the format produced by `encode`,
/// zeroing the input on success.
pub fn decode(kp: &mut [u8]) -> Result<Keypair, DecodingError> {
ed25519::Keypair::from_bytes(kp)
.map(|k| { kp.zeroize(); Keypair(k) })
.map_err(|e| DecodingError::new("Ed25519 keypair", e.compat()))
}
/// Sign a message using the private key of this keypair.
pub fn sign(&self, msg: &[u8]) -> Vec<u8> {
self.0.sign(msg).to_bytes().to_vec()
}
/// Get the public key of this keypair.
pub fn public(&self) -> PublicKey {
PublicKey(self.0.public)
}
/// Get the secret key of this keypair.
pub fn secret(&self) -> SecretKey {
SecretKey::from_bytes(&mut self.0.secret.to_bytes())
.expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k")
}
}
impl Clone for Keypair {
fn clone(&self) -> Keypair {
let mut sk_bytes = self.0.secret.to_bytes();
let secret = SecretKey::from_bytes(&mut sk_bytes)
.expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k").0;
let public = ed25519::PublicKey::from_bytes(&self.0.public.to_bytes())
.expect("ed25519::PublicKey::from_bytes(to_bytes(k)) != k");
Keypair(ed25519::Keypair { secret, public })
}
}
/// Demote an Ed25519 keypair to a secret key.
impl From<Keypair> for SecretKey {
fn from(kp: Keypair) -> SecretKey {
SecretKey(kp.0.secret)
}
}
/// Promote an Ed25519 secret key into a keypair.
impl From<SecretKey> for Keypair {
fn from(sk: SecretKey) -> Keypair {
let secret = sk.0;
let public = ed25519::PublicKey::from(&secret);
Keypair(ed25519::Keypair { secret, public })
}
}
/// An Ed25519 public key.
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct PublicKey(ed25519::PublicKey);
impl PublicKey {
/// Verify the Ed25519 signature on a message using the public key.
pub fn verify(&self, msg: &[u8], sig: &[u8]) -> bool {
ed25519::Signature::from_bytes(sig).map(|s| self.0.verify(msg, &s)).is_ok()
}
/// Encode the public key into a byte array in compressed form, i.e.
/// where one coordinate is represented by a single bit.
pub fn encode(&self) -> [u8; 32] {
self.0.to_bytes()
}
/// Decode a public key from a byte array as produced by `encode`.
pub fn decode(k: &[u8]) -> Result<PublicKey, DecodingError> {
ed25519::PublicKey::from_bytes(k)
.map_err(|e| DecodingError::new("Ed25519 public key", e.compat()))
.map(PublicKey)
}
}
/// An Ed25519 secret key.
pub struct SecretKey(ed25519::SecretKey);
/// View the bytes of the secret key.
impl AsRef<[u8]> for SecretKey {
fn as_ref(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl Clone for SecretKey {
fn clone(&self) -> SecretKey {
let mut sk_bytes = self.0.to_bytes();
Self::from_bytes(&mut sk_bytes)
.expect("ed25519::SecretKey::from_bytes(to_bytes(k)) != k")
}
}
impl SecretKey {
/// Generate a new Ed25519 secret key.
pub fn generate() -> SecretKey {
SecretKey(ed25519::SecretKey::generate(&mut rand::thread_rng()))
}
/// Create an Ed25519 secret key from a byte slice, zeroing the input on success.
/// If the bytes do not constitute a valid Ed25519 secret key, an error is
/// returned.
pub fn from_bytes(mut sk_bytes: impl AsMut<[u8]>) -> Result<SecretKey, DecodingError> {
let sk_bytes = sk_bytes.as_mut();
let secret = ed25519::SecretKey::from_bytes(&*sk_bytes)
.map_err(|e| DecodingError::new("Ed25519 secret key", e.compat()))?;
sk_bytes.zeroize();
Ok(SecretKey(secret))
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::*;
fn eq_keypairs(kp1: &Keypair, kp2: &Keypair) -> bool {
kp1.public() == kp2.public()
&&
kp1.0.secret.as_bytes() == kp2.0.secret.as_bytes()
}
#[test]
fn ed25519_keypair_encode_decode() {
fn prop() -> bool {
let kp1 = Keypair::generate();
let mut kp1_enc = kp1.encode();
let kp2 = Keypair::decode(&mut kp1_enc).unwrap();
eq_keypairs(&kp1, &kp2)
&&
kp1_enc.iter().all(|b| *b == 0)
}
QuickCheck::new().tests(10).quickcheck(prop as fn() -> _);
}
#[test]
fn ed25519_keypair_from_secret() {
fn prop() -> bool {
let kp1 = Keypair::generate();
let mut sk = kp1.0.secret.to_bytes();
let kp2 = Keypair::from(SecretKey::from_bytes(&mut sk).unwrap());
eq_keypairs(&kp1, &kp2)
&&
sk == [0u8; 32]
}
QuickCheck::new().tests(10).quickcheck(prop as fn() -> _);
}
}

View File

@ -0,0 +1,88 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//! Errors during identity key operations.
use std::error::Error;
use std::fmt;
/// An error during decoding of key material.
#[derive(Debug)]
pub struct DecodingError {
msg: String,
source: Option<Box<dyn Error + Send + Sync>>
}
impl DecodingError {
pub(crate) fn new(msg: &str, source: impl Error + Send + Sync + 'static) -> DecodingError {
DecodingError { msg: msg.to_string(), source: Some(Box::new(source)) }
}
}
impl From<String> for DecodingError {
fn from(s: String) -> DecodingError {
DecodingError { msg: s, source: None }
}
}
impl fmt::Display for DecodingError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Key decoding error: {}", self.msg)
}
}
impl Error for DecodingError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_ref().map(|s| &**s as &dyn Error)
}
}
/// An error during signing of a message.
#[derive(Debug)]
pub struct SigningError {
msg: String,
source: Option<Box<dyn Error + Send + Sync>>
}
/// An error during encoding of key material.
impl SigningError {
pub(crate) fn new(msg: &str, source: impl Error + Send + Sync + 'static) -> SigningError {
SigningError { msg: msg.to_string(), source: Some(Box::new(source)) }
}
}
impl fmt::Display for SigningError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Key signing error: {}", self.msg)
}
}
impl From<String> for SigningError {
fn from(s: String) -> SigningError {
SigningError { msg: s, source: None }
}
}
impl Error for SigningError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_ref().map(|s| &**s as &dyn Error)
}
}

259
core/src/identity/rsa.rs Normal file
View File

@ -0,0 +1,259 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//! RSA keys.
use asn1_der::{Asn1Der, FromDerObject, IntoDerObject, DerObject, DerTag, DerValue, Asn1DerError};
use lazy_static::lazy_static;
use super::error::*;
use ring::rand::SystemRandom;
use ring::signature::{self, RsaKeyPair, RSA_PKCS1_SHA256, RSA_PKCS1_2048_8192_SHA256};
use ring::signature::KeyPair;
use std::sync::Arc;
use untrusted::Input;
use zeroize::Zeroize;
/// An RSA keypair.
#[derive(Clone)]
pub struct Keypair(Arc<RsaKeyPair>);
impl Keypair {
/// Decode an RSA keypair from a DER-encoded private key in PKCS#8 PrivateKeyInfo
/// format (i.e. unencrypted) as defined in [RFC5208].
///
/// [RFC5208]: https://tools.ietf.org/html/rfc5208#section-5
pub fn from_pkcs8(der: &mut [u8]) -> Result<Keypair, DecodingError> {
let kp = RsaKeyPair::from_pkcs8(Input::from(&der[..]))
.map_err(|e| DecodingError::new("RSA PKCS#8 PrivateKeyInfo", e))?;
der.zeroize();
Ok(Keypair(Arc::new(kp)))
}
/// Get the public key from the keypair.
pub fn public(&self) -> PublicKey {
PublicKey(self.0.public_key().as_ref().to_vec())
}
/// Sign a message with this keypair.
pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>, SigningError> {
let mut signature = vec![0; self.0.public_modulus_len()];
let rng = SystemRandom::new();
match self.0.sign(&RSA_PKCS1_SHA256, &rng, &data, &mut signature) {
Ok(()) => Ok(signature),
Err(e) => Err(SigningError::new("RSA", e))
}
}
}
/// An RSA public key.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct PublicKey(Vec<u8>);
impl PublicKey {
/// Verify an RSA signature on a message using the public key.
pub fn verify(&self, msg: &[u8], sig: &[u8]) -> bool {
signature::verify(&RSA_PKCS1_2048_8192_SHA256,
Input::from(&self.0),
Input::from(msg),
Input::from(sig)).is_ok()
}
/// Encode the RSA public key in DER as a PKCS#1 RSAPublicKey structure,
/// as defined in [RFC3447].
///
/// [RFC3447]: https://tools.ietf.org/html/rfc3447#appendix-A.1.1
pub fn encode_pkcs1(&self) -> Vec<u8> {
// This is the encoding currently used in-memory, so it is trivial.
self.0.clone()
}
/// Encode the RSA public key in DER as a X.509 SubjectPublicKeyInfo structure,
/// as defined in [RFC5280].
///
/// [RFC5280] https://tools.ietf.org/html/rfc5280#section-4.1
pub fn encode_x509(&self) -> Vec<u8> {
let spki = Asn1SubjectPublicKeyInfo {
algorithmIdentifier: Asn1RsaEncryption {
algorithm: Asn1OidRsaEncryption(),
parameters: ()
},
subjectPublicKey: Asn1SubjectPublicKey(self.clone())
};
let mut buf = vec![0u8; spki.serialized_len()];
spki.serialize(buf.iter_mut()).map(|_| buf)
.expect("RSA X.509 public key encoding failed.")
}
/// Decode an RSA public key from a DER-encoded X.509 SubjectPublicKeyInfo
/// structure. See also `encode_x509`.
pub fn decode_x509(pk: &[u8]) -> Result<PublicKey, DecodingError> {
Asn1SubjectPublicKeyInfo::deserialize(pk.iter())
.map_err(|e| DecodingError::new("RSA X.509", e))
.map(|spki| spki.subjectPublicKey.0)
}
}
//////////////////////////////////////////////////////////////////////////////
// DER encoding / decoding of public keys
//
// Primer: http://luca.ntop.org/Teaching/Appunti/asn1.html
// Playground: https://lapo.it/asn1js/
lazy_static! {
/// The DER encoding of the object identifier (OID) 'rsaEncryption' for
/// RSA public keys defined for X.509 in [RFC-3279] and used in
/// SubjectPublicKeyInfo structures defined in [RFC-5280].
///
/// [RFC-3279]: https://tools.ietf.org/html/rfc3279#section-2.3.1
/// [RFC-5280]: https://tools.ietf.org/html/rfc5280#section-4.1
static ref OID_RSA_ENCRYPTION_DER: DerObject =
DerObject {
tag: DerTag::x06,
value: DerValue {
data: vec![ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 ]
}
};
}
/// The ASN.1 OID for "rsaEncryption".
#[derive(Clone)]
struct Asn1OidRsaEncryption();
impl IntoDerObject for Asn1OidRsaEncryption {
fn into_der_object(self) -> DerObject {
OID_RSA_ENCRYPTION_DER.clone()
}
fn serialized_len(&self) -> usize {
OID_RSA_ENCRYPTION_DER.serialized_len()
}
}
impl FromDerObject for Asn1OidRsaEncryption {
fn from_der_object(o: DerObject) -> Result<Self, Asn1DerError> {
if o.tag != DerTag::x06 {
return Err(Asn1DerError::InvalidTag)
}
if o.value != OID_RSA_ENCRYPTION_DER.value {
return Err(Asn1DerError::InvalidEncoding)
}
Ok(Asn1OidRsaEncryption())
}
}
/// The ASN.1 AlgorithmIdentifier for "rsaEncryption".
#[derive(Asn1Der)]
struct Asn1RsaEncryption {
algorithm: Asn1OidRsaEncryption,
parameters: ()
}
/// The ASN.1 SubjectPublicKey inside a SubjectPublicKeyInfo,
/// i.e. encoded as a DER BIT STRING.
struct Asn1SubjectPublicKey(PublicKey);
impl IntoDerObject for Asn1SubjectPublicKey {
fn into_der_object(self) -> DerObject {
let pk_der = (self.0).0;
let mut bit_string = Vec::with_capacity(pk_der.len() + 1);
// The number of bits in pk_der is trivially always a multiple of 8,
// so there are always 0 "unused bits" signaled by the first byte.
bit_string.push(0u8);
bit_string.extend(pk_der);
DerObject::new(DerTag::x03, bit_string.into())
}
fn serialized_len(&self) -> usize {
DerObject::compute_serialized_len((self.0).0.len() + 1)
}
}
impl FromDerObject for Asn1SubjectPublicKey {
fn from_der_object(o: DerObject) -> Result<Self, Asn1DerError> {
if o.tag != DerTag::x03 {
return Err(Asn1DerError::InvalidTag)
}
let pk_der: Vec<u8> = o.value.data.into_iter().skip(1).collect();
// We don't parse pk_der further as an ASN.1 RsaPublicKey, since
// we only need the DER encoding for `verify`.
Ok(Asn1SubjectPublicKey(PublicKey(pk_der)))
}
}
/// ASN.1 SubjectPublicKeyInfo
#[derive(Asn1Der)]
#[allow(non_snake_case)]
struct Asn1SubjectPublicKeyInfo {
algorithmIdentifier: Asn1RsaEncryption,
subjectPublicKey: Asn1SubjectPublicKey
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::*;
use rand::seq::SliceRandom;
use std::fmt;
const KEY1: &'static [u8] = include_bytes!("test/rsa-2048.pk8");
const KEY2: &'static [u8] = include_bytes!("test/rsa-3072.pk8");
const KEY3: &'static [u8] = include_bytes!("test/rsa-4096.pk8");
#[derive(Clone)]
struct SomeKeypair(Keypair);
impl fmt::Debug for SomeKeypair {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SomeKeypair")
}
}
impl Arbitrary for SomeKeypair {
fn arbitrary<G: Gen>(g: &mut G) -> SomeKeypair {
let mut key = [KEY1, KEY2, KEY3].choose(g).unwrap().to_vec();
SomeKeypair(Keypair::from_pkcs8(&mut key).unwrap())
}
}
#[test]
fn rsa_from_pkcs8() {
assert!(Keypair::from_pkcs8(&mut KEY1.to_vec()).is_ok());
assert!(Keypair::from_pkcs8(&mut KEY2.to_vec()).is_ok());
assert!(Keypair::from_pkcs8(&mut KEY3.to_vec()).is_ok());
}
#[test]
fn rsa_x509_encode_decode() {
fn prop(SomeKeypair(kp): SomeKeypair) -> Result<bool, String> {
let pk = kp.public();
PublicKey::decode_x509(&pk.encode_x509())
.map_err(|e| e.to_string())
.map(|pk2| pk2 == pk)
}
QuickCheck::new().tests(10).quickcheck(prop as fn(_) -> _);
}
#[test]
fn rsa_sign_verify() {
fn prop(SomeKeypair(kp): SomeKeypair, msg: Vec<u8>) -> Result<bool, SigningError> {
kp.sign(&msg).map(|s| kp.public().verify(&msg, &s))
}
QuickCheck::new().tests(10).quickcheck(prop as fn(_,_) -> _);
}
}

View File

@ -0,0 +1,158 @@
// Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//! Secp256k1 keys.
use asn1_der::{FromDerObject, DerObject};
use lazy_static::lazy_static;
use sha2::{Digest as ShaDigestTrait, Sha256};
use secp256k1 as secp;
use secp::{Message, Signature};
use super::error::DecodingError;
use zeroize::Zeroize;
// Cached `Secp256k1` context, to avoid recreating it every time.
lazy_static! {
static ref SECP: secp::Secp256k1<secp::All> = secp::Secp256k1::new();
}
/// A Secp256k1 keypair.
#[derive(Clone)]
pub struct Keypair {
secret: SecretKey,
public: PublicKey
}
impl Keypair {
/// Generate a new sec256k1 `Keypair`.
pub fn generate() -> Keypair {
Keypair::from(SecretKey::generate())
}
/// Get the public key of this keypair.
pub fn public(&self) -> &PublicKey {
&self.public
}
/// Get the secret key of this keypair.
pub fn secret(&self) -> &SecretKey {
&self.secret
}
}
/// Promote a Secp256k1 secret key into a keypair.
impl From<SecretKey> for Keypair {
fn from(secret: SecretKey) -> Keypair {
let public = PublicKey(secp::key::PublicKey::from_secret_key(&SECP, &secret.0));
Keypair { secret, public }
}
}
/// Demote a Secp256k1 keypair into a secret key.
impl From<Keypair> for SecretKey {
fn from(kp: Keypair) -> SecretKey {
kp.secret
}
}
/// A Secp256k1 secret key.
#[derive(Clone)]
pub struct SecretKey(secp::key::SecretKey);
/// View the bytes of the secret key.
impl AsRef<[u8]> for SecretKey {
fn as_ref(&self) -> &[u8] {
&self.0[..]
}
}
impl SecretKey {
/// Generate a new Secp256k1 secret key.
pub fn generate() -> SecretKey {
SecretKey(secp::key::SecretKey::new(&mut secp::rand::thread_rng()))
}
/// Create a secret key from a byte slice, zeroing the slice on success.
/// If the bytes do not constitute a valid Secp256k1 secret key, an
/// error is returned.
pub fn from_bytes(mut sk: impl AsMut<[u8]>) -> Result<SecretKey, DecodingError> {
let sk_bytes = sk.as_mut();
let secret = secp::key::SecretKey::from_slice(&*sk_bytes)
.map_err(|e| DecodingError::new("Secp256k1 secret key", e))?;
Ok(SecretKey(secret))
}
/// Decode a DER-encoded Secp256k1 secret key in an ECPrivateKey
/// structure as defined in [RFC5915].
///
/// [RFC5915]: https://tools.ietf.org/html/rfc5915
pub fn from_der(mut der: impl AsMut<[u8]>) -> Result<SecretKey, DecodingError> {
// TODO: Stricter parsing.
let der_obj = der.as_mut();
let obj: Vec<DerObject> = FromDerObject::deserialize((&*der_obj).iter())
.map_err(|e| DecodingError::new("Secp256k1 DER ECPrivateKey", e))?;
der_obj.zeroize();
let sk_obj = obj.into_iter().nth(1)
.ok_or_else(|| "Not enough elements in DER".to_string())?;
let mut sk_bytes: Vec<u8> = FromDerObject::from_der_object(sk_obj)
.map_err(|e| e.to_string())?;
let sk = SecretKey::from_bytes(&mut sk_bytes)?;
sk_bytes.zeroize();
Ok(sk)
}
/// Sign a message with this secret key, producing a DER-encoded
/// ECDSA signature, as defined in [RFC3278].
///
/// [RFC3278]: https://tools.ietf.org/html/rfc3278#section-8.2
pub fn sign(&self, msg: &[u8]) -> Vec<u8> {
let m = Message::from_slice(Sha256::digest(&msg).as_ref())
.expect("digest output length doesn't match secp256k1 input length");
SECP.sign(&m, &self.0).serialize_der()
}
}
/// A Secp256k1 public key.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct PublicKey(secp::key::PublicKey);
impl PublicKey {
/// Verify the Secp256k1 signature on a message using the public key.
pub fn verify(&self, msg: &[u8], sig: &[u8]) -> bool {
Message::from_slice(&Sha256::digest(msg))
.and_then(|m| Signature::from_der(sig)
.and_then(|s| SECP.verify(&m, &s, &self.0))).is_ok()
}
/// Encode the public key in compressed form, i.e. with one coordinate
/// represented by a single bit.
pub fn encode(&self) -> [u8; 33] {
self.0.serialize()
}
/// Decode a public key from a byte slice in the the format produced
/// by `encode`.
pub fn decode(k: &[u8]) -> Result<PublicKey, DecodingError> {
secp256k1::PublicKey::from_slice(k)
.map_err(|e| DecodingError::new("Secp256k1 public key", e))
.map(PublicKey)
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -67,12 +67,12 @@ pub use multiaddr;
mod keys_proto;
mod peer_id;
mod public_key;
#[cfg(test)]
mod tests;
pub mod either;
pub mod identity;
pub mod muxing;
pub mod nodes;
pub mod protocols_handler;
@ -84,7 +84,7 @@ pub use self::multiaddr::Multiaddr;
pub use self::muxing::StreamMuxer;
pub use self::peer_id::PeerId;
pub use self::protocols_handler::{ProtocolsHandler, ProtocolsHandlerEvent};
pub use self::public_key::PublicKey;
pub use self::identity::PublicKey;
pub use self::swarm::Swarm;
pub use self::transport::Transport;
pub use self::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, UpgradeError, ProtocolName};

View File

@ -42,9 +42,9 @@ impl fmt::Debug for PeerId {
impl PeerId {
/// Builds a `PeerId` from a public key.
#[inline]
pub fn from_public_key(public_key: PublicKey) -> PeerId {
let protobuf = public_key.into_protobuf_encoding();
let multihash = multihash::encode(multihash::Hash::SHA2256, &protobuf)
pub fn from_public_key(key: PublicKey) -> PeerId {
let key_enc = key.into_protobuf_encoding();
let multihash = multihash::encode(multihash::Hash::SHA2256, &key_enc)
.expect("sha2-256 is always supported");
PeerId { multihash }
}
@ -120,9 +120,10 @@ impl PeerId {
/// given public key, otherwise `Some` boolean as the result of an equality check.
pub fn is_public_key(&self, public_key: &PublicKey) -> Option<bool> {
let alg = self.multihash.algorithm();
match multihash::encode(alg, &public_key.clone().into_protobuf_encoding()) {
Ok(compare) => Some(compare == self.multihash),
Err(multihash::EncodeError::UnsupportedType) => None,
let enc = public_key.clone().into_protobuf_encoding();
match multihash::encode(alg, &enc) {
Ok(h) => Some(h == self.multihash),
Err(multihash::EncodeError::UnsupportedType) => None
}
}
}
@ -195,26 +196,25 @@ impl FromStr for PeerId {
#[cfg(test)]
mod tests {
use rand::random;
use crate::{PeerId, PublicKey};
use crate::{PeerId, identity};
#[test]
fn peer_id_is_public_key() {
let key = PublicKey::Rsa((0 .. 2048).map(|_| -> u8 { random() }).collect());
let peer_id = PeerId::from_public_key(key.clone());
let key = identity::Keypair::generate_ed25519().public();
let peer_id = key.clone().into_peer_id();
assert_eq!(peer_id.is_public_key(&key), Some(true));
}
#[test]
fn peer_id_into_bytes_then_from_bytes() {
let peer_id = PublicKey::Rsa((0 .. 2048).map(|_| -> u8 { random() }).collect()).into_peer_id();
let peer_id = identity::Keypair::generate_ed25519().public().into_peer_id();
let second = PeerId::from_bytes(peer_id.clone().into_bytes()).unwrap();
assert_eq!(peer_id, second);
}
#[test]
fn peer_id_to_base58_then_back() {
let peer_id = PublicKey::Rsa((0 .. 2048).map(|_| -> u8 { random() }).collect()).into_peer_id();
let peer_id = identity::Keypair::generate_ed25519().public().into_peer_id();
let second: PeerId = peer_id.to_base58().parse().unwrap();
assert_eq!(peer_id, second);
}

View File

@ -1,108 +0,0 @@
// Copyright 2018 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use crate::{keys_proto, PeerId};
use log::debug;
use protobuf::{self, Message};
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
/// Public key used by the remote.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PublicKey {
/// DER format.
Rsa(Vec<u8>),
/// Format = ???
// TODO: ^
Ed25519(Vec<u8>),
/// Format = ???
// TODO: ^
Secp256k1(Vec<u8>),
}
impl PublicKey {
/// Encodes the public key as a protobuf message.
///
/// Used at various locations in the wire protocol of libp2p.
#[inline]
pub fn into_protobuf_encoding(self) -> Vec<u8> {
let mut public_key = keys_proto::PublicKey::new();
match self {
PublicKey::Rsa(data) => {
public_key.set_Type(keys_proto::KeyType::RSA);
public_key.set_Data(data);
},
PublicKey::Ed25519(data) => {
public_key.set_Type(keys_proto::KeyType::Ed25519);
public_key.set_Data(data);
},
PublicKey::Secp256k1(data) => {
public_key.set_Type(keys_proto::KeyType::Secp256k1);
public_key.set_Data(data);
},
};
public_key
.write_to_bytes()
.expect("protobuf writing should always be valid")
}
/// Decodes the public key from a protobuf message.
///
/// Used at various locations in the wire protocol of libp2p.
#[inline]
pub fn from_protobuf_encoding(bytes: &[u8]) -> Result<PublicKey, IoError> {
let mut pubkey = protobuf::parse_from_bytes::<keys_proto::PublicKey>(bytes)
.map_err(|err| {
debug!("failed to parse public key's protobuf encoding");
IoError::new(IoErrorKind::InvalidData, err)
})?;
Ok(match pubkey.get_Type() {
keys_proto::KeyType::RSA => {
PublicKey::Rsa(pubkey.take_Data())
},
keys_proto::KeyType::Ed25519 => {
PublicKey::Ed25519(pubkey.take_Data())
},
keys_proto::KeyType::Secp256k1 => {
PublicKey::Secp256k1(pubkey.take_Data())
},
})
}
/// Builds a `PeerId` corresponding to the public key of the node.
#[inline]
pub fn into_peer_id(self) -> PeerId {
self.into()
}
}
#[cfg(test)]
mod tests {
use rand::random;
use crate::PublicKey;
#[test]
fn key_into_protobuf_then_back() {
let key = PublicKey::Rsa((0 .. 2048).map(|_| -> u8 { random() }).collect());
let second = PublicKey::from_protobuf_encoding(&key.clone().into_protobuf_encoding()).unwrap();
assert_eq!(key, second);
}
}

View File

@ -549,13 +549,11 @@ where TBehaviour: NetworkBehaviour,
#[cfg(test)]
mod tests {
use crate::peer_id::PeerId;
use crate::{identity, PeerId, PublicKey};
use crate::protocols_handler::{DummyProtocolsHandler, ProtocolsHandler};
use crate::public_key::PublicKey;
use crate::tests::dummy_transport::DummyTransport;
use futures::prelude::*;
use multiaddr::Multiaddr;
use rand::random;
use std::marker::PhantomData;
use super::{ConnectedPoint, NetworkBehaviour, NetworkBehaviourAction,
PollParameters, SwarmBuilder};
@ -601,10 +599,7 @@ mod tests {
}
fn get_random_id() -> PublicKey {
PublicKey::Rsa((0 .. 2048)
.map(|_| -> u8 { random() })
.collect()
)
identity::Keypair::generate_ed25519().public()
}
#[test]
@ -612,8 +607,8 @@ mod tests {
let id = get_random_id();
let transport = DummyTransport::new();
let behaviour = DummyBehaviour{marker: PhantomData};
let swarm = SwarmBuilder::new(transport, behaviour,
id.into_peer_id()).incoming_limit(Some(4)).build();
let swarm = SwarmBuilder::new(transport, behaviour, id.into())
.incoming_limit(Some(4)).build();
assert_eq!(swarm.raw_swarm.incoming_limit(), Some(4));
}
@ -622,8 +617,7 @@ mod tests {
let id = get_random_id();
let transport = DummyTransport::new();
let behaviour = DummyBehaviour{marker: PhantomData};
let swarm = SwarmBuilder::new(transport, behaviour, id.into_peer_id())
.build();
let swarm = SwarmBuilder::new(transport, behaviour, id.into()).build();
assert!(swarm.raw_swarm.incoming_limit().is_none())
}