Code to generate extensions with CertEnroll COM

Certificate

Key usage extension:


var keyUsageExtension = new CX509ExtensionKeyUsage();
keyUsageExtension.Critical = true;
keyUsageExtension.InitializeEncode(CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE);
certRequest.X509Extensions.Add((CX509Extension)keyUsageExtension);


Certificate Policies:

var cpOid = new CObjectId();
cpOid.InitializeFromValue("1.3.6.1.4.1.19389......");
var cp = new CCertificatePolicy();
var Qualifier = new CPolicyQualifier();
Qualifier.InitializeEncode("https://somewhere/cps", PolicyQualifierType.PolicyQualifierTypeUrl);
cp.Initialize(cpOid);
cp.PolicyQualifiers.Add(Qualifier);
var cps = new CCertificatePolicies();
cps.Add(cp);
CX509ExtensionCertificatePolicies cpExt = new CX509ExtensionCertificatePolicies();
cpExt.InitializeEncode(cps);
certRequest.X509Extensions.Add((CX509Extension)cpExt);

Subject Alternative Name:

var sanExtension = new CX509ExtensionAlternativeNames() { Critical = false };
var altNames = new CAlternativeNames();
                
var upnAltName = new CAlternativeName();
upnAltName.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_USER_PRINCIPLE_NAME, 
"some@upn.co.il");
altNames.Add(upnAltName);
            
var rfc822 = new CAlternativeName();
rfc822.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_RFC822_NAME, "email@email.co.il");
altNames.Add(rfc822);


string sanDN = "CN=Some Name";
var sanDNName = new CAlternativeName();
CX500DistinguishedName objX500 = new CX500DistinguishedName();
objX500.Encode(sanDN, X500NameFlags.XCN_CERT_NAME_STR_FORCE_UTF8_DIR_STR_FLAG);
var strDirectory = objX500.get_EncodedName(EncodingType.XCN_CRYPT_STRING_BINARY);
sanDNName.InitializeFromRawData(AlternativeNameType.XCN_CERT_ALT_NAME_DIRECTORY_NAME, 
    EncodingType.XCN_CRYPT_STRING_BINARY, strDirectory);
altNames.Add(sanDNName);
            

sanExtension.InitializeEncode(altNames);
certRequest.X509Extensions.Add((CX509Extension)sanExtension);



Enhanced Key Usage:

var ekuExtension = new CX509ExtensionEnhancedKeyUsage() { Critical = false };
var objObjectIds = new CObjectIds();

var objId = new CObjectId();
objId.InitializeFromValue("1.3.6.1.5.5.7.3.2");
objObjectIds.Add(objId);

ekuExtension.InitializeEncode(objObjectIds);
certRequest.X509Extensions.Add((CX509Extension)ekuExtension);

Post a Comment

Previous Post Next Post