// create the certifcate request public string createCertifcate(string hostName) { // Create all the objects that will be required CX509CertificateRequestPkcs10 objPkcs10 = new CX509CertificateRequestPkcs10(); CX509PrivateKey objPrivateKey = new CX509PrivateKey(); CCspInformation objCSP = new CCspInformation(); CCspInformations objCSPs = new CCspInformations(); CX500DistinguishedName objDN = new CX500DistinguishedName(); CX509Enrollment objEnroll = new CX509Enrollment(); CObjectIds objObjectIds = new CObjectIds(); CObjectId objObjectId = new CObjectId(); CX509ExtensionKeyUsage objExtensionKeyUsage = new CX509ExtensionKeyUsage(); CX509ExtensionEnhancedKeyUsage objX509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage(); string CertifcateStr; try { SqlLite sql = new SqlLite(); /*Check if there is allready request for the hostname so we dont need to create new one*/ if (sql.checkCertExsits(hostName) == 1) { return("Exsits"); } if (sql.checkCertExsits(hostName) == 2) { return("Issued"); } //create the private key (CX509CertificateRequestPkcs10 will initilizae from the private key) objCSP.InitializeFromName("Microsoft Enhanced Cryptographic Provider v1.0"); objCSPs.Add(objCSP); objPrivateKey.Length = 1024; objPrivateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; objPrivateKey.MachineContext = false; objPrivateKey.CspInformations = objCSPs; objPrivateKey.Create(); //create pkc10 object from the privaet key objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, objPrivateKey, ""); objExtensionKeyUsage.InitializeEncode(CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE); // objPkcs10.X509Extensions.Add((CX509Extension)objExtensionKeyUsage); // objObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // objObjectIds.Add(objObjectId); // objX509ExtensionEnhancedKeyUsage.InitializeEncode(objObjectIds); // objPkcs10.X509Extensions.Add((CX509Extension)objX509ExtensionEnhancedKeyUsage); objDN.Encode("CN=" + hostName, X500NameFlags.XCN_CERT_NAME_STR_NONE); //create DistinguishedName objPkcs10.Subject = objDN; //initial the DistinguishedName objEnroll.InitializeFromRequest(objPkcs10); //init enrollement request CertifcateStr = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); //Certifcate Request return(CertifcateStr); } catch (Exception ex) { return("Error" + ex.Message); } }