Skip to content

Instantly share code, notes, and snippets.

@nakov
Last active October 26, 2022 23:18
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nakov/f2a579eb9893b29338b11e063d6f80c2 to your computer and use it in GitHub Desktop.
Save nakov/f2a579eb9893b29338b11e063d6f80c2 to your computer and use it in GitHub Desktop.
ECDSA with secp256k1 in C# - Generate Keys, Sign, Verify
using System;
using System.Text;
using Nethereum.Hex.HexConvertors.Extensions;
using Nethereum.Signer;
using Nethereum.Util;
using Nethereum.Signer.Crypto;
class ECDSASecp256k1Example
{
static void Main()
{
//var privKey = EthECKey.GenerateKey();
var privKey = new EthECKey("97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a");
byte[] pubKeyCompressed = new ECKey(privKey.GetPrivateKeyAsBytes(), true).GetPubKey(true);
Console.WriteLine("Private key: {0}", privKey.GetPrivateKey().Substring(4));
Console.WriteLine("Public key: {0}", privKey.GetPubKey().ToHex().Substring(2));
Console.WriteLine("Public key (compressed): {0}", pubKeyCompressed.ToHex());
Console.WriteLine();
string msg = "Message for signing";
byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
byte[] msgHash = new Sha3Keccack().CalculateHash(msgBytes);
var signature = privKey.SignAndCalculateV(msgHash);
Console.WriteLine("Msg: {0}", msg);
Console.WriteLine("Msg hash: {0}", msgHash.ToHex());
Console.WriteLine("Signature: [v = {0}, r = {1}, s = {2}]",
signature.V[0] - 27, signature.R.ToHex(), signature.S.ToHex());
Console.WriteLine();
var pubKeyRecovered = EthECKey.RecoverFromSignature(signature, msgHash);
Console.WriteLine("Recovered pubKey: {0}", pubKeyRecovered.GetPubKey().ToHex().Substring(2));
bool validSig = pubKeyRecovered.Verify(msgHash, signature);
Console.WriteLine("Signature valid? {0}", validSig);
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Nethereum.Signer" Version="2.4.0" />
</ItemGroup>
</Project>
@woncode
Copy link

woncode commented Apr 7, 2022

where is EthECKey definition?

@woncode
Copy link

woncode commented Apr 7, 2022

i see, Nethereum.Signer PackageReference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment