nostr_rust

My fork of nostr_rust
git clone git://jb55.com/nostr_rust
Log | Files | Refs | README

keys.rs (2130B)


      1 use rand::rngs::OsRng;
      2 use secp256k1::{PublicKey, SecretKey, SECP256K1};
      3 
      4 // TODO: implement bech32 keys
      5 
      6 /// Get a random secret key
      7 /// # Example
      8 /// ```
      9 /// use nostr_rust::keys::get_random_secret_key;
     10 /// let (secret_key, public_key) = get_random_secret_key();
     11 /// ```
     12 pub fn get_random_secret_key() -> (SecretKey, PublicKey) {
     13     SECP256K1.generate_keypair(&mut OsRng)
     14 }
     15 
     16 /// Get a secret key from a hex string
     17 /// # Example
     18 /// ```rust
     19 /// use nostr_rust::keys::secret_key_from_str;
     20 /// let secret_key = secret_key_from_str(env!("SECRET_KEY"));
     21 /// assert!(secret_key.is_ok());
     22 /// ```
     23 pub fn secret_key_from_str(s: &str) -> Result<SecretKey, String> {
     24     let decoded_hex = &hex::decode(s);
     25     match decoded_hex {
     26         Ok(decoded_hex) => match SecretKey::from_slice(decoded_hex) {
     27             Ok(secret_key) => Ok(secret_key),
     28             Err(_) => Err("Invalid secret key".to_string()),
     29         },
     30         Err(_) => Err("Invalid hex format".to_string()),
     31     }
     32 }
     33 
     34 /// Get a public key from a secret key
     35 /// # Example
     36 /// ```rust
     37 /// use nostr_rust::keys::{secret_key_from_str, get_public_key_from_secret};
     38 ///
     39 /// let secret_key = secret_key_from_str(env!("SECRET_KEY")).unwrap();
     40 /// let public_key = get_public_key_from_secret(&secret_key);
     41 /// ```
     42 pub fn get_public_key_from_secret(secret_key: &SecretKey) -> PublicKey {
     43     PublicKey::from_secret_key(SECP256K1, secret_key)
     44 }
     45 
     46 /// Generate a hex secret key and a hex public key from a secret key
     47 /// # Example
     48 /// ```rust
     49 /// use nostr_rust::keys::{secret_key_from_str, get_str_keys_from_secret};
     50 ///
     51 /// let secret_key = secret_key_from_str(env!("SECRET_KEY")).unwrap();
     52 /// let (secret_key_str, public_key_str) = get_str_keys_from_secret(&secret_key);
     53 ///
     54 /// assert_eq!(secret_key_str, env!("SECRET_KEY"));
     55 /// assert_eq!(public_key_str, env!("PUBLIC_KEY"));
     56 /// ```
     57 pub fn get_str_keys_from_secret(secret_key: &SecretKey) -> (String, String) {
     58     (
     59         secret_key.display_secret().to_string(),
     60         // Remove the 2 first characters because they are "0X" and useless
     61         get_public_key_from_secret(secret_key).to_string()[2..].to_string(),
     62     )
     63 }