Skip to content

Instantly share code, notes, and snippets.

@chgeuer
Last active April 22, 2022 11:17
Show Gist options
  • Save chgeuer/2e57b307d9ffff2eb568 to your computer and use it in GitHub Desktop.
Save chgeuer/2e57b307d9ffff2eb568 to your computer and use it in GitHub Desktop.
Demonstrates how to use BouncyCastle with brainpoolp256r1 curve
namespace microsoft.chgeuer.crypto
{
// compile this baby against https://github.com/bcgit/bc-csharp
// or against NuGet <package id="BouncyCastle" version="1.7.0" targetFramework="net45" />
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
try
{
var algorithm = "brainpoolp256r1";
X9ECParameters brainpoolp256r1Params = ECNamedCurveTable.GetByName(algorithm);
var keyParams = new ECKeyGenerationParameters(
domainParameters: new ECDomainParameters(
curve: brainpoolp256r1Params.Curve,
g: brainpoolp256r1Params.G,
n: brainpoolp256r1Params.N,
h: brainpoolp256r1Params.H),
random: new SecureRandom());
var gen = new ECKeyPairGenerator();
gen.Init(keyParams);
var key = gen.GenerateKeyPair();
string plainText = "Hello World öäü";
var inputData = Encoding.UTF8.GetBytes(plainText);
var privateKey = (ECPrivateKeyParameters)(key.Private);
var signature = GetSignature(inputData, privateKey);
var publicKey = (ECPublicKeyParameters)(key.Public);
var signatureOK = VerifySignature(inputData, publicKey, signature);
Console.WriteLine(string.Format("======= Key Size: {0} =======", keyParams.Strength));
Console.WriteLine("Input Text: " + plainText);
Console.WriteLine("Key ({0} bytes): {1}", privateKey.D.BitLength, privateKey.D);
Console.WriteLine("Signature ({0} bytes): {1}", signature.Length, ToHexString(signature));
Console.WriteLine("Signature verified: {0}", signatureOK);
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
private static byte[] GetSignature(byte[] inputData, ECPrivateKeyParameters privateKey)
{
var signer = SignerUtilities.GetSigner("ECDSA");
signer.Init(true, privateKey);
signer.BlockUpdate(inputData, 0, inputData.Length);
return signer.GenerateSignature();
}
private static bool VerifySignature(byte[] inputData, ECPublicKeyParameters publicKey, byte[] signature)
{
var signer = SignerUtilities.GetSigner("ECDSA");
signer.Init(false, publicKey);
signer.BlockUpdate(inputData, 0, inputData.Length);
return signer.VerifySignature(signature);
}
private static string ToHexString(IEnumerable<byte> b)
{
var sb = new StringBuilder();
foreach (byte b1 in b)
{
sb.Append(b1.ToString("X2"));
}
return sb.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment