-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathkeypair.rs
More file actions
65 lines (52 loc) · 1.82 KB
/
keypair.rs
File metadata and controls
65 lines (52 loc) · 1.82 KB
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
// SPDX-License-Identifier: Apache-2.0
//
// Copyright © 2017 Trust Wallet.
use crate::ed25519::{private::PrivateKey, public::PublicKey, signature::Signature, Hasher512};
use crate::traits::{KeyPairTrait, SigningKeyTrait, VerifyingKeyTrait};
use crate::{KeyPairError, KeyPairResult};
use tw_encoding::hex;
use zeroize::Zeroizing;
/// Represents a pair of `ed25519` private and public keys.
pub struct KeyPair<H: Hasher512> {
private: PrivateKey<H>,
public: PublicKey<H>,
}
impl<H: Hasher512> KeyPairTrait for KeyPair<H> {
type Private = PrivateKey<H>;
type Public = PublicKey<H>;
fn public(&self) -> &Self::Public {
&self.public
}
fn private(&self) -> &Self::Private {
&self.private
}
}
impl<H: Hasher512> SigningKeyTrait for KeyPair<H> {
type SigningMessage = Vec<u8>;
type Signature = Signature;
fn sign(&self, message: Self::SigningMessage) -> KeyPairResult<Self::Signature> {
self.private().sign(message)
}
}
impl<H: Hasher512> VerifyingKeyTrait for KeyPair<H> {
type SigningMessage = Vec<u8>;
type VerifySignature = Signature;
fn verify(&self, signature: Self::VerifySignature, message: Self::SigningMessage) -> bool {
self.public().verify(signature, message)
}
}
impl<'a, H: Hasher512> TryFrom<&'a [u8]> for KeyPair<H> {
type Error = KeyPairError;
fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
let private = PrivateKey::try_from(bytes)?;
let public = private.public();
Ok(KeyPair { private, public })
}
}
impl<'a, H: Hasher512> TryFrom<&'a str> for KeyPair<H> {
type Error = KeyPairError;
fn try_from(hex: &'a str) -> Result<Self, Self::Error> {
let bytes = Zeroizing::new(hex::decode(hex).map_err(|_| KeyPairError::InvalidSecretKey)?);
Self::try_from(bytes.as_slice())
}
}