rusted_nostr_tools/functions/
convert_key.rs1use bech32::FromBase32;
2
3use super::utils::{bech32_encode, Prefix};
4
5pub struct ConvertKey;
6
7impl ConvertKey {
8 pub fn to_hex(key: &str) -> Result<String, String> {
9 let (_, decoded_key, _) = match bech32::decode(key) {
10 Ok((hrp, data, _)) => (hrp, data, true),
11 Err(_) => return Err("Error decoding bech32 key".to_string()),
12 };
13
14 let base_32_key = match Vec::<u8>::from_base32(&decoded_key) {
15 Ok(key) => key,
16 Err(_) => return Err("Error converting bech32 key to base32".to_string()),
17 };
18
19 let hex_key = hex::encode(base_32_key);
20
21 Ok(hex_key)
22 }
23
24 pub fn to_bech32_public_key(key: &str) -> String {
25 let bech32_pubkey = bech32_encode(Prefix::Npub, &key.to_string());
26 bech32_pubkey
27 }
28
29 pub fn to_bech32_private_key(key: &str) -> String {
30 let bech32_privkey = bech32_encode(Prefix::Nsec, &key.to_string());
31 bech32_privkey
32 }
33}