wedpr_l_crypto_ecies_secp256k1/
lib.rs1use wedpr_l_utils::{error::WedprError, traits::Ecies};
6
7#[macro_use]
8extern crate wedpr_l_macros;
9
10#[derive(Default, Debug, Clone)]
12pub struct WedprSecp256k1Ecies {}
13
14impl Ecies for WedprSecp256k1Ecies {
15 fn encrypt<T: ?Sized + AsRef<[u8]>>(
16 &self,
17 public_key: &T,
18 message: &T,
19 ) -> Result<Vec<u8>, WedprError> {
20 match ecies::encrypt(public_key.as_ref(), message.as_ref()) {
21 Ok(v) => Ok(v.to_vec()),
22 Err(_) => {
23 wedpr_println!("secp256k1 ECIES encrypt failed");
24 return Err(WedprError::FormatError);
25 },
26 }
27 }
28
29 fn decrypt<T: ?Sized + AsRef<[u8]>>(
30 &self,
31 private_key: &T,
32 ciphertext: &T,
33 ) -> Result<Vec<u8>, WedprError> {
34 match ecies::decrypt(private_key.as_ref(), ciphertext.as_ref()) {
35 Ok(v) => Ok(v.to_vec()),
36 Err(_) => {
37 wedpr_println!("secp256k1 ECIES decrypt failed");
38 return Err(WedprError::FormatError);
39 },
40 }
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47 use wedpr_l_utils::constant::tests::{
48 BASE64_ENCODED_TEST_MESSAGE, SECP256K1_TEST_PUBLIC_KEY,
49 SECP256K1_TEST_SECRET_KEY,
50 };
51
52 #[test]
53 fn test_secp256k1_ecies() {
54 let secp256k1_ecies = WedprSecp256k1Ecies::default();
55
56 let ciphertext = secp256k1_ecies
57 .encrypt(
58 &SECP256K1_TEST_PUBLIC_KEY.to_vec(),
59 &BASE64_ENCODED_TEST_MESSAGE.to_vec(),
60 )
61 .unwrap();
62 let decrypted_msg = secp256k1_ecies
63 .decrypt(&SECP256K1_TEST_SECRET_KEY.to_vec(), &ciphertext)
64 .unwrap();
65 assert_eq!(decrypted_msg, BASE64_ENCODED_TEST_MESSAGE);
66 }
67}