Address-Generation

從使用者輸入生成“私鑰”的地址

  • March 6, 2022

我想將私鑰作為使用者的輸入,並使用 C# 將其轉換為錢包地址。

我在生成隨機密鑰的教程中看到了這一點:

Key privateKey = new Key();
PubKey publicKey = privateKey.PubKey;
Console.WriteLine(publicKey.GetAddress(ScriptPubKeyType.Legacy, Network.Main));

如何將使用者的私鑰字元串轉換為主網的錢包地址?

假設本例中的私鑰字元串是pk

Console.WriteLine("Enter private key:");
string pk = Console.ReadLine();
var bitcoinPrivateKey = new BitcoinSecret(pk, Network.Main);

var legacy_address = bitcoinPrivateKey.GetAddress(ScriptPubKeyType.Legacy);

Console.WriteLine("Legacy Address :" + legacy_address);

如果您想獲得 p2sh-segwit 和 bech32 地址,請添加以下行:

var p2shsegwit_address = bitcoinPrivateKey.GetAddress(ScriptPubKeyType.SegwitP2SH);
var nativesegwit_address = bitcoinPrivateKey.GetAddress(ScriptPubKeyType.Segwit);

Console.WriteLine("P2SH-Segwit Address :" + p2shsegwit_address);
Console.WriteLine("Bech32 Address :" + nativesegwit_address);

我已經通過javascript實現了它,也許它可以幫助你。

//usage:
//$ yarn add bip32 bip39
// node --version is 16.1.0

const bs58check = require('bs58check');
const bip39 = require("bip39");
const bip32 = require("bip32");
const createHash = require('create-hash');


function addr(node) {
   var hash = node.identifier; // hash160 of the publicKey

   const payload = Buffer.allocUnsafe(21);

   var version = 0x0;
   payload.writeUInt8(version, 0);

   hash.copy(payload, 1);

   var address = bs58check.encode(payload);
   return address;
}

var puzzle = "some puzzle you inputting";

var entropy = createHash("sha256").update(puzzle).digest().toString("hex");
console.log("entropy: " + entropy);

var mnemonic = bip39.entropyToMnemonic(entropy);
console.log("mnemonic: " + mnemonic);

var passphrase = "";

var seed = bip39.mnemonicToSeedSync(mnemonic, passphrase);
var master = bip32.fromSeed(seed); // m

// generate 10 btc addresses...
for (var i = 0; i < 3; i++) {
   var node = master.derivePath("m/44'/0'/0'/1/" + i);
   var address = addr(node);
   console.log("BTC #" + i + ": " + address);
}

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