使用 softHSM 生成比特币钱包

时间:2021-07-05 10:49:32

标签: javascript bitcoin ecdsa wallet softhsm

我尝试使用 javascript 从 softHSM 实现比特币钱包。我可以使用下面的代码对以太坊做同样的事情,ethereumjssofthsm2graphene 成功

var lib = "C:/SoftHSM2/lib/softhsm2-x64.dll";

var mod = Module.load(lib, "SoftHSM");
mod.initialize();

var slot = mod.getSlots(0);
var session
if (slot.flags & graphene.SlotFlag.TOKEN_PRESENT) {
    session = slot.open(graphene.SessionFlag.RW_SESSION | graphene.SessionFlag.SERIAL_SESSION);
    session.login("******");
    
     // generate ECDSA key pair
     var keys = session.generateKeyPair(graphene.KeyGenMechanism.ECDSA, {
        label: "publickey",
        id: Buffer.from([1, 2, 3, 4, 5]),
        keyType: graphene.KeyType.ECDSA,
        token: true,
        verify: true,
        paramsECDSA: graphene.NamedCurve.getByName("secp256k1").value,
        
    }, {
        keyType: graphene.KeyType.ECDSA,
        label: "privateKey",
        id: Buffer.from([1, 2, 3, 4, 5]),        
        token: true,
        sign: true
    }); 

    ///////////////////////////////////////////////////////////////////////////////////////////
    // Extract Public Key and calculate Ethereum Address
    ////////////////////////////////////////////////////////////////////////////////////////////
    
    /// the first 3 byte for uncompressed key 
    // https://tools.ietf.org/html/rfc5480#section-2.2
    puplicKey = decodeECPointToPublicKey(keys.publicKey.getAttribute({pointEC: null}).pointEC)
    const address = keccak256(puplicKey) // keccak256 hash of publicKey     
    const buf2 = Buffer.from(address, 'hex');
    const EthAddr="0x"+buf2.slice(-20).toString('hex') // take lat 20 bytes as ethereum adress
    console.log("Generated Ethreum address:" + EthAddr) 
}

如果我使用 bitcoinjsbitcore-lib,有两种方法可以生成比特币钱包:一种是从库中创建一个随机的公钥和私钥对(不是从 hsm ) 或另一个正在导入我无法从 softHSM 获得的私钥的 WIF 字符串。我还尝试使用从上面的 decodeECPointToPublicKey 方法生成的公钥用于比特币,但我在缓冲区中得到了一个 62 字节长的公钥。参考这个 conversation,我应该有 32 或 64 个字节。

//////////////////////////////////////////////////////////////////
// Generate Random KeyPair
/////////////////////////////////////////////////////////////////
const keypair = bitcoin.ECPair.makeRandom({ network })

const pubkey = keypair.publicKey

const addressObject = bitcoin.payments.p2pkh({ pubkey, network })
const wif = keypair.toWIF();
console.log("address: "+addressObject.address);

////////////////////////////////////////////////////////////////////
// ReGenerate From WIF
////////////////////////////////////////////////////////////////////
const keyPair = bitcoin.ECPair.fromWIF(
    wif , bitcoin.networks.testnet
  );
const { address } = bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey , network: bitcoin.networks.testnet});
console.log("regenerated address: "+address);

我对这个问题有点困惑,非常愿意接受新的意见、建议或解决方案。

提前致谢。

0 个答案:

没有答案
相关问题