You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中secp256k1的new_with_hash方法不存在,求新版本替代方案

解决SharedSecret::new_with_hash不存在的问题

在secp256k1 crate的新版本中,SharedSecret::new_with_hash方法已被移除。替代方案是先生成原始共享密钥,再手动对其应用哈希函数,步骤如下:

  • 调用SharedSecret::new传入对方公钥与自身私钥,生成原始共享密钥
  • 通过SharedSecret::as_bytes()获取原始密钥的字节数据
  • 使用你需要的哈希函数(如SHA-256、SHA-512等)处理这些字节

代码示例

先确保依赖配置正确:

[dependencies]
secp256k1 = "0.29"
sha2 = "0.10"
rand = "0.8"

实现代码:

use secp256k1::{ecdh::SharedSecret, PublicKey, SecretKey, Secp256k1};
use sha2::{Sha256, Digest};
use rand::thread_rng;

fn main() {
    let secp = Secp256k1::new();
    let my_secret_key = SecretKey::new(&mut thread_rng());
    // 实际场景中替换为对方的公钥
    let their_public_key = PublicKey::from_secret_key(&secp, &my_secret_key);

    // 生成原始共享密钥
    let shared_secret = SharedSecret::new(&their_public_key, &my_secret_key);

    // 手动应用SHA-256哈希(替代原new_with_hash的功能)
    let mut hasher = Sha256::new();
    hasher.update(shared_secret.as_bytes());
    let hashed_secret = hasher.finalize();

    println!("Hashed shared secret: {:x}", hashed_secret);
}

这种方式更灵活,支持任意哈希算法,只要保证与交互方使用相同的哈希函数,就能和依赖旧方法的代码兼容。

内容的提问来源于stack exchange,提问作者lolplanet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 20:40:56