Home > front end >  Generate Bitcoin public/private key from Guid C#
Generate Bitcoin public/private key from Guid C#

Time:11-14

I have a randomly generated 128 bit guid (cryptographically secure). How can I use this as a seed to generate a public and private key for Bitcoin, using C#? By seed, I mean that every time I use the same guid as input, it should result in the same public/private keys.

I have looked at NBitcoin, but don't understand how to pull it off.

CodePudding user response:

You can directly create 32 random bytes to be your private key. Example below. But it is VERY important: these 32 bytes must be from cryptographically-secure pseudorandom generator. For example, if you use C# built-in Random class, anyone will be able to restore your private keys with regular computer. You need to be very careful if you plan to use this in real bitcoin network. I am not sure if Guid generation is cryptographically-secure.

static void Main(string[] args)
{
    byte[] GetRawKey()
    {
        // private key=1 in this example
        byte[] data = new byte[32];
        data[^1] = 1;
        return data;
    }

    var key = new Key(GetRawKey()); // private key
    var pair = key.CreateKeyPair(); // key pair (pub priv keys)
    var addrP2pkh = key.GetAddress(ScriptPubKeyType.Legacy, Network.Main); // P2PKH address
    var addrP2sh = key.GetAddress(ScriptPubKeyType.SegwitP2SH, Network.Main); // Segwit P2SH address
    Console.WriteLine(addrP2pkh.ToString());
    Console.WriteLine(addrP2sh.ToString());
}
  • Related