Transactions
如何使用私鑰對數據進行簽名?[javascript]
使用 BlockCypher 的簽名工具(連結),我可以對以下數據進行簽名:
05de69f5d37f41340eed3230f03d2394dde5e497738a76f027b7d962a0cbdf39
使用私鑰:
2fd7cab0970c692b4151d77a6aeebcae2a3284556cbfc6f182c571eccfc2424f
得到結果:
30440220352f6d47bc33e2596600c6a297a0e3e84079a9b2f16d10cb9396993370365976022062a30c63adfeef315bcfc690e254dd3b6d4f14fe9919317e14ebb15c29325326
但是,我無法使用 bitcoinjs-lib 模組使用 javascript 複製它。我的嘗試如下所示:
var bitcoin = require('bitcoinjs-lib') var wif = require('wif') var dataToSign = '05de69f5d37f41340eed3230f03d2394dde5e497738a76f027b7d962a0cbdf39' var wifObj = wif.decode('KxpiD4T1QHFahGVyg9onfLXjbwBSf5Dyh3BPYY899uXQHn6gfnbz') var keys = bitcoin.ECPair.fromPrivateKey(wifObj.privateKey) var signed = keys.sign(Buffer.from(dataToSign, 'hex')) var signedHex = signed.toString('hex')
你可以嘗試使用
eccrypto
index.js
:var crypto = require("crypto"); var eccrypto = require("eccrypto"); // A new random 32-byte private key. var privateKey = Buffer.from('2fd7cab0970c692b4151d77a6aeebcae2a3284556cbfc6f182c571eccfc2424f', 'hex') // Corresponding uncompressed (65-byte) public key. var publicKey = eccrypto.getPublic(privateKey); var buf = Buffer.from('05de69f5d37f41340eed3230f03d2394dde5e497738a76f027b7d962a0cbdf39', 'hex') // Always hash you message to sign! var msg = crypto.createHash("sha256").update(buf).digest(); eccrypto.sign(privateKey, buf).then(function(sig) { console.log("Signature in DER format (hex):", sig.toString('hex')) eccrypto.verify(publicKey, buf, sig).then(function() { console.log("Signature is OK"); }).catch(function() { console.log("Signature is BAD"); }); });
控制台輸出:
$ node index.js Signature in DER format (hex): 30440220352f6d47bc33e2596600c6a297a0e3e84079a9b2f16d10cb9396993370365976022062a30c63adfeef315bcfc690e254dd3b6d4f14fe9919317e14ebb15c29325326 Signature is OK