I want to take a private key as input from the user and convert it to a wallet address using C#.

I have seen this in a tutorial to generate a random key:

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

How do I convert a private key string from the user to a wallet address for main net?


Assuming the private key string in this example is 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);

And if you want to get p2sh-segwit and bech32 address, add below lines:

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.