Skip to main content

wasmium_securemem/
protected_keypair.rs

1use ed25519_dalek::{Keypair, PublicKey, SecretKey, Signature, Signer};
2use secrecy::DebugSecret;
3use wasmium_errors::{WasmiumError, WasmiumResult};
4use zeroize::Zeroize;
5
6pub struct ProtectedEd25519KeyPair(pub(crate) Keypair);
7
8impl ProtectedEd25519KeyPair {
9    pub fn new(keypair: Keypair) -> ProtectedEd25519KeyPair {
10        ProtectedEd25519KeyPair(keypair)
11    }
12
13    pub fn from_bytes(input_bytes: &[u8]) -> WasmiumResult<ProtectedEd25519KeyPair> {
14        match Keypair::from_bytes(input_bytes) {
15            Ok(keypair) => Ok(ProtectedEd25519KeyPair::new(keypair)),
16            Err(_) => return Err(WasmiumError::InvalidBytesForKeyPair),
17        }
18    }
19
20    pub fn try_sign(&self, message: &[u8]) -> WasmiumResult<Signature> {
21        match self.0.try_sign(message) {
22            Ok(signature) => Ok(signature),
23            Err(_) => Err(WasmiumError::SigningError),
24        }
25    }
26
27    pub fn zero_init(public_key_array: [u8; 32]) -> WasmiumResult<Self> {
28        let public = match PublicKey::from_bytes(&public_key_array) {
29            Ok(key) => key,
30            Err(_) => return Err(WasmiumError::InvalidBytesForPublicKey),
31        };
32        let secret = SecretKey::from_bytes(&[0_u8; 32]).unwrap(); // Never fails hence `.unwrap()`
33
34        let keypair = Keypair { secret, public };
35
36        Ok(ProtectedEd25519KeyPair(keypair))
37    }
38
39    pub fn public_key(&self) -> [u8; 32] {
40        self.0.public.to_bytes()
41    }
42
43    #[cfg(feature = "satoshi_mode")]
44    pub fn base58_public_key(&self) -> String {
45        bs58::encode(&self.0.public.to_bytes()).into_string()
46    }
47}
48
49impl Zeroize for ProtectedEd25519KeyPair {
50    fn zeroize(&mut self) {
51        *self = ProtectedEd25519KeyPair(Keypair {
52            secret: SecretKey::from_bytes(&[0_u8; 32]).unwrap(), //Never fails, hence unwrap()
53            public: PublicKey::from_bytes(&[0_u8; 32]).unwrap(), //Never fails, hence unwrap()
54        });
55    }
56}
57
58impl DebugSecret for ProtectedEd25519KeyPair {
59    fn debug_secret(f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
60        f.debug_struct("ProtectedEd25519KeyPair(Keypair)").finish()
61    }
62}
63
64impl core::fmt::Debug for ProtectedEd25519KeyPair {
65    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
66        f.debug_struct("ProtectedEd25519KeyPair(Keypair)").finish()
67    }
68}