Rust密钥存储库holochain_keystore的使用:安全高效的密钥管理与加密功能实现

Rust密钥存储库holochain_keystore的使用:安全高效的密钥管理与加密功能实现

holochain_keystore是一个安全的私钥存储库。MetaLairClient是对Keystore的引用,它允许异步生成密钥对,并通过公共AgentPubKey引用使用这些密钥对。

示例代码

use holo_hash::AgentPubKey;
use std::path::Path;
use std::path::PathBuf;
use holochain_keystore::*;
use holochain_keystore::lair_keystore::*;
use holochain_serialized_bytes::prelude::*;
use std::sync::{Arc, Mutex};

#[tokio::main(flavor = "multi_thread")]
async fn main() {
    tokio::task::spawn(async move {
        let mut passphrase = sodoken::LockedArray::new(32).unwrap();
        passphrase.lock().copy_from_slice(b"passphrase");

        let passphrase = Arc::new(Mutex::new(passphrase));

        let keystore = spawn_lair_keystore_in_proc(&PathBuf::from("/"), passphrase).await.unwrap();
        let agent_pubkey = AgentPubKey::new_random(&keystore).await.unwrap();

        #[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes)]
        struct MyData(Vec<u8>);

        let my_data_1 = MyData(b"signature test data 1".to_vec());

        let signature = agent_pubkey.sign(&keystore, &my_data_1).await.unwrap();

        assert!(agent_pubkey.verify_signature(&signature, &my_data_1).await.unwrap());
    }).await.unwrap();
}

完整示例

use holo_hash::AgentPubKey;
use std::path::PathBuf;
use holochain_keystore::*;
use holochain_keystore::lair_keystore::*;
use holochain_serialized_bytes::prelude::*;
use std::sync::{Arc, Mutex};

#[tokio::main(flavor = "multi_thread")]
async fn main() {
    // 创建一个32字节的加密passphrase
    let mut passphrase = sodoken::LockedArray::new(32).unwrap();
    passphrase.lock().copy_from_slice(b"my_secure_passphrase_123");

    // 将passphrase包装在Arc<Mutex>中以安全共享
    let passphrase = Arc::new(Mutex::new(passphrase));

    // 创建一个in-process的密钥存储
    let keystore = spawn_lair_keystore_in_proc(
        &PathBuf::from("/tmp/keystore"), // 密钥存储路径
        passphrase
    ).await.unwrap();

    // 生成一个新的随机代理公钥
    let agent_pubkey = AgentPubKey::new_random(&keystore).await.unwrap();
    println!("Generated new agent pubkey: {:?}", agent_pubkey);

    // 定义一个可序列化的数据结构
    #[derive(Debug, serde::Serialize, serde::Deserialize, SerializedBytes)]
    struct SecureMessage {
        content: String,
        timestamp: u64,
    }

    // 创建要签名的消息
    let message = SecureMessage {
        content: "Hello, secure world!".to_string(),
        timestamp: 1234567890,
    };

    // 使用代理私钥对消息进行签名
    let signature = agent_pubkey.sign(&keystore, &message).await.unwrap();
    println!("Generated signature: {:?}", signature);

    // 验证签名
    let verification_result = agent_pubkey.verify_signature(&signature, &message).await.unwrap();
    assert!(verification_result, "Signature verification failed!");
    println!("Signature verified successfully!");
}

功能说明

  1. 密钥管理

    • 安全存储私钥
    • 生成新的密钥对
    • 通过AgentPubKey引用密钥
  2. 加密功能

    • 数据签名
    • 签名验证
  3. 安全特性

    • 使用加密passphrase保护密钥
    • 线程安全设计(Arc/Mutex)

安装

作为库安装:

cargo add holochain_keystore

或在Cargo.toml中添加:

holochain_keystore = "0.5.4"

许可证:CAL-1.0


1 回复

Rust密钥存储库holochain_keystore使用指南

概述

holochain_keystore是Rust中一个安全高效的密钥管理与加密库,专为Holochain生态设计,但也适用于其他需要密钥管理的Rust项目。它提供了密钥生成、存储、签名和加密等核心功能。

主要特性

  • 安全的密钥存储和管理
  • 支持多种加密算法
  • 线程安全的操作
  • 简单的API设计
  • 与Holochain生态无缝集成

