How to generate a PKCS#10 certification request in C#

Modified on 2012/04/25 19:43 by Administrator — Categorized as: Uncategorized

The following function generates a PKCS#10 certification request. It uses the library BouncyCastle to manage the ASN1 objects involved in PKCS#10 request and to perform the Der encoding:

public static byte[] generatePKCS10CertificationRequest(string distinguishedName, RSAPrivateKey priKey, RSAPublicKey pubKey, Session session)
{
     X509Name subject = new X509Name(distinguishedName);
           
     RsaPublicKeyStructure pk = new RsaPublicKeyStructure(new BigInteger(1, pubKey.Modulus), new BigInteger(1, pubKey.PublicExponent));

     SubjectPublicKeyInfo pkInfo = new SubjectPublicKeyInfo(new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance), pk.GetDerEncoded());

     CertificationRequestInfo reqInfo = new CertificationRequestInfo(subject, pkInfo, null);

     byte[] toSign = reqInfo.GetDerEncoded();

     session.SignInit(Mechanism.SHA1_RSA_PKCS, priKey);

     byte[] signature = session.Sign(toSign);

     CertificationRequest pkcs10 = new CertificationRequest(reqInfo, new AlgorithmIdentifier(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Sha1WithRsaEncryption, DerNull.Instance), new DerBitString(signature));

     return pkcs10.GetDerEncoded();
}