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
#[macro_use]
extern crate serde_derive;
extern crate crypto;
extern crate rand;
extern crate secp256k1;
extern crate serde;
extern crate serde_json;
pub mod ed25519;
pub mod secp256k;
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
#[repr(u8)]
pub enum SignType {
Ed25519 = 0,
Secp256k1 = 1,
}
impl Default for SignType {
fn default() -> Self {
SignType::Ed25519
}
}
impl SignType {
pub fn is_valid(n: u8) -> bool {
if n <= 1 {
return true;
}
false
}
}
pub trait Signer {
fn get_key_pair() -> Self;
fn get_public_key(sk: &[u8]) -> Vec<u8>;
fn sign(sk: &[u8], message: &[u8]) -> Vec<u8>;
fn verify(pk: &[u8], message: &[u8], signature: &[u8]) -> bool;
}
pub fn get_key_pair(sign_type: Option<SignType>) -> (Vec<u8>, Vec<u8>) {
match sign_type {
Some(SignType::Ed25519) | None => {
let pair = ed25519::Ed25519::get_key_pair();
(pair.sk, pair.pk)
}
Some(SignType::Secp256k1) => {
let pair = secp256k::Secp256k::get_key_pair();
(pair.sk, pair.pk)
}
}
}
pub fn get_pk_by_sk(sk: &[u8], sign_type: &Option<SignType>) -> Vec<u8> {
match sign_type {
Some(SignType::Ed25519) | None => ed25519::Ed25519::get_public_key(sk),
Some(SignType::Secp256k1) => secp256k::Secp256k::get_public_key(sk),
}
}
pub fn sign(sk: &[u8], message: &[u8], sign_type: Option<SignType>) -> Vec<u8> {
match sign_type {
Some(SignType::Ed25519) | None => ed25519::Ed25519::sign(sk, message),
Some(SignType::Secp256k1) => secp256k::Secp256k::sign(sk, message),
}
}
pub fn verify(pk: &[u8], message: &[u8], signature: &[u8], sign_type: Option<SignType>) -> bool {
match sign_type {
Some(SignType::Ed25519) | None => ed25519::Ed25519::verify(pk, message, signature),
Some(SignType::Secp256k1) => secp256k::Secp256k::verify(pk, message, signature),
}
}
#[test]
fn test_signer() {
let ed25519_key_pair = get_key_pair(Some(SignType::Ed25519));
let expect_pk = get_pk_by_sk(&ed25519_key_pair.0, &Some(SignType::Ed25519));
assert_eq!(ed25519_key_pair.1, expect_pk);
let message = b"hello rust";
let signature = sign(&ed25519_key_pair.0, message, Some(SignType::Ed25519));
assert!(verify(
&ed25519_key_pair.1,
message,
&signature,
Some(SignType::Ed25519)
));
}