How to request a certificate programmatically using the Certificate Enrollment Web Services (C#)

Hi all,


Some time ago I mentioned a Microsoft SDK sample that uses CertEnroll to access the Certificate Enrollment Web Services and enroll a certificate using a template:

How to access the new Certificate Enrollment Web Services programmatically

Now, if you see that sample, it just selects a certificate template and enrolls the certificate with it, but it doesn't customize the request in any way. And a customer of mine wanted to enroll a certificate with specific properties and extensions like Subject, Key Usage, Key Size and Enhanced Key Usage, in the same way we do it in the following samples:

How to request an smartcard logon cert programmatically (C#) 

How to create a certificate request with CertEnroll and .NET (C#)


So up to this point we have two different codes: one from Microsoft SDK which makes an enrollment requests to the web services, and one which successfully makes custom certificate requests with all the properties and extensions we need to any Certificate Authority. How do we put them together?

The IX509Enrollment2 interface has a Request property of type IX509CertificateRequest that we can use here. We will have to get the Request object first and call the methods we need on it to add all the required info to the cert request, and then call Enroll. The piece of code that puts everything together would look like this:

  // Initialize the request from the template 
 // Customize the request 
 objPkcs10 = objEnroll.Request.GetInnerRequest(InnerRequestLevel.LevelInnermost) as CX509CertificateRequestPkcs10; 
 objPkcs10.Subject = objDN; 
 // Enroll the certificate 

I hope this helps.



Alex (Alejandro Campos Magencio)