解码Phantom私钥转Uint8Array时遇‘bad secret key size’错误求助
错误原因及解决方法
这个错误的核心原因是:Solana Web3.js的Keypair.fromSecretKey()方法要求传入64字节的Uint8Array,这个数组需要包含32字节的私钥 + 32字节对应公钥;而你通过bs58解码Phantom导出的私钥后,得到的是仅32字节的纯私钥,不符合方法的参数规格,因此触发"bad secret key size"错误。
两种可行的解决方式:
方式1:使用fromSeed方法(推荐)
直接用32字节的私钥作为种子生成Keypair:
const secretKey = bs58.decode("BxAN...RGM"); // Uint8Array(32) const keypair = Web3.Keypair.fromSeed(secretKey); console.log(keypair);
方式2:补全公钥生成64字节完整密钥
先从32字节私钥推导对应公钥,再将私钥与公钥拼接成64字节数组:
const secretKey = bs58.decode("BxAN...RGM"); // Uint8Array(32) const tempKeypair = Web3.Keypair.fromSeed(secretKey); // 拼接私钥和公钥得到符合要求的64字节密钥 const fullSecretKey = new Uint8Array([...secretKey, ...tempKeypair.publicKey.toBytes()]); const keypair = Web3.Keypair.fromSecretKey(fullSecretKey); console.log(keypair);
内容的提问来源于stack exchange,提问作者Cigdem
相关产品推荐
相关产品推荐

