C# Crypto Libraries

C# Crypto Libraries


Cryptography in C# and .NET

  • Bouncy Castle .NET and Nethereum:Hashes, ECC and ECDSA

.NET Cryptography and Bouncy Castle .NET

  • Cryptography in C# and .NET is based on:

  • Nethereum – a simplified library for Ethereum and secp256k1

    • The cryptographic functionality is in Nethereum.Signer

    • Nethereum also includes the Bouncy Castle .NET library

ECDSA in C#: Initialize the Application

Install the "Nethereum.Signer" package from NuGet

dotnet add package Nethereum.Signer

Import the Nethereum Signer namespaces:

using Nethereum.Signer;
using Nethereum.Signer.Crypto;
using Nethereum.Util;
using Nethereum.Hex.HexConvertors.Extensions;

The Bouncy Castle namespaces will also be available, e.g.

Org.BouncyCastle.Math.EC.ECPoint p = …;

ECDSA in C#: Generate / Load Keys

// var privKey = EthECKey.GenerateKey(); // Random private key
var privKey = new EthECKey( "97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a");
byte[] pubKeyCompressed = new ECKey(
  privKey.GetPrivateKeyAsBytes(), true).GetPubKey(true);
Console.WriteLine("Private key: {0}",
Console.WriteLine("Public key: {0}",
Console.WriteLine("Public key (compressed): {0}",

Complete example:https://gist.github.com/nakov/f2a579eb9893b29338b11e063d6f80c2

ECDSA in C#: Sign Message

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,

Complete example:https://gist.github.com/nakov/f2a579eb9893b29338b11e063d6f80c2

ECDSA in C#: Verify Message

var pubKeyRecovered =
  EthECKey.RecoverFromSignature(signature, msgHash);
Console.WriteLine("Recovered pubKey: {0}",

bool validSig = pubKeyRecovered.Verify(msgHash, signature);
Console.WriteLine("Signature valid? {0}", validSig);

Complete example:https://gist.github.com/nakov/f2a579eb9893b29338b11e063d6f80c2

Last updated