Skip to main content

prople_crypto/ecdh/
pubkey.rs

1//! `pubkey` module used to maintain generated `ECDH` [`PublicKey`] struct
2//! object
3use rst_common::with_cryptography::x25519_dalek::PublicKey as ECDHPublicKey;
4
5use crate::ecdh::types::errors::*;
6use crate::ecdh::types::PublicKeyBytes;
7use crate::types::{ByteHex, Value};
8
9/// `PublicKey` used to store the [`ECDHPublicKey`] object or a wrapper of it
10///
11/// This object give a helper methods to convert, encode and decode the data, which is
12/// a public key
13#[derive(Debug, PartialEq, Clone)]
14pub struct PublicKey {
15    key: ECDHPublicKey,
16}
17
18impl PublicKey {
19    pub fn new(key: ECDHPublicKey) -> Self {
20        Self { key }
21    }
22
23    pub fn to_bytes(&self) -> PublicKeyBytes {
24        PublicKeyBytes::from(self.key.to_bytes())
25    }
26
27    pub fn to_hex(&self) -> ByteHex {
28        ByteHex::from(self.key)
29    }
30
31    pub fn from_hex(key: ByteHex) -> Result<Self, EcdhError> {
32        let key_bytes = PublicKeyBytes::try_from(key)?;
33        let key_bytes_val = key_bytes
34            .get()
35            .map_err(|err| EcdhError::ParseBytesError(err.to_string()))?;
36
37        Ok(Self {
38            key: ECDHPublicKey::from(key_bytes_val),
39        })
40    }
41}