安装

在Cargo.toml中添加依赖:

[dependencies]
holochain_keystore = "0.1.0"

基本使用方法

1. 创建密钥存储

use holochain_keystore::*;
use holochain_keystore::keystore::*;

async fn create_keystore() -> KeystoreResult<MetaLairClient> {
    let keystore = lair_keystore_in_memory().await?;
    Ok(keystore)
}

2. 生成新密钥

async fn generate_new_key(keystore: &MetaLairClient) -> KeystoreResult<holochain_keystore::AgentPubKey> {
    let key = keystore.new_sign_key_ed25519().await?;
    Ok(key)
}

3. 使用密钥签名

async fn sign_data(
    keystore: &MetaLairClient,
    key: &AgentPubKey,
    data: &[u8],
) -> KeystoreResult<Signature> {
    let signature = keystore.sign(key.clone(), data.to_vec()).await?;
    Ok(signature)
}

4. 验证签名

async fn verify_signature(
    keystore: &MetaLairClient,
    key: &AgentPubKey,
    signature: &Signature,
    data: &[u8],
) -> KeystoreResult<bool> {
    let valid = keystore.verify_signature(key.clone(), signature.clone(), data.to_vec()).await?;
    Ok(valid)
}

高级用法

1. 加密数据

async fn encrypt_data(
    keystore: &MetaLairClient,
    sender_key: &AgentPubKey,
    recipient_key: &AgentPubKey,
    data: &[u8],
) -> KeystoreResult<Vec<u8>> {
    let encrypted = keystore.encrypt_x25519(
        sender_key.clone(),
        recipient_key.clone(),
        data.to_vec()
    ).await?;
    Ok(encrypted)
}

2. 解密数据

async fn decrypt_data(
    keystore: &MetaLairClient,
    recipient_key: &AgentPubKey,
    sender_key: &AgentPubKey,
    encrypted_data: &[u8],
) -> KeystoreResult<Vec<u8>> {
    let decrypted = keystore.decrypt_x25519(
        recipient_key.clone(),
        sender_key.clone(),
        encrypted_data.to_vec()
    ).await?;
    Ok(decrypted)
}

3. 密钥派生

async fn derive_key(
    keystore: &MetaLairClient,
    base_key: &AgentPubKey,
    context: &[u8],
) -> KeystoreResult<AgentPubKey> {
    let derived_key = keystore.derive_seed(base_key.clone(), context.to_vec()).await?;
    Ok(derived_key)
}

完整示例

use holochain_keystore::*;
use holochain_keystore::keystore::*;

#[tokio::main]
async fn main() -> KeystoreResult<()> {
    // 1. 创建密钥存储
    let keystore = lair_keystore_in_memory().await?;
    
    // 2. 生成密钥对
    let key = keystore.new_sign_key_ed25519().await?;
    println!("Generated key: {:?}", key);
    
    // 3. 签名数据
    let data = b"Hello, holochain_keystore!";
    let signature = keystore.sign(key.clone(), data.to_vec()).await?;
    println!("Signature: {:?}", signature);
    
    // 4. 验证签名
    let valid = keystore.verify_signature(key.clone(), signature.clone(), data.to_vec()).await?;
    println!("Signature valid: {}", valid);
    
    // 5. 加密示例
    let recipient_key = keystore.new_sign_key_ed25519().await?;
    let encrypted = keystore.encrypt_x25519(
        key.clone(),
        recipient_key.clone(),
        data.to_vec()
    ).await?;
    println!("Encrypted data length: {}", encrypted.len());
    
    // 6. 解密示例
    let decrypted = keystore.decrypt_x25519(
        recipient_key.clone(),
        key.clone(),
        encrypted
    ).await?;
    println!("Decrypted data: {:?}", String::from_utf8_lossy(&decrypted));
    
    Ok(())
}

注意事项

  1. 生产环境中应使用持久化存储而非内存存储
  2. 妥善保管主密钥,它是访问所有派生密钥的关键
  3. 定期轮换敏感密钥
  4. 使用最新版本的库以获得安全更新

holochain_keystore为Rust开发者提供了强大的密钥管理功能,特别适合分布式应用和安全敏感场景。

回到顶部