-
-
Save kennethhutw/2df246ecf9e2eaefcd36b3794dc1d18f to your computer and use it in GitHub Desktop.
ECDSA with secp256k1 in C# - Generate Keys, Sign, Verify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment