1use crate::crypto::{
2 CryptoError, PrivateKeyExtension, PublicKeyExtension, Secp256r1PrivateKey, Secp256r1PublicKey,
3};
4use base64;
5use hex;
6
7pub fn private_key_to_public_key(private_key: &Secp256r1PrivateKey) -> Secp256r1PublicKey {
9 private_key.to_public_key()
10}
11
12pub fn private_key_to_hex_string(private_key: &Secp256r1PrivateKey) -> String {
22 hex::encode(private_key.to_raw_bytes().to_vec())
23}
24
25pub fn private_key_from_hex(hex: &str) -> Result<Secp256r1PrivateKey, CryptoError> {
31 let bytes = hex::decode(hex)?;
32 let secret_key = Secp256r1PrivateKey::from_slice(&bytes)?;
33 Ok(secret_key)
34}
35
36pub fn public_key_to_hex_string(public_key: &[u8]) -> String {
46 hex::encode(public_key.to_vec())
47}
48
49pub fn public_key_from_hex(hex: &str) -> Result<Secp256r1PublicKey, CryptoError> {
55 let bytes = hex::decode(hex)?;
56 let public_key = Secp256r1PublicKey::from_slice(&bytes)?;
57 Ok(public_key)
58}
59
60pub trait ToArray32 {
61 fn to_array32(&self) -> Result<[u8; 32], CryptoError>;
62}
63
64macro_rules! impl_to_array32 {
65 ($type:ty) => {
66 impl ToArray32 for $type {
67 fn to_array32(&self) -> Result<[u8; 32], CryptoError> {
68 if self.len() != 32 {
69 return Err(CryptoError::InvalidFormat(
70 "Vector does not contain exactly 32 elements".to_string(),
71 ));
72 }
73
74 let mut array = [0u8; 32];
75 let bytes = &self[..array.len()]; array.copy_from_slice(bytes); Ok(array)
78 }
79 }
80 };
81}
82
83impl_to_array32!(Vec<u8>);
84impl_to_array32!(&[u8]);
85
86pub trait ToHexString {
88 fn to_hex_string(&self) -> String;
89}
90
91impl ToHexString for [u8] {
92 fn to_hex_string(&self) -> String {
93 hex::encode(self)
94 }
95}
96
97impl ToHexString for Vec<u8> {
98 fn to_hex_string(&self) -> String {
99 hex::encode(self)
100 }
101}
102
103impl<const N: usize> ToHexString for [u8; N] {
104 fn to_hex_string(&self) -> String {
105 hex::encode(self)
106 }
107}
108
109pub trait FromHexString {
111 fn from_hex_string(&self) -> Result<Vec<u8>, hex::FromHexError>;
112}
113
114impl FromHexString for str {
115 fn from_hex_string(&self) -> Result<Vec<u8>, hex::FromHexError> {
116 hex::decode(self)
117 }
118}
119
120impl FromHexString for String {
121 fn from_hex_string(&self) -> Result<Vec<u8>, hex::FromHexError> {
122 hex::decode(self)
123 }
124}
125
126pub trait FromBase64String {
128 fn from_base64_string(&self) -> Result<Vec<u8>, base64::DecodeError>;
129}
130
131impl FromBase64String for str {
132 fn from_base64_string(&self) -> Result<Vec<u8>, base64::DecodeError> {
133 base64::decode(self)
134 }
135}
136
137impl FromBase64String for String {
138 fn from_base64_string(&self) -> Result<Vec<u8>, base64::DecodeError> {
139 base64::decode(self)
140 }
141}