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
1
dotnet add package Nethereum.Signer
Copied!
Import the Nethereum Signer namespaces:
1
using Nethereum.Signer;
2
using Nethereum.Signer.Crypto;
3
using Nethereum.Util;
4
using Nethereum.Hex.HexConvertors.Extensions;
Copied!
The Bouncy Castle namespaces will also be available, e.g.
1
Org.BouncyCastle.Math.EC.ECPoint p =;
Copied!

ECDSA in C#: Generate / Load Keys

1
// var privKey = EthECKey.GenerateKey(); // Random private key
2
var privKey = new EthECKey( "97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a");
3
byte[] pubKeyCompressed = new ECKey(
4
privKey.GetPrivateKeyAsBytes(), true).GetPubKey(true);
5
Console.WriteLine("Private key: {0}",
6
privKey.GetPrivateKey().Substring(4));
7
Console.WriteLine("Public key: {0}",
8
privKey.GetPubKey().ToHex().Substring(2));
9
Console.WriteLine("Public key (compressed): {0}",
10
pubKeyCompressed.ToHex());
Copied!

ECDSA in C#: Sign Message

1
string msg = "Message for signing";
2
byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
3
byte[] msgHash = new Sha3Keccack().CalculateHash(msgBytes);
4
var signature = privKey.SignAndCalculateV(msgHash);
5
6
Console.WriteLine("Msg: {0}", msg);
7
Console.WriteLine("Msg hash: {0}", msgHash.ToHex());
8
Console.WriteLine("Signature: [v = {0}, r = {1}, s = {2}]",
9
signature.V[0] - 27,
10
signature.R.ToHex(),
11
signature.S.ToHex());
Copied!

ECDSA in C#: Verify Message

1
var pubKeyRecovered =
2
EthECKey.RecoverFromSignature(signature, msgHash);
3
Console.WriteLine("Recovered pubKey: {0}",
4
pubKeyRecovered.GetPubKey().ToHex().Substring(2));
5
6
bool validSig = pubKeyRecovered.Verify(msgHash, signature);
7
Console.WriteLine("Signature valid? {0}", validSig);
Copied!
Last modified 6d ago