bsv_wasm/ecdsa/
ecdh.rs

1use crate::{BSVErrors, PrivateKey, PublicKey};
2use elliptic_curve::ecdh::diffie_hellman;
3#[cfg(target_arch = "wasm32")]
4use wasm_bindgen::prelude::*;
5#[cfg(target_arch = "wasm32")]
6use wasm_bindgen::{throw_str, JsValue};
7
8#[cfg_attr(all(target_arch = "wasm32", feature = "wasm-bindgen-ecdh"), wasm_bindgen)]
9#[derive(Clone)]
10pub struct ECDH {}
11
12impl ECDH {
13    /**
14     * Derives the shared key between a recipients public key and an optional private key.
15     */
16    pub(crate) fn derive_shared_key_impl(priv_key: &PrivateKey, pub_key: &PublicKey) -> Result<Vec<u8>, BSVErrors> {
17        let internal_key = k256::PublicKey::from_sec1_bytes(&pub_key.to_bytes_impl()?)?;
18        let shared = diffie_hellman(priv_key.secret_key.to_nonzero_scalar(), internal_key.as_affine());
19        let bytes = shared.as_bytes();
20        Ok(bytes.as_slice().to_vec())
21    }
22}
23
24#[cfg(target_arch = "wasm32")]
25#[cfg_attr(all(target_arch = "wasm32", feature = "wasm-bindgen-ecdh"), wasm_bindgen)]
26impl ECDH {
27    #[cfg_attr(all(target_arch = "wasm32", feature = "wasm-bindgen-ecdh"), wasm_bindgen(js_name = deriveSharedKey))]
28    pub fn derive_shared_key(priv_key: &PrivateKey, pub_key: &PublicKey) -> Result<Vec<u8>, JsValue> {
29        match ECDH::derive_shared_key_impl(priv_key, pub_key) {
30            Ok(v) => Ok(v),
31            Err(e) => Err(JsValue::from_str(&e.to_string())),
32        }
33    }
34}
35
36#[cfg(not(target_arch = "wasm32"))]
37impl ECDH {
38    pub fn derive_shared_key(priv_key: &PrivateKey, pub_key: &PublicKey) -> Result<Vec<u8>, BSVErrors> {
39        ECDH::derive_shared_key_impl(priv_key, pub_key)
40    }
41}