#[cfg(feature = "ecdsa")]
pub mod ecdsa;
pub mod ed25519;
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
pub mod rsa;
#[cfg(feature = "secp256k1")]
pub mod secp256k1;
pub mod error;
use self::error::*;
use crate::{keys_proto, PeerId};
use std::convert::{TryFrom, TryInto};
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Keypair {
Ed25519(ed25519::Keypair),
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
Rsa(rsa::Keypair),
#[cfg(feature = "secp256k1")]
Secp256k1(secp256k1::Keypair),
#[cfg(feature = "ecdsa")]
Ecdsa(ecdsa::Keypair),
}
impl Keypair {
pub fn generate_ed25519() -> Keypair {
Keypair::Ed25519(ed25519::Keypair::generate())
}
#[cfg(feature = "secp256k1")]
pub fn generate_secp256k1() -> Keypair {
Keypair::Secp256k1(secp256k1::Keypair::generate())
}
#[cfg(feature = "ecdsa")]
pub fn generate_ecdsa() -> Keypair {
Keypair::Ecdsa(ecdsa::Keypair::generate())
}
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
pub fn rsa_from_pkcs8(pkcs8_der: &mut [u8]) -> Result<Keypair, DecodingError> {
rsa::Keypair::from_pkcs8(pkcs8_der).map(Keypair::Rsa)
}
#[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)))
}
pub fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError> {
use Keypair::*;
match self {
Ed25519(ref pair) => Ok(pair.sign(msg)),
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
Rsa(ref pair) => pair.sign(msg),
#[cfg(feature = "secp256k1")]
Secp256k1(ref pair) => pair.secret().sign(msg),
#[cfg(feature = "ecdsa")]
Ecdsa(ref pair) => Ok(pair.secret().sign(msg)),
}
}
pub fn public(&self) -> PublicKey {
use Keypair::*;
match self {
Ed25519(pair) => PublicKey::Ed25519(pair.public()),
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
Rsa(pair) => PublicKey::Rsa(pair.public()),
#[cfg(feature = "secp256k1")]
Secp256k1(pair) => PublicKey::Secp256k1(pair.public().clone()),
#[cfg(feature = "ecdsa")]
Ecdsa(pair) => PublicKey::Ecdsa(pair.public().clone()),
}
}
pub fn to_protobuf_encoding(&self) -> Result<Vec<u8>, DecodingError> {
use prost::Message;
let pk = match self {
Self::Ed25519(data) => keys_proto::PrivateKey {
r#type: keys_proto::KeyType::Ed25519.into(),
data: data.encode().into(),
},
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
Self::Rsa(_) => return Err(DecodingError::encoding_unsupported("RSA")),
#[cfg(feature = "secp256k1")]
Self::Secp256k1(_) => return Err(DecodingError::encoding_unsupported("secp256k1")),
#[cfg(feature = "ecdsa")]
Self::Ecdsa(_) => return Err(DecodingError::encoding_unsupported("ECDSA")),
};
Ok(pk.encode_to_vec())
}
pub fn from_protobuf_encoding(bytes: &[u8]) -> Result<Keypair, DecodingError> {
use prost::Message;
let mut private_key = keys_proto::PrivateKey::decode(bytes)
.map_err(|e| DecodingError::bad_protobuf("private key bytes", e))
.map(zeroize::Zeroizing::new)?;
let key_type = keys_proto::KeyType::from_i32(private_key.r#type)
.ok_or_else(|| DecodingError::unknown_key_type(private_key.r#type))?;
match key_type {
keys_proto::KeyType::Ed25519 => {
ed25519::Keypair::decode(&mut private_key.data).map(Keypair::Ed25519)
}
keys_proto::KeyType::Rsa => Err(DecodingError::decoding_unsupported("RSA")),
keys_proto::KeyType::Secp256k1 => Err(DecodingError::decoding_unsupported("secp256k1")),
keys_proto::KeyType::Ecdsa => Err(DecodingError::decoding_unsupported("ECDSA")),
}
}
}
impl zeroize::Zeroize for keys_proto::PrivateKey {
fn zeroize(&mut self) {
self.r#type.zeroize();
self.data.zeroize();
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum PublicKey {
Ed25519(ed25519::PublicKey),
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
Rsa(rsa::PublicKey),
#[cfg(feature = "secp256k1")]
Secp256k1(secp256k1::PublicKey),
#[cfg(feature = "ecdsa")]
Ecdsa(ecdsa::PublicKey),
}
impl PublicKey {
#[must_use]
pub fn verify(&self, msg: &[u8], sig: &[u8]) -> bool {
use PublicKey::*;
match self {
Ed25519(pk) => pk.verify(msg, sig),
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
Rsa(pk) => pk.verify(msg, sig),
#[cfg(feature = "secp256k1")]
Secp256k1(pk) => pk.verify(msg, sig),
#[cfg(feature = "ecdsa")]
Ecdsa(pk) => pk.verify(msg, sig),
}
}
pub fn to_protobuf_encoding(&self) -> Vec<u8> {
use prost::Message;
let public_key = keys_proto::PublicKey::from(self);
let mut buf = Vec::with_capacity(public_key.encoded_len());
public_key
.encode(&mut buf)
.expect("Vec<u8> provides capacity as needed");
buf
}
pub fn from_protobuf_encoding(bytes: &[u8]) -> Result<PublicKey, DecodingError> {
use prost::Message;
let pubkey = keys_proto::PublicKey::decode(bytes)
.map_err(|e| DecodingError::bad_protobuf("public key bytes", e))?;
pubkey.try_into()
}
pub fn to_peer_id(&self) -> PeerId {
self.into()
}
}
impl From<&PublicKey> for keys_proto::PublicKey {
fn from(key: &PublicKey) -> Self {
match key {
PublicKey::Ed25519(key) => keys_proto::PublicKey {
r#type: keys_proto::KeyType::Ed25519 as i32,
data: key.encode().to_vec(),
},
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
PublicKey::Rsa(key) => keys_proto::PublicKey {
r#type: keys_proto::KeyType::Rsa as i32,
data: key.encode_x509(),
},
#[cfg(feature = "secp256k1")]
PublicKey::Secp256k1(key) => keys_proto::PublicKey {
r#type: keys_proto::KeyType::Secp256k1 as i32,
data: key.encode().to_vec(),
},
#[cfg(feature = "ecdsa")]
PublicKey::Ecdsa(key) => keys_proto::PublicKey {
r#type: keys_proto::KeyType::Ecdsa as i32,
data: key.encode_der(),
},
}
}
}
impl TryFrom<keys_proto::PublicKey> for PublicKey {
type Error = DecodingError;
fn try_from(pubkey: keys_proto::PublicKey) -> Result<Self, Self::Error> {
let key_type = keys_proto::KeyType::from_i32(pubkey.r#type)
.ok_or_else(|| DecodingError::unknown_key_type(pubkey.r#type))?;
match key_type {
keys_proto::KeyType::Ed25519 => {
ed25519::PublicKey::decode(&pubkey.data).map(PublicKey::Ed25519)
}
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
keys_proto::KeyType::Rsa => {
rsa::PublicKey::decode_x509(&pubkey.data).map(PublicKey::Rsa)
}
#[cfg(any(not(feature = "rsa"), target_arch = "wasm32"))]
keys_proto::KeyType::Rsa => {
log::debug!("support for RSA was disabled at compile-time");
Err(DecodingError::missing_feature("rsa"))
}
#[cfg(feature = "secp256k1")]
keys_proto::KeyType::Secp256k1 => {
secp256k1::PublicKey::decode(&pubkey.data).map(PublicKey::Secp256k1)
}
#[cfg(not(feature = "secp256k1"))]
keys_proto::KeyType::Secp256k1 => {
log::debug!("support for secp256k1 was disabled at compile-time");
Err(DecodingError::missing_feature("secp256k1"))
}
#[cfg(feature = "ecdsa")]
keys_proto::KeyType::Ecdsa => {
ecdsa::PublicKey::decode_der(&pubkey.data).map(PublicKey::Ecdsa)
}
#[cfg(not(feature = "ecdsa"))]
keys_proto::KeyType::Ecdsa => {
log::debug!("support for ECDSA was disabled at compile-time");
Err(DecodingError::missing_feature("ecdsa"))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
#[test]
fn keypair_protobuf_roundtrip() {
let expected_keypair = Keypair::generate_ed25519();
let expected_peer_id = expected_keypair.public().to_peer_id();
let encoded = expected_keypair.to_protobuf_encoding().unwrap();
let keypair = Keypair::from_protobuf_encoding(&encoded).unwrap();
let peer_id = keypair.public().to_peer_id();
assert_eq!(expected_peer_id, peer_id);
}
#[test]
fn keypair_from_protobuf_encoding() {
let base_64_encoded = "CAESQL6vdKQuznQosTrW7FWI9At+XX7EBf0BnZLhb6w+N+XSQSdfInl6c7U4NuxXJlhKcRBlBw9d0tj2dfBIVf6mcPA=";
let expected_peer_id =
PeerId::from_str("12D3KooWEChVMMMzV8acJ53mJHrw1pQ27UAGkCxWXLJutbeUMvVu").unwrap();
let encoded = base64::decode(base_64_encoded).unwrap();
let keypair = Keypair::from_protobuf_encoding(&encoded).unwrap();
let peer_id = keypair.public().to_peer_id();
assert_eq!(expected_peer_id, peer_id);
}
#[test]
fn public_key_implements_hash() {
use std::hash::Hash;
fn assert_implements_hash<T: Hash>() {}
assert_implements_hash::<PublicKey>();
}
#[test]
fn public_key_implements_ord() {
use std::cmp::Ord;
fn assert_implements_ord<T: Ord>() {}
assert_implements_ord::<PublicKey>();
}
}