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

Node.js中如何将Solana钱包密钥对转换为KeyObject?

解决方法

你现在的问题核心有两个:一是没必要把截取后的密钥Buffer再转成base58字符串,直接用原始二进制数据就行;二是Solana用的是Ed25519签名密钥,而要做Diffie-Hellman密钥交换得用对应的X25519格式密钥,Node.js的crypto模块支持X25519,但得先把Ed25519密钥转成X25519格式,再生成KeyObject。

具体代码实现

先安装所需依赖(用成熟的库处理密钥转换,比手动写逻辑更可靠):

npm install bs58 @noble/curves

然后直接使用以下代码:

const crypto = require('crypto');
const base58 = require('bs58');
const { ed25519, x25519 } = require('@noble/curves/ed25519');

// 1. 解析Solana密钥对,直接获取二进制Buffer
const solanaKeypairBase58 = '你的Solana钱包密钥对base58字符串';
const keypairBuffer = Buffer.from(base58.decode(solanaKeypairBase58));
const ed25519PrivateSeed = keypairBuffer.slice(0, 32); // Ed25519私钥种子
const ed25519PubKey = keypairBuffer.slice(32); // Ed25519公钥

// 2. 将Ed25519私钥转换为X25519私钥
const x25519PrivKey = x25519.getPrivateKeyFromSeed(ed25519PrivateSeed);
// 3. 将Ed25519公钥转换为X25519公钥
const ed25519Point = ed25519.Point.fromHex(ed25519PubKey.toString('hex'));
const x25519PubKey = x25519.getPublicKeyFromPoint(ed25519Point);

// 4. 生成符合要求的KeyObject
const privateKeyObj = crypto.KeyObject.from({
  key: Buffer.from(x25519PrivKey),
  format: 'raw',
  type: 'private',
});

// 假设user2的公钥已通过同样方法转换为X25519格式的Buffer
const publicKeyObj = crypto.KeyObject.from({
  key: Buffer.from(user2X25519PubKey),
  format: 'raw',
  type: 'public',
});

// 执行Diffie-Hellman密钥交换
const sharedSecret = crypto.diffieHellman({
  privateKey: privateKeyObj,
  publicKey: publicKeyObj,
});

重要提示

  • 不要再对密钥做base58来回编码,crypto模块直接兼容二进制Buffer,多余的编码操作只会增加出错概率。
  • Ed25519是签名专用算法,不能直接用于Diffie-Hellman密钥交换,必须转换为X25519格式,@noble/curves已经封装好了转换逻辑,无需手动处理复杂的椭圆曲线细节。
  • 若不想额外安装依赖,也可以手动对私钥做SHA-512哈希并修正格式,但出错风险高,不推荐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:51:36