Skip to main content

KeyManager

Struct KeyManager 

Source
pub struct KeyManager;
Expand description

Main interface for key management operations

This is the recommended API for library integration. It provides simple, safe methods for common key operations.

Implementations§

Source§

impl KeyManager

Source

pub fn generate_keypair() -> Keypair

Generate a new Solana keypair

§Example
use sol_safekey::KeyManager;

let keypair = KeyManager::generate_keypair();
println!("Public key: {}", keypair.pubkey());
Source

pub fn encrypt_with_password( private_key: &str, password: &str, ) -> EncryptionResult<String>

Encrypt a private key with a password

§Arguments
  • private_key - The private key in base58 string format
  • password - The password to use for encryption
§Returns

Base64-encoded encrypted string

§Example
use sol_safekey::KeyManager;

let keypair = KeyManager::generate_keypair();
let private_key = keypair.to_base58_string();

let encrypted = KeyManager::encrypt_with_password(
    &private_key,
    "my_password"
).unwrap();
Source

pub fn decrypt_with_password( encrypted_data: &str, password: &str, ) -> EncryptionResult<String>

Decrypt a private key with a password

§Arguments
  • encrypted_data - Base64-encoded encrypted data
  • password - The password used for encryption
§Returns

The original private key in base58 string format

§Example
use sol_safekey::KeyManager;

let encrypted = "..."; // from encryption
let decrypted = KeyManager::decrypt_with_password(
    encrypted,
    "my_password"
).unwrap();
Source

pub fn get_public_key(private_key: &str) -> EncryptionResult<String>

Get public key from a private key

§Arguments
  • private_key - Private key in base58 string format
§Returns

Public key as a base58 string

Source

pub fn keypair_to_encrypted_json( keypair: &Keypair, password: &str, ) -> EncryptionResult<String>

Encrypt a keypair to a JSON keystore format

This creates a standard encrypted keystore file compatible with Solana tools.

§Arguments
  • keypair - The Solana keypair to encrypt
  • password - The password for encryption
§Returns

JSON string containing the encrypted keystore

Source

pub fn keypair_from_encrypted_json( json_data: &str, password: &str, ) -> EncryptionResult<Keypair>

Decrypt a keypair from encrypted JSON keystore. 与 GitHub 最新版兼容:优先按「base58 私钥」解密;若解密结果非 UTF-8,再尝试「64 字节 keypair」。

Examples found in repository?
examples/test_decrypt.rs (line 79)
7fn main() {
8    let args: Vec<String> = std::env::args().collect();
9    let password = if args.len() >= 2 {
10        args[1].clone()
11    } else {
12        eprintln!("Usage: cargo run -p sol-safekey --example test_decrypt <password>");
13        std::process::exit(1);
14    };
15
16    let keystore_path = if args.len() >= 3 {
17        args[2].clone()
18    } else {
19        "config/dev/keystore.json".to_string()
20    };
21
22    let content = std::fs::read_to_string(&keystore_path)
23        .unwrap_or_else(|e| {
24            eprintln!("Failed to read {}: {}", keystore_path, e);
25            std::process::exit(1);
26        });
27
28    let data: serde_json::Value = serde_json::from_str(&content).unwrap();
29    let encrypted = data["encrypted_private_key"].as_str().unwrap();
30    let pubkey = data["public_key"].as_str().unwrap();
31
32    eprintln!("Keystore: {}", keystore_path);
33    eprintln!("Public key: {}", pubkey);
34    eprintln!("Password len: {}", password.len());
35
36    let key = generate_encryption_key_simple(&password);
37    eprintln!("Encryption key: {:02x}{:02x}{:02x}{:02x}...", key[0], key[1], key[2], key[3]);
38
39    match decrypt_key_to_bytes(encrypted, &key) {
40        Ok(bytes) => {
41            let preview: Vec<String> = bytes.iter().take(16).map(|b| format!("{:02x}", b)).collect();
42            eprintln!("Decrypted {} bytes, first 16: {}", bytes.len(), preview.join(" "));
43            eprintln!("is_ascii: {}", bytes.iter().all(|b| b.is_ascii()));
44            eprintln!("is_utf8: {}", String::from_utf8(bytes.clone()).is_ok());
45
46            // Check if it looks like base58
47            let all_base58 = bytes.iter().all(|b| {
48                let c = *b as char;
49                c.is_ascii() && (
50                    c >= '1' && c <= '9' ||
51                    c >= 'A' && c <= 'H' ||
52                    c >= 'J' && c <= 'N' ||
53                    c >= 'P' && c <= 'Z' ||
54                    c >= 'a' && c <= 'z'
55                )
56            });
57            eprintln!("all_base58_chars: {}", all_base58);
58        }
59        Err(e) => eprintln!("decrypt_key_to_bytes failed: {}", e),
60    }
61
62    // Also try with trimmed password
63    let trimmed = password.trim();
64    if trimmed != password {
65        eprintln!("\n--- Trying trimmed password (len={}) ---", trimmed.len());
66        let key2 = generate_encryption_key_simple(trimmed);
67        eprintln!("Encryption key: {:02x}{:02x}{:02x}{:02x}...", key2[0], key2[1], key2[2], key2[3]);
68
69        match decrypt_key_to_bytes(encrypted, &key2) {
70            Ok(bytes) => {
71                let preview: Vec<String> = bytes.iter().take(16).map(|b| format!("{:02x}", b)).collect();
72                eprintln!("Decrypted {} bytes, first 16: {}", bytes.len(), preview.join(" "));
73                eprintln!("is_ascii: {}", bytes.iter().all(|b| b.is_ascii()));
74                eprintln!("is_utf8: {}", String::from_utf8(bytes.clone()).is_ok());
75            }
76            Err(e) => eprintln!("decrypt failed: {}", e),
77        }
78
79        match KeyManager::keypair_from_encrypted_json(&content, trimmed) {
80            Ok(kp) => {
81                println!("SUCCESS with trimmed! keypair: {}", kp.pubkey());
82                if kp.pubkey().to_string() == pubkey {
83                    println!("Public key MATCHES!");
84                }
85            }
86            Err(e) => eprintln!("keypair_from_encrypted_json (trimmed) failed: {}", e),
87        }
88    }
89
90    match KeyManager::keypair_from_encrypted_json(&content, &password) {
91        Ok(kp) => {
92            println!("SUCCESS! keypair: {}", kp.pubkey());
93            if kp.pubkey().to_string() == pubkey {
94                println!("Public key MATCHES!");
95            } else {
96                println!("WARNING: mismatch! expected {}", pubkey);
97            }
98        }
99        Err(e) => eprintln!("keypair_from_encrypted_json failed: {}", e),
100    }
101}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V