简体   繁体   中英

Generate Bitcoin public/private key from Guid C#

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM