Mukil Deepthi Mukil Deepthi - 1 month ago 23
C# Question

Digital signature using bouncy castle and certificate private key

I am developing a feature to digital sign some content. I have valid certificate with a private key. How to digital sign using the private key and bouncy castle?

I tried the following but want some right way to achieve the same using bouncy castle:

X509Certificate2 signingCert =
CryptoHelper.FindCertificate("21A6107EC254457AAF3D4D6FD286FB79");

var rsaObj = (RSACryptoServiceProvider)signingCert.PrivateKey;
_privateKey = rsaObj.ExportParameters(true);


Thanks!

Answer

I donĀ“t know exactly what you need based on your code, but there X509 namespace/code is at bcgit/bc-csharp - X509 and there is an utility class for conversion between System.Security.Cryptography and BouncyCastle bcgit/bc-csharp - DotNetUtilities.cs

BouncyCastle got lots of test (and examples). Have a look at bcgit/bc-csharp - TestCertificateGen.cs too. Maybe this helps you.

EDIT: In general it should go something like this

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;

// Your loaded certificate
X509Certificate cert = null;             

// Your loaded RSA key   
AsymmetricKeyParameter privateKey = null;

AsymmetricKeyParameter publicKey = cert.GetPublicKey();

ISigner signer = SignerUtilities.GetSigner(cert.SigAlgName);

// Init for signing, you pass in the private key
signer.Init(true, privateKey);

// Init for verification, you pass in the public key
signer.Init(false, publicKey);

Greetings