I want to get the ether address from private key using C # and the BouncyCastle library, but the correct result does not come out
https://cdn-media-1.freecodecamp.org/images/ftvp6XOxQG9VoczsAV0Nh8YvrdKrafRJYbMt
Code:
using System;
using Org.BouncyCastle.Crypto.Digests;
namespace EthTest
{
public static class ConvertExt
{
public static byte[] Hex2Bytes(this string source)
{
source = source.Trim().ToLower();
var bytes = new byte[source.Length / 2];
for (int i = 0; i < source.Length / 2; i++)
{
int v = 0;
for (int j = i * 2; j < i * 2 + 2; j++)
{
var c = source[j];
v *= 16;
if (c >= '0' && c <= '9') v += (c - '0');
else if (c >= 'a' && c <= 'f') v += (c - 'a' + 10);
}
v &= 0xff;
bytes[i] = (byte)v;
}
return bytes;
}
public static string ToHex(this byte[] ba)
{
string rv = "";
for (int i = 0; i < ba.Length; i++) rv += $"{ba[i]:x2}";
return rv;
}
}
class Program
{
static byte[] Keccak256(byte[] src)
{
var digest = new Sha3Digest();
var result = new byte[digest.GetDigestSize()];
digest.BlockUpdate(src, 0, src.Length);
digest.DoFinal(result, 0);
return result;
}
static (string privKey, string pubKey, string address) CreateEthAddr(byte[] privKey)
{
var secp256k1 = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
var privBi = new Org.BouncyCastle.Math.BigInteger(privKey);
var mult = secp256k1.G.Multiply(privBi);
var x = mult.Normalize().XCoord.ToBigInteger().ToByteArray().ToHex();
var y = mult.Normalize().YCoord.ToBigInteger().ToByteArray().ToHex();
string pubKey = x + y;
var hash = Keccak256(pubKey.Hex2Bytes());
string address = "0x";
for (int i = hash.Length - 20; i < hash.Length; i++) address += $"{hash[i]:x2}";
return (privKey.ToHex(), pubKey, address);
}
static void Main(string[] args)
{
var privKey = new byte[32];
privKey[0] = 1;
var eth = CreateEthAddr(privKey);
Console.WriteLine($"privKey: {eth.privKey}\npubKey: {eth.pubKey}\naddress: {eth.address}\n ");
Console.WriteLine("right address: 0xDC5b20847F43d67928F49Cd4f85D696b5A7617B5");
Console.ReadLine();
}
}
}
Please help!
Thanks.