Litecoin

如何使用萊特幣私鑰簽署消息並從字元串生成萊特幣地址?

  • February 16, 2018

我正在使用 bitcoinjs,但是否有 litecoinjs 等價物?我希望能夠使用我的萊特幣私鑰簽署和驗證消息,並從字元串中生成萊特幣地址。如果存在一個 javascript 庫,將如何使用這些功能來完成這些功能?

bitcoinjs 已經支持 litecoin,快速查看 /src/network.js 和 README 揭示了這一點。 <https://github.com/bitcoinjs/bitcoinjs-lib/blob/d853806/test/integration/basic.js#L30>

看看他們如何設置網路:litecoin 變數,它可能在程式碼中一直使用(至少用於地址生成)。

老實說,簽名沒有什麼大的變化,看看<https://github.com/bitcoinjs/bitcoinjs-message>


WIF 和地址生成 不要對加密安全隨機數生成器的警告掉以輕心。如果您不更改它,那麼您將不斷生成相同的地址,這將是非常不安全的。

//import bitcoinjs libs
var bitcoin = require('bitcoinjs-lib') // v2.x.x
var bitcoinMessage = require('bitcoinjs-message')

//set a litecoin variable equal to its network type, which we'll use throughout the example
var litecoin = bitcoin.networks.litecoin

//let's generate a litecoin keypair from a string
//WARNING: YOU MUST REPLACE rng() WITH A FUNCTION THAT ACTUALLY RETURNS CRYPTOGRAPHICALLY SECURE RANDOM DATA!
function rng () { return Buffer.from('MAKE SURE THIS IS NEW RANDOM DATA EACH TIME RNG() IS CALLED') }

var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng: rng })


var wif = keyPair.toWIF()
//You should store the output of the variable wif here, this is the actual key to the litecoin address (contains the private key) and is crucial to signing messages, do not share this and handle with care.

var address = keyPair.getAddress()

console.log("wif: " + wif + "\n")
console.log("address: " + address + "\n")

使用範例 1 中的 WIF 進行消息簽名

這將獲取您的 WIF,然後簽署一條消息。

//import bitcoinjs libs
var bitcoin = require('bitcoinjs-lib') // v2.x.x
var bitcoinMessage = require('bitcoinjs-message')

//set a litecoin variable equal to its network type, which we'll use throughout the example
var litecoin = bitcoin.networks.litecoin

// add the wif key you stored
var wif = 'WIF key goes here'

var keyPair = bitcoin.ECPair.fromWIF(wif, litecoin)
var privateKey = keyPair.d.toBuffer(32)
var message = 'This is an example of a signed message.'
var messagePrefix = litecoin.messagePrefix

var signature = bitcoinMessage.sign(message, messagePrefix, privateKey, keyPair.compressed)
console.log(signature.toString('base64'))

將 WIF 替換為您在上一個範例中生成的 WIF。

使用範例 1 中的地址和範例 2 中的簽名輸出進行消息驗證

//import bitcoinjs libs
var bitcoin = require('bitcoinjs-lib') // v2.x.x
var bitcoinMessage = require('bitcoinjs-message')

//set a litecoin variable equal to its network type, which we'll use throughout the example
var litecoin = bitcoin.networks.litecoin

var address = 'THE ADDRESS FROM EXAMPLE1'
var signature = 'THE OUTPUT OF CONSOLE LOG OF EXAMPLE2'
var message = 'This is an example of a signed message.'
var messagePrefix = litcoin.messagePrefix

console.log(bitcoinMessage.verify(message, messagePrefix, address, signature))

引用自:https://bitcoin.stackexchange.com/questions/54435