public string CreateRequest(string cn, string ou, string o, string l, string s, string c, string oid, int keylength) { var objCSPs = new CCspInformations(); objCSPs.AddAvailableCsps(); var objPrivateKey = new CX509PrivateKey(); objPrivateKey.Length = keylength; objPrivateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379409(v=vs.85).aspx objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379417(v=vs.85).aspx objPrivateKey.MachineContext = false; //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379024(v=vs.85).aspx objPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379412(v=vs.85).aspx objPrivateKey.CspInformations = objCSPs; objPrivateKey.Create(); var objPkcs10 = new CX509CertificateRequestPkcs10(); objPkcs10.InitializeFromPrivateKey( X509CertificateEnrollmentContext.ContextUser, //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379399(v=vs.85).aspx objPrivateKey, string.Empty); var objExtensionKeyUsage = new CX509ExtensionKeyUsage(); objExtensionKeyUsage.InitializeEncode( CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | // http://msdn.microsoft.com/en-us/library/windows/desktop/aa379410(v=vs.85).aspx CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE | // http://msdn.microsoft.com/en-us/library/windows/desktop/aa379410(v=vs.85).aspx CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | // http://msdn.microsoft.com/en-us/library/windows/desktop/aa379410(v=vs.85).aspx CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE); // http://msdn.microsoft.com/en-us/library/windows/desktop/aa379410(v=vs.85).aspx objPkcs10.X509Extensions.Add((CX509Extension)objExtensionKeyUsage); var objObjectId = new CObjectId(); var objObjectIds = new CObjectIds(); var objX509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage(); //objObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.1"); objObjectId.InitializeFromValue(oid); //Some info about OIDS: http://www.alvestrand.no/objectid/1.3.6.1.5.5.7.3.html objObjectIds.Add(objObjectId); objX509ExtensionEnhancedKeyUsage.InitializeEncode(objObjectIds); objPkcs10.X509Extensions.Add((CX509Extension)objX509ExtensionEnhancedKeyUsage); // TODO: Create CERTS with SAN: http://msdn.microsoft.com/en-us/library/windows/desktop/aa378081(v=vs.85).aspx /* var test3 = new CX509ExtensionAlternativeNames(); var test4 = new CAlternativeName(); var test2 = new CAlternativeNames(); test4.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME,"CRAP.no"); test2.Add(test4); test3.InitializeEncode(test2); */ //objPkcs10.X509Extensions.Add((CX509Extension)); var objDN = new CX500DistinguishedName(); var subjectName = "CN = " + cn + ",OU = " + ou + ",O = " + o + ",L = " + l + ",S = " + s + ",C = " + c; objDN.Encode(subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379394(v=vs.85).aspx objPkcs10.Subject = objDN; var objEnroll = new CX509Enrollment(); objEnroll.InitializeFromRequest(objPkcs10); var strRequest = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); //http://msdn.microsoft.com/en-us/library/windows/desktop/aa374936(v=vs.85).aspx return strRequest; }
public static bool Enroll(string username, WindowsCertificate agentCertificate, string caConfig, string template, string csr, out string errorMessage, out X509Certificate2 cert) { errorMessage = null; cert = null; string argsUser = username; X509Store store = new X509Store("My", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); // Create a PKCS 10 inner request. CX509CertificateRequestPkcs10 pkcs10Req; try { pkcs10Req = new CX509CertificateRequestPkcs10(); pkcs10Req.InitializeDecode(csr, EncodingType.XCN_CRYPT_STRING_BASE64_ANY); } catch (Exception ex) { errorMessage = "Unable to create PKCS10 request, malformed CSR?" + Environment.NewLine + ex.Message; return(false); } // Create a CMC outer request and initialize CX509CertificateRequestCmc cmcReq; try { cmcReq = new CX509CertificateRequestCmc(); cmcReq.InitializeFromInnerRequestTemplateName(pkcs10Req, template); cmcReq.RequesterName = argsUser; } catch (Exception ex) { errorMessage = "Unable to create CMC request, bad certificate template?" + Environment.NewLine + ex.Message; return(false); } if (agentCertificate.StoreLocation == StoreLocation.CurrentUser) { try { CSignerCertificate signer = new CSignerCertificate(); signer.Initialize(false, X509PrivateKeyVerify.VerifyNone, EncodingType.XCN_CRYPT_STRING_HEXRAW, agentCertificate.Certificate.Thumbprint); cmcReq.SignerCertificate = signer; } catch (COMException ex) when(ex.HResult == (int)WindowsCryptoApiErrors.CRYPT_E_NOT_FOUND) { errorMessage = "Agent certificate was not found in the CurrentUser store"; return(false); } catch (COMException ex) when(ex.HResult == (int)WindowsCryptoApiErrors.NTE_NO_KEY) { errorMessage = "Could not access the key of the agent certificate. Perhaps you do not have permissions for it?" + Environment.NewLine + Environment.NewLine + "Consult the manual for more information"; return(false); } catch (Exception ex) { errorMessage = "Unable to initialize signer, bad agent certificate?" + Environment.NewLine + ex.Message; return(false); } } else if (agentCertificate.StoreLocation == StoreLocation.LocalMachine) { try { CSignerCertificate signer = new CSignerCertificate(); signer.Initialize(true, X509PrivateKeyVerify.VerifyNone, EncodingType.XCN_CRYPT_STRING_HEXRAW, agentCertificate.Certificate.Thumbprint); cmcReq.SignerCertificate = signer; } catch (COMException ex) when(ex.HResult == (int)WindowsCryptoApiErrors.CRYPT_E_NOT_FOUND) { errorMessage = "Agent certificate was not found in the LocalMachine store"; return(false); } catch (COMException ex) when(ex.HResult == (int)WindowsCryptoApiErrors.NTE_NO_KEY) { errorMessage = "Could not access the key of the agent certificate. Perhaps you do not have permissions for it?" + Environment.NewLine + Environment.NewLine + "Consult the manual for more information"; return(false); } catch (Exception ex) { errorMessage = "Unable to initialize signer, bad agent certificate?" + Environment.NewLine + ex.Message; return(false); } } else { errorMessage = "Agent certificate was not found in any store"; return(false); } // encode the request cmcReq.Encode(); string strRequest = cmcReq.RawData[EncodingType.XCN_CRYPT_STRING_BASE64]; CCertRequest objCertRequest = new CCertRequest(); // Get CA config from UI string strCAConfig = caConfig; // Submit the request int iDisposition; try { iDisposition = objCertRequest.Submit(CR_IN_BASE64 | CR_IN_FORMATANY, strRequest, null, strCAConfig); } catch (Exception ex) { errorMessage = "Unable to submit signing request, bad CA config?" + Environment.NewLine + ex.Message; return(false); } // Check the submission status if (CR_DISP_ISSUED != iDisposition) // Not enrolled { string strDisposition = objCertRequest.GetDispositionMessage(); errorMessage = strDisposition; if (CR_DISP_UNDER_SUBMISSION == iDisposition) { return(false); } errorMessage = errorMessage + Environment.NewLine + objCertRequest.GetLastStatus(); return(false); } // Get the certificate string strCert = objCertRequest.GetCertificate(CR_OUT_BASE64); byte[] rawCert = Convert.FromBase64String(strCert); cert = new X509Certificate2(rawCert); return(true); }
private string BuildEncodedCsr(CX509CertificateRequestPkcs10 pkcs10) { CX509Enrollment enrollment = new CX509Enrollment(); enrollment.InitializeFromRequest(pkcs10); return(enrollment.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64)); }
private void button1_Click(object sender, EventArgs e) { const int ECDSA_PRIVATE_P256_MAGIC = 0x32534345; if (saveFileDialog1.ShowDialog() != DialogResult.OK) { return; } KeyPair key = (KeyPair)comboBox1.SelectedItem; byte[] pubkey = key.PublicKey.EncodePoint(false).Skip(1).ToArray(); byte[] prikey = BitConverter.GetBytes(ECDSA_PRIVATE_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).Concat(key.PrivateKey).ToArray(); CX509PrivateKey x509key = new CX509PrivateKey(); x509key.AlgorithmName = "ECDSA_P256"; x509key.Import("ECCPRIVATEBLOB", Convert.ToBase64String(prikey)); Array.Clear(prikey, 0, prikey.Length); CX509CertificateRequestPkcs10 request = new CX509CertificateRequestPkcs10(); request.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, x509key, null); request.Subject = new CX500DistinguishedName(); request.Subject.Encode($"CN={textBox1.Text},C={textBox2.Text},S={textBox3.Text},SERIALNUMBER={textBox4.Text}"); request.Encode(); File.WriteAllText(saveFileDialog1.FileName, "-----BEGIN NEW CERTIFICATE REQUEST-----\r\n" + request.RawData + "-----END NEW CERTIFICATE REQUEST-----\r\n"); Close(); }
static void Main() { CX509Enrollment enroll = new CX509Enrollment(); CX509PrivateKey pri = new CX509PrivateKey(); CX509CertificateRequestPkcs10 request = new CX509CertificateRequestPkcs10(); CX500DistinguishedName dn = new CX500DistinguishedName(); pri.ProviderName = "eToken Base Cryptographic Provider"; pri.Length = 2048; pri.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; //pri.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG; pri.ProviderType = X509ProviderType.XCN_PROV_RSA_FULL; pri.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_NONE; request.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, pri, ""); dn.Encode("CN=KimiNoNaWa", X500NameFlags.XCN_CERT_NAME_STR_DISABLE_UTF8_DIR_STR_FLAG); request.Subject = dn; enroll.InitializeFromRequest(request); string pkcs10 = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); Console.WriteLine(pkcs10); //Do Enrollment //Install certificate //enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedRoot, pkcs10, EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER, ""); }
public void DecodeCSR(string csr, out string distinguishedName, out int publicKeyLength, out string hashAlgo) { CX509CertificateRequestPkcs10 request = new CX509CertificateRequestPkcs10(); request.InitializeDecode(csr, EncodingType.XCN_CRYPT_STRING_BASE64_ANY); request.CheckSignature(); distinguishedName = ((CX500DistinguishedName)request.Subject).Name; publicKeyLength = request.PublicKey.Length; hashAlgo = request.HashAlgorithm.FriendlyName; }
private string GetSubjectDNFromRequest() { CX509CertificateRequestPkcs10 req = new CX509CertificateRequestPkcs10(); string csr = new StreamReader(Context.Request.InputStream).ReadToEnd(); req.InitializeDecode(csr, EncodingType.XCN_CRYPT_STRING_BASE64_ANY); req.CheckSignature(); return(((CX500DistinguishedName)req.Subject).Name); }
private CertificateRequest CreateCsrFromPrivateKey(CertificateSubject subject, CipherAlgorithm cipher, int keysize, CX509PrivateKey privateKey) { CertificateRequest csr = new CertificateRequest(subject, cipher, keysize); CX509CertificateRequestPkcs10 pkcs10 = NewCertificateRequestPkcs10(csr.Subject, privateKey); csr.SubjectKeyIdentifier = GetSubjectKeyIdentifier(pkcs10); csr.EncodedCsr = BuildEncodedCsr(pkcs10); return(csr); }
internal static Pkcs10CertificationRequest createKeyPair() { var objCSPs = new CCspInformations(); objCSPs.AddAvailableCsps(); var objPrivateKey = new CX509PrivateKey(); objPrivateKey.Length = 1024; objPrivateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; objPrivateKey.MachineContext = false; objPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; objPrivateKey.CspInformations = objCSPs; objPrivateKey.Create(); var objPkcs10 = new CX509CertificateRequestPkcs10(); objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, objPrivateKey, string.Empty); //var objExtensionKeyUsage = new CX509ExtensionKeyUsage(); //objExtensionKeyUsage.InitializeEncode( // CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_CERT_SIGN_KEY_USAGE | // CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_CRL_SIGN_KEY_USAGE); //objPkcs10.X509Extensions.Add((CX509Extension)objExtensionKeyUsage); //var objObjectId = new CObjectId(); //var objObjectIds = new CObjectIds(); //var objX509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage(); //objObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.2"); //objObjectIds.Add(objObjectId); //objX509ExtensionEnhancedKeyUsage.InitializeEncode(objObjectIds); //objPkcs10.X509Extensions.Add((CX509Extension)objX509ExtensionEnhancedKeyUsage); var objDN = new CX500DistinguishedName(); var subjectName = "CN = shaunxu.me, OU = ADCS, O = Blog, L = Beijng, S = Beijing, C = CN"; objDN.Encode(subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); objPkcs10.Subject = objDN; var objEnroll = new CX509Enrollment(); objEnroll.InitializeFromRequest(objPkcs10); var strRequest = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); Pkcs10CertificationRequest p10 = new Pkcs10CertificationRequest(Convert.FromBase64String(strRequest)); return(p10); }
protected static string GenerateCSR() { var objPrivateKey = new CX509PrivateKey(); objPrivateKey.MachineContext = false; objPrivateKey.Length = 2048; objPrivateKey.ProviderType = X509ProviderType.XCN_PROV_RSA_AES; objPrivateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; objPrivateKey.CspInformations = new CCspInformations(); objPrivateKey.CspInformations.AddAvailableCsps(); objPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; objPrivateKey.Create(); var cert = new CX509CertificateRequestPkcs10(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, objPrivateKey, string.Empty); var objExtensionKeyUsage = new CX509ExtensionKeyUsage(); objExtensionKeyUsage.InitializeEncode((X509KeyUsageFlags)X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE | X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE ); cert.X509Extensions.Add((CX509Extension)objExtensionKeyUsage); var cobjectId = new CObjectId(); cobjectId.InitializeFromName(CERTENROLL_OBJECTID.XCN_OID_PKIX_KP_CLIENT_AUTH); var cobjectIds = new CObjectIds(); cobjectIds.Add(cobjectId); var pValue = cobjectIds; var cx509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage(); cx509ExtensionEnhancedKeyUsage.InitializeEncode(pValue); cert.X509Extensions.Add((CX509Extension)cx509ExtensionEnhancedKeyUsage); var cx509Enrollment = new CX509Enrollment(); cx509Enrollment.InitializeFromRequest(cert); var output = cx509Enrollment.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); return(output); }
private CX509CertificateRequestPkcs10 NewCertificateRequestPkcs10(CertificateSubject subject, CX509PrivateKey privateKey) { CX509CertificateRequestPkcs10 pkcs10 = new CX509CertificateRequestPkcs10(); pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); if (subject.ContainsSubjectAlternativeName) { pkcs10.X509Extensions.Add(GetQualifiedSan(subject.SubjectAlternativeName)); } pkcs10.X509Extensions.Add(GetKeyUsage()); pkcs10.Subject = GetEncodedSubject(subject); return(pkcs10); }
//rennew certficiate that expired public int RenewCert(string Cert, int reqid) { int iDisposition; string CertifcateStr; string status; string HostName; CX509CertificateRequestPkcs10 objPkcs10 = new CX509CertificateRequestPkcs10(); CX509Enrollment objEnroll = new CX509Enrollment(); CCertConfig objCertConfig = new CCertConfig(); CX500DistinguishedName objDN = new CX500DistinguishedName(); CCertAdmin objCertAdmin = new CCertAdmin(); string strCAConfig; var inheritOptions = X509RequestInheritOptions.InheritPrivateKey | X509RequestInheritOptions.InheritSubjectFlag | X509RequestInheritOptions.InheritExtensionsFlag | X509RequestInheritOptions.InheritSubjectAltNameFlag; try { strCAConfig = objCertConfig.GetConfig(CC_DEFAULTCONFIG); //connect to the ca InstallCert(Cert); objPkcs10.InitializeFromCertificate(X509CertificateEnrollmentContext.ContextUser, Cert, EncodingType.XCN_CRYPT_STRING_BASE64HEADER, inheritOptions); //create new cert request from exists expired cert objDN = objPkcs10.Subject; //getting old cert subject (hostname) HostName = objDN.Name.ToString().Substring(3); objEnroll.InitializeFromRequest(objPkcs10); //create enroll rquest CertifcateStr = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); //crearte new cert request Database db = new Database(); var cert = db.ReturnCertificateInformation(HostName); db.DeleteCertificateRecordFromDb(reqid); // revokeCert(cert.serialnumber); iDisposition = SubmitRequest(CertifcateStr, HostName); //submit cert to the ca objCertAdmin.ResubmitRequest(strCAConfig, iDisposition); //issue the Certificate if (iDisposition > 0) //if cert was created delete the old cert from the table { DeleteCertificateFromStore(objDN.Name.ToString()); return(iDisposition); } return(0); } catch (Exception ex) { status = ex.Message; Database db = new Database(); db.InsertToErrorMessageTable("", reqid, ex.Message, "RenewCert");//insert Error Message into The Error Table Log In The DataBase return(1); } }
public string CreateTemplateRequest(string cn, string ou, string o, string l, string s, string c, int keyLength, string templateName) { var csp = new CCspInformations(); csp.AddAvailableCsps(); var privateKey = new CX509PrivateKey(); privateKey.Length = keyLength; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; privateKey.MachineContext = false; privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.CspInformations = csp; privateKey.Create(); var pkcs10 = new CX509CertificateRequestPkcs10(); pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, templateName); var san = GetSAN(cn); pkcs10.X509Extensions.Add((CX509Extension)san); var distinguishedName = new CX500DistinguishedName(); var subjectName = $"{cn},OU = {ou},O = {o} ,L = {l},S = {s},C = {c}"; distinguishedName.Encode(subjectName); pkcs10.Subject = distinguishedName; var enroll = new CX509Enrollment(); enroll.InitializeFromRequest(pkcs10); var strRequest = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64HEADER); return(strRequest); }
/// <summary> /// The create active directory certificate request. /// </summary> /// <param name="templateName"> /// The template name. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public string CreateActiveDirectoryCertificateRequest(string templateName) { //// https://blogs.msdn.microsoft.com/alejacma/2008/09/05/how-to-create-a-certificate-request-with-certenroll-and-net-c/ //// http://geekswithblogs.net/shaunxu/archive/2012/01/13/working-with-active-directory-certificate-service-via-c.aspx this.LastError.Clear(); try { var cspInformations = new CCspInformations(); cspInformations.AddAvailableCsps(); var privateKey = new CX509PrivateKey // Создали приватный ключ { Length = 2048, KeySpec = X509KeySpec.XCN_AT_SIGNATURE, KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES, MachineContext = false, ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG, CspInformations = cspInformations }; privateKey.Create(); var objPkcs10 = new CX509CertificateRequestPkcs10(); objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, templateName); var objEnroll = new CX509Enrollment(); objEnroll.InitializeFromRequest(objPkcs10); var strRequest = objEnroll.CreateRequest(); // Значение по уолчанию: EncodingType.XCN_CRYPT_STRING_BASE64 return(strRequest); } catch (Exception ex) { this.LastError.Add(ex.Message); return(string.Empty); } }
private void richTextBox1_TextChanged(object sender, EventArgs e) { try { contextMenuStrip1.Enabled = false; string csr = richTextBox1.Text; CX509CertificateRequestPkcs10 request = new CX509CertificateRequestPkcs10(); request.InitializeDecode(csr, EncodingType.XCN_CRYPT_STRING_BASE64_ANY); request.CheckSignature(); string[] csrArray = Functions.explode(",", ((CX500DistinguishedName)request.Subject).Name); string[] E = Functions.explode("=", csrArray[0]); string[] CN = Functions.explode("=", csrArray[1]); string[] OU = Functions.explode("=", csrArray[2]); string[] O = Functions.explode("=", csrArray[3]); string[] L = Functions.explode("=", csrArray[4]); string[] S = Functions.explode("=", csrArray[5]); string[] C = Functions.explode("=", csrArray[6]); Font boldfont = new Font("Arial", 10, FontStyle.Bold); Font normalfont = new Font("Arial", 10, FontStyle.Regular); richTextBox2.SelectionFont = boldfont; richTextBox2.AppendText("Common Name: "); richTextBox2.SelectionFont = normalfont; richTextBox2.AppendText(CN[1]); richTextBox2.SelectionFont = boldfont; richTextBox2.AppendText("\nOrganization: "); richTextBox2.SelectionFont = normalfont; richTextBox2.AppendText(O[1]); richTextBox2.SelectionFont = boldfont; richTextBox2.AppendText("\nOrganization Unit: "); richTextBox2.SelectionFont = normalfont; richTextBox2.AppendText(OU[1]); richTextBox2.SelectionFont = boldfont; richTextBox2.AppendText("\nLocality: "); richTextBox2.SelectionFont = normalfont; richTextBox2.AppendText(L[1]); richTextBox2.SelectionFont = boldfont; richTextBox2.AppendText("\nState: "); richTextBox2.SelectionFont = normalfont; richTextBox2.AppendText(S[1]); richTextBox2.SelectionFont = boldfont; richTextBox2.AppendText("\nCountry: "); richTextBox2.SelectionFont = normalfont; richTextBox2.AppendText(C[1]); richTextBox2.SelectionFont = boldfont; richTextBox2.AppendText("\nEmail: "); richTextBox2.SelectionFont = normalfont; richTextBox2.AppendText(E[1]); richTextBox2.SelectionFont = boldfont; richTextBox2.AppendText("\nPublic Key Lenth: "); richTextBox2.SelectionFont = normalfont; richTextBox2.AppendText(request.PublicKey.Length.ToString()); richTextBox2.SelectionFont = boldfont; richTextBox2.AppendText("\nHash Algorithm Friendly Name: "); richTextBox2.SelectionFont = normalfont; richTextBox2.AppendText(request.HashAlgorithm.FriendlyName.ToString()); } catch { richTextBox2.Clear(); } finally { richTextBox1.Focus(); contextMenuStrip1.Enabled = true; } }
// 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 { Database db = new Database(); /*Check if there is allready request for the hostname so we dont need to create new one*/ if (db.CheckIfCertificateExists(hostName) == 1) { return("Exsits"); } if (db.CheckIfCertificateExists(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) { Database db = new Database(); db.InsertToErrorMessageTable(hostName, 0, ex.Message, "CreateCertifcate");//insert Error Message into The Error Table Log In The DataBase return("Error" + ex.Message); } }
public void GenerateCsr(SSLCertificate cert) { // Create all the objects that will be required CX509CertificateRequestPkcs10 pkcs10 = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509CertificateRequestPkcs10", true)) as CX509CertificateRequestPkcs10; CX509PrivateKey privateKey = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey", true)) as CX509PrivateKey; CCspInformation csp = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CCspInformation", true)) as CCspInformation; CCspInformations csPs = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CCspInformations", true)) as CCspInformations; CX500DistinguishedName dn = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX500DistinguishedName", true)) as CX500DistinguishedName; CX509Enrollment enroll = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment", true)) as CX509Enrollment; CObjectIds objectIds = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CObjectIds", true)) as CObjectIds; CObjectId objectId = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CObjectId", true)) as CObjectId; CX509ExtensionKeyUsage extensionKeyUsage = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionKeyUsage", true)) as CX509ExtensionKeyUsage; CX509ExtensionEnhancedKeyUsage x509ExtensionEnhancedKeyUsage = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionEnhancedKeyUsage", true)) as CX509ExtensionEnhancedKeyUsage; try { // Initialize the csp object using the desired Cryptograhic Service Provider (CSP) csp.InitializeFromName("Microsoft RSA SChannel Cryptographic Provider"); // Add this CSP object to the CSP collection object csPs.Add(csp); // Provide key container name, key length and key spec to the private key object privateKey.Length = cert.CSRLength; privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_ARCHIVING_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_ARCHIVING_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.MachineContext = true; // Provide the CSP collection object (in this case containing only 1 CSP object) // to the private key object privateKey.CspInformations = csPs; // Create the actual key pair privateKey.Create(); // Initialize the PKCS#10 certificate request object based on the private key. // Using the context, indicate that this is a user certificate request and don't // provide a template name pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.PrivateKey = privateKey.ToString(); // Key Usage Extension extensionKeyUsage.InitializeEncode( CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE | CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE ); pkcs10.X509Extensions.Add((CX509Extension)extensionKeyUsage); // Enhanced Key Usage Extension objectId.InitializeFromName(CertEnrollInterop.CERTENROLL_OBJECTID.XCN_OID_PKIX_KP_SERVER_AUTH); objectIds.Add(objectId); x509ExtensionEnhancedKeyUsage.InitializeEncode(objectIds); pkcs10.X509Extensions.Add((CX509Extension)x509ExtensionEnhancedKeyUsage); // Encode the name in using the Distinguished Name object string request = String.Format(@"CN={0}, O={1}, OU={2}, L={3}, S={4}, C={5}", cert.Hostname, cert.Organisation, cert.OrganisationUnit, cert.City, cert.State, cert.Country); dn.Encode(request, X500NameFlags.XCN_CERT_NAME_STR_NONE); // enable SMIME capabilities pkcs10.SmimeCapabilities = true; // Assing the subject name by using the Distinguished Name object initialized above pkcs10.Subject = dn; // Create enrollment request enroll.InitializeFromRequest(pkcs10); enroll.CertificateFriendlyName = cert.FriendlyName; cert.CSR = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER); } catch (Exception ex) { Log.WriteError("Error creating CSR", ex); } }
private static void Enroll(string publicKeyAsPem, string username, string agentCertificate, string caConfig) { string argsKey = agentCertificate; string argsUser = username; X509Store store = new X509Store("My", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); publicKeyAsPem = string.Join("", publicKeyAsPem.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Where(s => !s.StartsWith("--"))); // Create a PKCS 10 inner request. CX509PublicKey pubKey = new CX509PublicKey(); pubKey.InitializeFromEncodedPublicKeyInfo(publicKeyAsPem); CObjectId sha512 = new CObjectId(); sha512.InitializeFromValue("2.16.840.1.101.3.4.2.3"); CX509CertificateRequestPkcs10 pkcs10Req = new CX509CertificateRequestPkcs10(); pkcs10Req.InitializeFromPublicKey(X509CertificateEnrollmentContext.ContextUser, pubKey, ""); pkcs10Req.HashAlgorithm = sha512; string toSign = pkcs10Req.RawDataToBeSigned[EncodingType.XCN_CRYPT_STRING_HASHDATA]; //using (YubikeyPivTool piv = new YubikeyPivTool()) //{ // //piv. //} // Create a CMC outer request and initialize CX509CertificateRequestCmc cmcReq = new CX509CertificateRequestCmc(); cmcReq.InitializeFromInnerRequestTemplateName(pkcs10Req, "SmartcardLogon"); cmcReq.RequesterName = argsUser; CSignerCertificate signer = new CSignerCertificate(); signer.Initialize(false, X509PrivateKeyVerify.VerifyNone, (EncodingType)0xc, argsKey); cmcReq.SignerCertificate = signer; // encode the request cmcReq.Encode(); string strRequest = cmcReq.RawData[EncodingType.XCN_CRYPT_STRING_BASE64]; CCertRequest objCertRequest = new CCertRequest(); // Get CA config from UI string strCAConfig = caConfig; // Submit the request int iDisposition = objCertRequest.Submit(CR_IN_BASE64 | CR_IN_FORMATANY, strRequest, null, strCAConfig); // Check the submission status if (CR_DISP_ISSUED != iDisposition) // Not enrolled { string strDisposition = objCertRequest.GetDispositionMessage(); if (CR_DISP_UNDER_SUBMISSION == iDisposition) { Console.WriteLine("The submission is pending: " + strDisposition); return; } Console.WriteLine("The submission failed: " + strDisposition); Console.WriteLine("Last status: " + objCertRequest.GetLastStatus()); return; } // Get the certificate string strCert = objCertRequest.GetCertificate(CR_OUT_BASE64); string argsCrt = "tmp.crt"; File.WriteAllText(argsCrt, "-----BEGIN CERTIFICATE-----\n" + strCert + "-----END CERTIFICATE-----\n"); }
public void GenerateCsr(SSLCertificate cert) { // Create all the objects that will be required CX509CertificateRequestPkcs10 pkcs10 = new CX509CertificateRequestPkcs10(); CX509PrivateKey privateKey = new CX509PrivateKey(); CCspInformation csp = new CCspInformation(); CCspInformations csPs = new CCspInformations(); CX500DistinguishedName dn = new CX500DistinguishedName(); CX509Enrollment enroll = new CX509Enrollment(); CObjectIds objectIds = new CObjectIds(); CObjectId clientObjectId = new CObjectId(); CObjectId serverObjectId = new CObjectId(); CX509ExtensionKeyUsage extensionKeyUsage = new CX509ExtensionKeyUsage(); CX509ExtensionEnhancedKeyUsage x509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage(); try { // Initialize the csp object using the desired Cryptograhic Service Provider (CSP) csp.InitializeFromName("Microsoft RSA SChannel Cryptographic Provider"); // Add this CSP object to the CSP collection object csPs.Add(csp); // Provide key container name, key length and key spec to the private key object //objPrivateKey.ContainerName = "AlejaCMa"; privateKey.Length = cert.CSRLength; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.MachineContext = true; // Provide the CSP collection object (in this case containing only 1 CSP object) // to the private key object privateKey.CspInformations = csPs; // Create the actual key pair privateKey.Create(); // Initialize the PKCS#10 certificate request object based on the private key. // Using the context, indicate that this is a user certificate request and don't // provide a template name pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.PrivateKey = privateKey.ToString(); // Key Usage Extension extensionKeyUsage.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 ); pkcs10.X509Extensions.Add((CX509Extension)extensionKeyUsage); // Enhanced Key Usage Extension clientObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.2"); objectIds.Add(clientObjectId); serverObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.1"); objectIds.Add(serverObjectId); x509ExtensionEnhancedKeyUsage.InitializeEncode(objectIds); pkcs10.X509Extensions.Add((CX509Extension)x509ExtensionEnhancedKeyUsage); // Encode the name in using the Distinguished Name object string request = String.Format(@"CN={0}, O={1}, OU={2}, L={3}, S={4}, C={5}", cert.Hostname, cert.Organisation, cert.OrganisationUnit, cert.City, cert.State, cert.Country); dn.Encode(request, X500NameFlags.XCN_CERT_NAME_STR_NONE); // Assing the subject name by using the Distinguished Name object initialized above pkcs10.Subject = dn; // Create enrollment request enroll.InitializeFromRequest(pkcs10); enroll.CertificateFriendlyName = cert.FriendlyName; cert.CSR = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER); } catch (Exception ex) { Log.WriteError("Error creating CSR", ex); } }
public string CreateTemplateRequest(string cn, string ou, string o, string l, string s, string c, int keylength, string template) { var objCSPs = new CCspInformations(); objCSPs.AddAvailableCsps(); var objPrivateKey = new CX509PrivateKey(); objPrivateKey.Length = keylength; objPrivateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; objPrivateKey.MachineContext = false; objPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; objPrivateKey.CspInformations = objCSPs; objPrivateKey.Create(); var objPkcs10 = new CX509CertificateRequestPkcs10(); objPkcs10.InitializeFromPrivateKey( X509CertificateEnrollmentContext.ContextUser, objPrivateKey, template); var objDN = new CX500DistinguishedName(); var subjectName = "CN = " + cn + ",OU = " + ou + ",O = " + o + ",L = " + l + ",S = " + s + ",C = " + c; objDN.Encode(subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); objPkcs10.Subject = objDN; var objEnroll = new CX509Enrollment(); objEnroll.InitializeFromRequest(objPkcs10); var strRequest = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); return strRequest; }
public string CreateRequest() { // Create all the objects that will be required var objPkcs10 = new CX509CertificateRequestPkcs10(); var objPrivKey = new CX509PrivateKey(); var objCSP = new CCspInformation(); var objCSPs = new CCspInformations(); var objDN = new CX500DistinguishedName(); var objEnroll = new CX509Enrollment(); var objObjIds = new CObjectIds(); var objObjId = new CObjectId(); var objExtKeyUsage = new CX509ExtensionKeyUsage(); var objExtEnhKeyUsage = new CX509ExtensionEnhancedKeyUsage(); string strRequest; //objCSP.InitializeFromName(provName); //objCSPs.Add(objCSP); //objPrivKey.Length = 2048; //objPrivKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; //objPrivKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; //objPrivKey.MachineContext = true; //objPrivKey.CspInformations = objCSPs; //objPrivKey.Create(); var strTemplateName = "1.3.6.1.4.1.311.21.8.12017375.10856495.934812.8687423.15807460.10.5731641.6795722"; // RDP All Names objPkcs10.InitializeFromTemplateName(X509CertificateEnrollmentContext.ContextMachine, strTemplateName); // Encode the name in using the DN object objDN.Encode("CN=" + Environment.GetEnvironmentVariable("COMPUTERNAME"), X500NameFlags.XCN_CERT_NAME_STR_NONE); // Adding the subject name by using the DN object initialized above objPkcs10.Subject = objDN; var dnsDom = Environment.GetEnvironmentVariable("USERDNSDOMAIN").ToLower(); var altName = new CAlternativeName(); var objAlternateNames = new CAlternativeNames(); var objExtAltNames = new CX509ExtensionAlternativeNames(); altName.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, Environment.GetEnvironmentVariable("COMPUTERNAME") + "." + dnsDom); var altName2 = new CAlternativeName(); altName2.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, Environment.GetEnvironmentVariable("COMPUTERNAME")); objAlternateNames.Add(altName2); objAlternateNames.Add(altName); objExtAltNames.InitializeEncode(objAlternateNames); objPkcs10.X509Extensions.Add((CX509Extension)objExtAltNames); // Create the enrollment request objEnroll.InitializeFromRequest(objPkcs10); strRequest = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); return(strRequest); }
public Pkcs10CertificateRequest() { Request = new CX509CertificateRequestPkcs10(); }
/// <summary> /// Function used to create a certificate signing request using the OS. /// Note that this function will place a certificate in the "Certificate Enrollment Requests" folder /// of the certificate store specified in loc. You can view this by running either /// certmgr or mmc from the command line. /// </summary> /// <param name="loc">Location to put certificate</param> /// <param name="subject_line">The subject line of the certificate, fields should be ; seperated, i.e.: "C=US; ST=Minnesota; L=Eden Prairie; O=Forward Pay Systems, Inc.; OU=Forward Pay; CN=fps.com"</param> /// <returns>The certificate signing request, if successful in PEM format</returns> public string GenerateRequest() { //code originally came from: http://blogs.msdn.com/b/alejacma/archive/2008/09/05/how-to-create-a-certificate-request-with-certenroll-and-net-c.aspx //modified version of it is here: http://stackoverflow.com/questions/16755634/issue-generating-a-csr-in-windows-vista-cx509certificaterequestpkcs10 //here is the standard for certificates: http://www.ietf.org/rfc/rfc3280.txt //the PKCS#10 certificate request (http://msdn.microsoft.com/en-us/library/windows/desktop/aa377505.aspx) CX509CertificateRequestPkcs10 objPkcs10 = new CX509CertificateRequestPkcs10(); //assymetric private key that can be used for encryption (http://msdn.microsoft.com/en-us/library/windows/desktop/aa378921.aspx) CX509PrivateKey objPrivateKey = new CX509PrivateKey(); //access to the general information about a cryptographic provider (http://msdn.microsoft.com/en-us/library/windows/desktop/aa375967.aspx) CCspInformation objCSP = new CCspInformation(); //collection on cryptographic providers available: http://msdn.microsoft.com/en-us/library/windows/desktop/aa375967(v=vs.85).aspx CCspInformations objCSPs = new CCspInformations(); CX500DistinguishedName objDN = new CX500DistinguishedName(); //top level object that enables installing a certificate response http://msdn.microsoft.com/en-us/library/windows/desktop/aa377809.aspx CX509Enrollment objEnroll = new CX509Enrollment(); CObjectIds objObjectIds = new CObjectIds(); CObjectId objObjectId = new CObjectId(); CObjectId objObjectId2 = new CObjectId(); CX509ExtensionKeyUsage objExtensionKeyUsage = new CX509ExtensionKeyUsage(); CX509ExtensionEnhancedKeyUsage objX509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage(); string csr_pem = null; // Initialize the csp object using the desired Cryptograhic Service Provider (CSP) objCSPs.AddAvailableCsps(); //Provide key container name, key length and key spec to the private key object objPrivateKey.ProviderName = providerName; objPrivateKey.Length = KeyLength; objPrivateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; //Must flag as XCN_AT_KEYEXCHANGE to use this certificate for exchanging symmetric keys (needed for most SSL cipher suites) objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; if (Location == StoreLocation.LocalMachine) { objPrivateKey.MachineContext = true; } else { objPrivateKey.MachineContext = false; //must set this to true if installing to the local machine certificate store } objPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; //must set this if we want to be able to export it later. (for WinSIP maybe we don't want to be able to ever export the key??) objPrivateKey.CspInformations = objCSPs; // Create the actual key pair objPrivateKey.Create(); // Initialize the PKCS#10 certificate request object based on the private key. // Using the context, indicate that this is a user certificate request and don't // provide a template name if (Location == StoreLocation.LocalMachine) { objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, objPrivateKey, ""); } else { objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, objPrivateKey, ""); } //Set has to sha256 CObjectId hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); objPkcs10.HashAlgorithm = hashobj; // Key Usage Extension -- we only need digital signature and key encipherment for TLS: // NOTE: in openSSL, I didn't used to request any specific extensions. Instead, I let the CA add them objExtensionKeyUsage.InitializeEncode( CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE ); objPkcs10.X509Extensions.Add((CX509Extension)objExtensionKeyUsage); // Enhanced Key Usage Extension objObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // OID for Server Authentication usage (see this: http://stackoverflow.com/questions/17477279/client-authentication-1-3-6-1-5-5-7-3-2-oid-in-server-certificates) objObjectId2.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // OID for Client Authentication usage (see this: http://stackoverflow.com/questions/17477279/client-authentication-1-3-6-1-5-5-7-3-2-oid-in-server-certificates) objObjectIds.Add(objObjectId); objObjectIds.Add(objObjectId2); objX509ExtensionEnhancedKeyUsage.InitializeEncode(objObjectIds); objPkcs10.X509Extensions.Add((CX509Extension)objX509ExtensionEnhancedKeyUsage); // Encode the name in using the Distinguished Name object // see here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa379394(v=vs.85).aspx /*objDN.Encode( * "C=US, ST=Minnesota, L=Eden Prairie, O=Forward Pay Systems; Inc., OU=Forward Pay, CN=ERIC_CN", * X500NameFlags.XCN_CERT_NAME_STR_NONE * );*/ objDN.Encode( Subject, X500NameFlags.XCN_CERT_NAME_STR_SEMICOLON_FLAG ); //"C=US; ST=Minnesota; L=Eden Prairie; O=Forward Pay Systems, Inc.; OU=Forward Pay; CN=ERIC_CN" // Assing the subject name by using the Distinguished Name object initialized above objPkcs10.Subject = objDN; //suppress extra attributes: objPkcs10.SuppressDefaults = true; // Create enrollment request objEnroll.InitializeFromRequest(objPkcs10); csr_pem = objEnroll.CreateRequest( EncodingType.XCN_CRYPT_STRING_BASE64 ); csr_pem = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + csr_pem + "-----END CERTIFICATE REQUEST-----"; return(csr_pem); }
private void button1_Click(object sender, EventArgs e) { const int SCEPProcessDefault = 0x0; //const int SCEPProcessSkipCertInstall = 0x1; string protocol; if (checkBox1.Checked) { protocol = "https"; } else { protocol = "http"; } var sConfigString = protocol + "://" + textBox1.Text + "/certsrv/mscep/mscep.dll/pkiclient.exe"; var oCertRequestPkcs10 = new CX509CertificateRequestPkcs10(); oCertRequestPkcs10.Initialize(CERTENROLLLib.X509CertificateEnrollmentContext.ContextUser); var oSubjectDN = new CX500DistinguishedName(); oSubjectDN.Encode(textBox3.Text); oCertRequestPkcs10.Subject = oSubjectDN; oCertRequestPkcs10.PrivateKey.Length = 2048; oCertRequestPkcs10.PrivateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; oCertRequestPkcs10.PrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_SIGNING_FLAG; oCertRequestPkcs10.KeyContainerNamePrefix = "NDESTest"; if (checkBox2.Checked) { oCertRequestPkcs10.ChallengePassword = textBox2.Text; } var oEnrollmentHelper = new CX509SCEPEnrollmentHelper(); try { oEnrollmentHelper.Initialize( sConfigString, "", oCertRequestPkcs10, "" ); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } var iDisposition = oEnrollmentHelper.Enroll(SCEPProcessDefault); switch (iDisposition) { case CERTENROLLLib.X509SCEPDisposition.SCEPDispositionFailure: MessageBox.Show(oEnrollmentHelper.ResultMessageText.ToString()); break; case CERTENROLLLib.X509SCEPDisposition.SCEPDispositionSuccess: string base64 = oEnrollmentHelper.X509SCEPEnrollment.Certificate[EncodingType.XCN_CRYPT_STRING_BASE64]; X509Certificate2 cert = new X509Certificate2(); cert.Import(Convert.FromBase64String(base64)); X509Certificate2UI.DisplayCertificate(cert); break; default: MessageBox.Show("Unknown"); break; } }
private string GetSubjectKeyIdentifier(CX509CertificateRequestPkcs10 crc) { return(crc.PublicKey.ComputeKeyIdentifier(KeyIdentifierHashAlgorithm.SKIHashSha1, EncodingType.XCN_CRYPT_STRING_HEX). Trim().Replace(" ", "").Replace(System.Environment.NewLine, "").Trim()); }
static void Main(string[] args) { if (args.Length != 5) { Console.WriteLine("Usage: Signer.exe [EnrollmentCertificateThumbprint] [BehalfOfUser] [PathToCSR] [OutputFileName] [CertificateTemplate]"); return; } string argsKey = args[0]; string argsUser = args[1]; string argsCsr = args[2]; string argsCrt = args[3]; string argsCrtTmpl = args[4]; string csr = string.Join("\n", File.ReadAllLines(argsCsr).Where(s => s.Length > 0 && !s.StartsWith("--"))); // Create a PKCS 10 inner request. CX509CertificateRequestPkcs10 pkcs10Req = new CX509CertificateRequestPkcs10(); pkcs10Req.InitializeDecode(csr); // Create a CMC outer request and initialize CX509CertificateRequestCmc cmcReq = new CX509CertificateRequestCmc(); cmcReq.InitializeFromInnerRequestTemplateName(pkcs10Req, argsCrtTmpl); cmcReq.RequesterName = argsUser; CSignerCertificate signer = new CSignerCertificate(); signer.Initialize(false, X509PrivateKeyVerify.VerifyNone, (EncodingType)0xc, argsKey); cmcReq.SignerCertificate = signer; // encode the request cmcReq.Encode(); string strRequest = cmcReq.RawData[EncodingType.XCN_CRYPT_STRING_BASE64]; CCertConfig objCertConfig = new CCertConfig(); CCertRequest objCertRequest = new CCertRequest(); // Get CA config from UI string strCAConfig = objCertConfig.GetConfig(CC_UIPICKCONFIG); // Submit the request int iDisposition = objCertRequest.Submit(CR_IN_BASE64 | CR_IN_FORMATANY, strRequest, null, strCAConfig); // Check the submission status if (CR_DISP_ISSUED != iDisposition) // Not enrolled { string strDisposition = objCertRequest.GetDispositionMessage(); if (CR_DISP_UNDER_SUBMISSION == iDisposition) { Console.WriteLine("The submission is pending: " + strDisposition); return; } Console.WriteLine("The submission failed: " + strDisposition); Console.WriteLine("Last status: " + objCertRequest.GetLastStatus()); return; } // Get the certificate string strCert = objCertRequest.GetCertificate(CR_OUT_BASE64); File.WriteAllText(argsCrt, "-----BEGIN CERTIFICATE-----\n" + strCert + "-----END CERTIFICATE-----\n"); }