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
use crate::{keys_proto, PeerId};
use log::debug;
use protobuf::{self, Message};
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PublicKey {
Rsa(Vec<u8>),
Ed25519(Vec<u8>),
Secp256k1(Vec<u8>),
}
impl PublicKey {
#[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")
}
#[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())
},
})
}
#[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);
}
}