I'm following the instructions here to generate a valid ethereum address from scratch. I'm using BouncyCastle's secp256k1 to do the privkey --> pubkey, but I don't know where to get a proper implementation of keccak for C# to do the final step pubkey --> address. Can anyone help me with this?

The BouncyCastle KeccakDigest does not return the same result as in the instructions for the same pubkey.


BouncyCastle KeccakDigest does seem to work : https://github.com/Nethereum/Nethereum/blob/master/src/Nethereum.Util/Sha3Keccack.cs

public byte[] CalculateHash(byte[] value)
            var digest = new KeccakDigest(256);
            var output = new byte[digest.GetDigestSize()];
            digest.BlockUpdate(value, 0, value.Length);
            digest.DoFinal(output, 0);
            return output;

The complete process of generating an address can be understood by the code in https://github.com/Nethereum/Nethereum/blob/master/src/Nethereum.Signer/EthECKey.cs, especially

public string GetPublicAddress()
            var initaddr = new Sha3Keccack().CalculateHash(GetPubKeyNoPrefix());
            var addr = new byte[initaddr.Length - 12];
            Array.Copy(initaddr, 12, addr, 0, initaddr.Length - 12);
            return new AddressUtil().ConvertToChecksumAddress(addr.ToHex());

It is generally quite simple:

  1. Generate random 32 bytes (and verify if they are a valid private key using secp256k1lib) (remember to use secure random generator)
  2. Calculate public key using secp256k1 operations (using secp256k1lib or Bouncy Castle).
  3. Calculate Keccak hash on the 64 bytes of the public key.
  4. Get last 20 bytes of the Keccak hash
  5. Upper / lower case does not really matter for the address but if you want to follow the rules then you may want to look at EIP55

You can check out Nethermind implementation - it uses secp256k1lib instead of Bouncy Castle.

PrivateKey: https://github.com/tkstanczak/nethermind/blob/master/src/Nethermind/Nethermind.Core/Crypto/PrivateKey.cs

Please note that when creating private keys you would like to make sure that they are wiped out from memory and generally hard to be intercepted. Nethermind (and many other existing implementations) does not yet (as of September 2018) handle that with appropriate security so just use it as a reference.

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.