/// <summary> /// Static Method used to create an LDAP connection object /// </summary> /// <param name="credential">User Credential</param> /// <param name="ldapConfigRepository">Repository of all LDAP configuration</param> /// <returns></returns> public static LdapConnection GetLdapConnection(NetworkCredential credential, ILdapConfigRepository ldapConfigRepository) { var ldapConnection = new LdapConnection(ldapConfigRepository.GetServer()) { AuthType = ldapConfigRepository.GetAuthType() }; ldapConnection.SessionOptions.ProtocolVersion = 3; if (ldapConfigRepository.GetSecureSocketLayerFlag()) ldapConnection.SessionOptions.SecureSocketLayer = true; if (ldapConfigRepository.GetTransportSocketLayerFlag()) ldapConnection.SessionOptions.StartTransportLayerSecurity(null); if (ldapConfigRepository.GetClientCertificateFlag()) { var clientCertificateFile = new X509Certificate(); clientCertificateFile.Import(ldapConfigRepository.GetClientCertificatePath()); ldapConnection.ClientCertificates.Add(clientCertificateFile); ldapConnection.SessionOptions.VerifyServerCertificate += (conn, cert) => true; } return ldapConnection; }
public void EncryptWithCertificateAndSignTest() { String inPdf = SOURCE_FOLDER + "in.pdf"; String outPdf = DEST_FOLDER + "encrypt_cert_signed.pdf"; String tmpPdf = DEST_FOLDER + "encrypt_cert.pdf"; EncryptPdfWithCertificate(inPdf, tmpPdf, SOURCE_FOLDER + "test.cer"); X509Certificate cert = new X509Certificate(); cert.Import(SOURCE_FOLDER + "test.cer"); Pkcs12Store pkstore = new Pkcs12Store(new FileStream(SOURCE_FOLDER + "test.p12", FileMode.Open, FileAccess.Read), "kspass".ToCharArray()); string pkalias = null; foreach (object a in pkstore.Aliases) { pkalias = ((string)a); if (pkstore.IsKeyEntry(pkalias)) { break; } } ICipherParameters certpk = pkstore.GetKey(pkalias).Key; X509Certificate2 signCert = new X509Certificate2(SOURCE_FOLDER + "test.p12", "kspass"); CertSign(signCert, new X509CertificateParser(), outPdf, new PdfReader(tmpPdf, Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert), certpk), "reason", "location"); }
public X509Certificate GetX509() { X509Certificate xc = new X509Certificate(); try { byte[] x509 = Read(); xc.Import(x509, "", X509KeyStorageFlags.DefaultKeySet); } catch { } return xc; }
public static X509Certificate GetRemoteCertificate(Guid remoteGuid) { var remoteCertificateStore = new FileInfo(GetStorePath(remoteGuid)); if (remoteCertificateStore.Exists) { var cert = new X509Certificate(); cert.Import(remoteCertificateStore.FullName); return(new X509Certificate(remoteCertificateStore.FullName, "")); } else { return(null); } }
public static void EncryptPdfWithCertificate(string sourceDocument, string targetDocument, string certPath) { X509Certificate chain = new X509Certificate(); chain.Import(certPath); Org.BouncyCastle.X509.X509Certificate cert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(chain); Org.BouncyCastle.X509.X509Certificate[] certs = new Org.BouncyCastle.X509.X509Certificate[1] { cert }; PdfReader reader = new PdfReader(sourceDocument); PdfStamper st = new PdfStamper(reader, new FileStream(targetDocument, FileMode.Create, FileAccess.Write), '\0', false); int[] x = new int[1]; x[0] = PdfWriter.ALLOW_SCREENREADERS; st.SetEncryption(certs, x, PdfWriter.STANDARD_ENCRYPTION_40); st.Close(); }
public void System_Security_Cryptography_X509Certificates_X509Certificate_Import () { X509Certificate cert = new X509Certificate (); cert.Import (raw_cert); cert.Import (raw_cert, String.Empty, X509KeyStorageFlags.DefaultKeySet); Assert.Throws<MethodAccessException> (delegate { cert.Import (String.Empty); }, "Import(string)"); Assert.Throws<MethodAccessException> (delegate { cert.Import (String.Empty, String.Empty, X509KeyStorageFlags.DefaultKeySet); }, "Import(string,string,X509KeyStorageFlags)"); }
private X509Certificate QueryClientCertificate(LdapConnection connection, byte[][] trustedCAs) { LdapDirectoryIdentifier id = connection.Directory as LdapDirectoryIdentifier; if (IsTrustedContosoCA(trustedCAs)) { X509Certificate cert = new X509Certificate(); cert.Import(GetPath(this.CertificatePath), this.Password, X509KeyStorageFlags.DefaultKeySet); connection.ClientCertificates.Add(cert); return null; } else return null; }
public void Pkcs7_Import () { X509Certificate x = new X509Certificate (); x.Import (farscape_pkcs7); }
public void Empty () { X509Certificate x = new X509Certificate (); Assert.AreEqual ("X509", x.GetFormat (), "GetFormat"); Assert.AreEqual (0, x.GetHashCode (), "GetHashCode"); Assert.AreEqual (IntPtr.Zero, x.Handle, "Handle"); Assert.AreEqual ("System.Security.Cryptography.X509Certificates.X509Certificate", x.ToString (true), "ToString(true)"); Assert.AreEqual ("System.Security.Cryptography.X509Certificates.X509Certificate", x.ToString (false), "ToString(false)"); Assert.IsTrue (x.Equals (x), "Equals(X509Certificate)"); Assert.IsTrue (x.Equals ((object) x), "Equals(object)"); x.Reset (); x.Import (cert1); Assert.AreEqual ("02720006E8", x.GetSerialNumberString (), "GetSerialNumberString"); }
//public static string ResolveRelativePath(string referencePath, string relativePath) //{ // Uri uri = new Uri(Path.Combine(referencePath, relativePath)); // return Path.GetFullPath(uri.AbsolutePath); //} //private static Dictionary<string, string> api_site_tokens = new Dictionary<string, string>(); //private static int logID = -1; public ActiveUser setUser() { Debug.WriteLine("here in CoreApp.setUser"); ActiveUser active_user = new ActiveUser(); HttpClientCertificate cert = Request.ClientCertificate; //start of mikes code String email = null; System.Security.Cryptography.X509Certificates.X509Certificate ucert = new System.Security.Cryptography.X509Certificates.X509Certificate(cert.Certificate); var ucert1 = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(ucert); Regex email_pat = new Regex(@"^.*@*\.mil$", RegexOptions.IgnoreCase); // Search for an email string var subject_alt_names = ucert1.GetSubjectAlternativeNames(); // Get subject alternative names from cert using and store into a collection if (subject_alt_names != null) // if collection is not null { foreach (var k in subject_alt_names) // here is where we hit the root of the collection using object 'k' to iterate through the collection { foreach (var i in (ArrayList)k) // going deeper into the child elements of object k.... typecast to an arraylist { Match m = email_pat.Match(Convert.ToString(i)); // use system api Match and see if what we are looking for is an email..... if (m.Success) { email = Convert.ToString(i); // convert object to string and set email equal to the matched value Debug.WriteLine("Subject Alternative Name email: " + email); break; } } } } //end of mikes code. go down to the return value from here if (cert.IsPresent) { if (Request.RequestContext.HttpContext.Session["ocsp_checked"] == null) { X509Store store = new X509Store(StoreName.Root); store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly); bool ocsp_testing_phase = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["ocsp_testing"]); System.Security.Cryptography.X509Certificates.X509Certificate user_cert; if (ocsp_testing_phase) {// JUST FOR TESTING ArrayList test_users = new ArrayList() { "AnVLAuthUser1.cer", "AnVLAuthUser2.cer", "amrdec_ocsp_test\\david.kalpakchian.ctr_base64.cer", "localhost_cert.cer" }; user_cert = new System.Security.Cryptography.X509Certificates.X509Certificate(); // throw new IOException("HERE - " + HttpContext.Current.Server.MapPath(".") + "\n" + System.IO.Directory.GetCurrentDirectory() + "\n" + Path.GetDirectoryName(HttpContext.Current.Server.MapPath(".")) + "\n" + Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()) + "\n" + ResolveRelativePath(HttpContext.Current.Server.MapPath("."), "..\\App_Data\\" + test_users[0])); // user_cert.Import("..\\App_Data\\" + test_users[0]); user_cert.Import(AppDomain.CurrentDomain.BaseDirectory + "Data\\" + test_users[0]); //ResolveRelativePath(HttpContext.Current.Server.MapPath("."), "..\\Data\\" + test_users[0])); } else { // real cert of user user_cert = new System.Security.Cryptography.X509Certificates.X509Certificate(cert.Certificate); Debug.WriteLine("\n\nUsing real certificate for OCSP! " + user_cert.GetExpirationDateString() + "\n\n"); } var exp_date = DateTime.Parse(user_cert.GetExpirationDateString()); if ((exp_date - DateTime.Now).TotalMilliseconds < 0) { Request.RequestContext.HttpContext.Session["ocsp_cert_good"] = false; active_user.edipi = -1; return(active_user); } string issuer_cn = user_cert.Issuer.ToString().Split(new string[] { "CN=" }, StringSplitOptions.None)[1].Split(',')[0]; var fndCA = store.Certificates.Find(X509FindType.FindBySubjectName, issuer_cn, true); // (ocsp_testing_phase) ? "DOD JITC CA-27" : issuer_cn if (fndCA.Count == 0) { store = new X509Store(StoreName.CertificateAuthority); // intermediate CAs store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly); fndCA = store.Certificates.Find(X509FindType.FindBySubjectName, issuer_cn, true); } if (fndCA.Count == 0) { throw new IOException("Could not find the appropriate issuer certificate!"); } System.Security.Cryptography.X509Certificates.X509Certificate2 rootCA = fndCA[0]; // Debug.WriteLine(rootCA.Subject); bool is_sipr = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["is_sipr"]); bool chk_subject = false; // print diagnostic information to the server log Response.AppendToLog("====**** CERT SUBJECT : " + rootCA.Subject + " ******======"); chk_subject = rootCA.Subject.Contains("OU=" + ((is_sipr) ? "DoD" : "PKI")) && rootCA.Subject.Contains("O=U.S. Government") && rootCA.Subject.Contains("C=US"); if (!chk_subject) { throw new IOException("Could not validate issuing CA!"); } string ocsp_url = (ocsp_testing_phase) ? System.Configuration.ConfigurationManager.AppSettings["ocsp_responder_test_url"].ToString() : System.Configuration.ConfigurationManager.AppSettings["ocsp_responder_url"].ToString(); var OCSPCheck = new OcspClientBouncyCastle(Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(user_cert), Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(rootCA), ocsp_url); bool do_ocsp = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["do_ocsp"]); var ocsp_resp = (do_ocsp) ? OCSPCheck.runAuth() : true; Request.RequestContext.HttpContext.Session["ocsp_cert_good"] = ocsp_resp; Request.RequestContext.HttpContext.Session["ocsp_checked"] = true; } else { if (!Convert.ToBoolean(Request.RequestContext.HttpContext.Session["ocsp_cert_good"])) { active_user.edipi = -1; return(active_user); } } // clear tokens that are stale (>10min) String subjectcn = cert.Get("SUBJECTCN"); string sn = cert.SerialNumber; int edi = Convert.ToInt32(subjectcn.Substring(subjectcn.LastIndexOf(".") + 1)); String name = subjectcn.Substring(0, subjectcn.LastIndexOf(".")); try { Response.AppendToLog("====**** " + edi + " : " + name + " ******======"); } catch (Exception err) { Debug.WriteLine(err.Message); } //string sql_q = "select * from hartselleb.cmdr_user where STATUS = 'A' and edipi =" + edi; //DataSet dsObj = DBUtils.ExecuteSqlQuery(sql_q); //var output = new List<string>(); //if (dsObj != null && dsObj.Tables[0].Rows.Count == 1) //{ // active_user = dsObj.Tables[0].AsEnumerable().Select(r => new ActiveUser // { // edipi = Convert.ToInt32(r["EDIPI"]), // rrc_edipi = Convert.ToInt32(r["RRC_EDIPI"]), // lastName = r["LASTNAME"].ToString(), // firstName = r["FIRSTNAME"].ToString(), // middleInitial = r["MIDDLEINITIAL"].ToString(), // email = r["EMAIL"].ToString(), // rank = r["RANK"].ToString(), // dsn_phone = r["DSN_PHONE"].ToString(), // alt_phone = r["ALT_PHONE"].ToString(), // macom = r["MACOM"].ToString(), // base_location = r["BASE"].ToString(), // state = r["STATE"].ToString(), // country_cd = r["COUNTRY_CD"].ToString(), // status = r["STATUS"].ToString() // }).FirstOrDefault(); //} //else //{ // active_user.edipi = -1; //} } else { active_user.edipi = -2; } //adding code mike showed me here active_user.email = email; //end return(active_user); }