core_crypto/
private_key.rs

1// Copyright 2021 BlockPuppets developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use anyhow::Result;
10#[cfg(feature = "serde")]
11use serde::{Deserialize, Deserializer, Serialize, Serializer};
12#[cfg(feature = "serde")]
13use serde_bytes::{ByteBuf as SerdeByteBuf, Bytes as SerdeBytes};
14
15use super::{block_cipher::BlockCipher, KEY_BYTES_SIZE};
16
17#[cfg(feature = "with_mnemonic")]
18use crate::mnemonic;
19
20construct_fixed_hash! {
21    /// 256 bit hash type.
22    pub struct PrivateKey(KEY_BYTES_SIZE);
23}
24
25#[cfg(feature = "with_mnemonic")]
26impl PrivateKey {
27    /// Constructs a `PrivateKey` the supplied mnemonic and password
28    ///
29    pub fn from_mnemonic(mnemonic: &str, password: &str) -> Result<Self> {
30        mnemonic::from_mnemonic(mnemonic, password)
31    }
32
33    /// Constructs a hash type from the given reference
34    /// to the mutable bytes array of fixed length.
35    ///
36    pub fn create_with_mnemonic(password: &str) -> Result<(PrivateKey, String)> {
37        mnemonic::create_with_mnemonic(password)
38    }
39}
40
41impl PrivateKey {
42    pub fn encrypt_message<C: BlockCipher>(
43        &self,
44        receiver_pk: &[u8; KEY_BYTES_SIZE],
45        msg: &[u8],
46    ) -> Result<Vec<u8>> {
47        C::encrypt_message(self.as_fixed_bytes(), receiver_pk, msg)
48    }
49
50    pub fn decrypt_message<C: BlockCipher>(
51        &self,
52        signer_pk: &[u8; KEY_BYTES_SIZE],
53        enc_msg: &[u8],
54    ) -> Result<Vec<u8>> {
55        C::decrypt_message(self.as_fixed_bytes(), signer_pk, enc_msg)
56    }
57}
58
59#[cfg(feature = "serde")]
60impl Serialize for PrivateKey {
61    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
62    where
63        S: Serializer,
64    {
65        let bytes = self.as_bytes();
66        SerdeBytes::new(bytes).serialize(serializer)
67    }
68}
69
70#[cfg(feature = "serde")]
71impl<'d> Deserialize<'d> for PrivateKey {
72    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
73    where
74        D: Deserializer<'d>,
75    {
76        let bytes = <SerdeByteBuf>::deserialize(deserializer)?;
77        Ok(PrivateKey::from_slice(bytes.as_ref()))
78    }
79}