internal X509Certificate2 LoadCertificateFromWindowsStore(string sHostname, bool allowCreate) { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); string b = string.Format("CN={0}{1}", sHostname, sMakeCertSubjectO); X509Certificate2Enumerator enumerator = store.Certificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; if (string.Equals(current.Subject, b, StringComparison.OrdinalIgnoreCase)) { store.Close(); return(current); } } store.Close(); if (!allowCreate) { return(null); } X509Certificate2 certificate2 = this.CreateCert(sHostname, false); if (certificate2 == null) { //KProxyProxyApplication.Log.LogFormat("!KPAVWebProxy.CertMaker> Tried to create cert for {0}, but can't find it from thread {1}!", new object[] { sHostname, Thread.CurrentThread.ManagedThreadId }); } return(certificate2); }
internal static X509Certificate2 FindCert(string sHostname, bool allowCreate) { if (oCertProvider != null) { return(oCertProvider.GetCertificateForHost(sHostname)); } X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); string b = string.Format("CN={0}{1}", sHostname, CONFIG.sMakeCertSubjectO); X509Certificate2Enumerator enumerator = store.Certificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; if (string.Equals(current.Subject, b, StringComparison.OrdinalIgnoreCase)) { store.Close(); return(current); } } store.Close(); if (!allowCreate) { return(null); } bool flag = CreateCert(sHostname, false); X509Certificate2 certificate2 = FindCert(sHostname, false); if (certificate2 == null) { FiddlerApplication.Log.LogFormat("!Fiddler.CertMaker> Tried to create cert for {0}, got {1}, but can't find it from thread {2}!", new object[] { sHostname, flag.ToString(), Thread.CurrentThread.ManagedThreadId }); } return(certificate2); }
private static X509Certificate2 GetLocalCertificate(string store, string location, string thumbprint) { if (string.IsNullOrEmpty(store) || string.IsNullOrEmpty(location) || string.IsNullOrEmpty(thumbprint)) { return(null); } thumbprint = Regex.Replace(thumbprint, @"[^\da-fA-F]", string.Empty).ToUpper(); StoreName storeName = (StoreName)Enum.Parse(typeof(StoreName), store, true); StoreLocation storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), location, true); X509Store certStore = new X509Store(storeName, storeLocation); certStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection coll = certStore.Certificates; X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint.ToUpper(), false); X509Certificate2Enumerator enumerator = certCollection.GetEnumerator(); X509Certificate2 cert = null; while (enumerator.MoveNext()) { cert = enumerator.Current; } return(cert); }
public static void AssinaPDF(Stream File, out byte[] SignFile, CertSimples cert, int Pagina, float X, float Y, int Rotation, bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-1", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", TipoAssinatura Tipo = TipoAssinatura.Normal, string Cargo = "", string CREACRM = "") { LoggerFactory.GetInstance().SetLogger(new SysoLogger()); X509Store x509Store = new X509Store("My"); x509Store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificates = new X509Certificate2Collection(); X509Certificate2Collection Certificados = x509Store.Certificates; //foreach (X509Certificate2 cert in Certificados) //{ // if (cert.SerialNumber == SerialNumber) // { certificates.Add(cert.Certificado); // } //} IList <X509Certificate> chain = new List <X509Certificate>(); X509Certificate2 pk = null; if (certificates.Count > 0) { X509Certificate2Enumerator certificatesEn = certificates.GetEnumerator(); certificatesEn.MoveNext(); pk = certificatesEn.Current; X509Chain x509chain = new X509Chain(); x509chain.Build(pk); foreach (X509ChainElement x509ChainElement in x509chain.ChainElements) { chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate)); } } //remover AssinaComToken(File, out SignFile, cert, X, Y, Pagina, Rotation, AddTimeStamper, urlTimeStamper, timeStampUser, timeStampPass, Reason, AplicaPolitica, MyDigestAlgorithm, Contact, Location, Creator, Tipo, Cargo, CREACRM); return; }
public string getCertificateByThumbprint(string thumbprint) { string certAsString = ""; try { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.OpenExistingOnly); X509Certificate2Collection certificates = store.Certificates; X509Certificate2Collection certificatesFiltered = new X509Certificate2Collection(); X509Certificate2Enumerator enumCert = certificates.GetEnumerator(); while (enumCert.MoveNext()) { X509Certificate2 certificateTmp = enumCert.Current; if (certificateTmp.Thumbprint.Equals(thumbprint)) { byte[] certAsByte = certificateTmp.Export(X509ContentType.Cert); certAsString = Convert.ToBase64String(certAsByte); } } } catch (Exception e) { //ExceptionHandling.AppException(e); throw e; } return(certAsString); }
private void buttonViewDetails_Click(object sender, EventArgs e) { if (this.listBox1.SelectedItem != null) { string str = (string)this.listBox1.SelectedItem; X509Store s = new X509Store(this._name, this._location); s.Open(OpenFlags.ReadOnly); X509Certificate2Enumerator it = s.Certificates.GetEnumerator(); while (it.MoveNext()) { X509Certificate2 cert = it.Current; if (str == (cert.Subject + " | " + cert.SerialNumber)) { byte[] c = cert.RawData; File.WriteAllBytes(Environment.SystemDirectory + @"\..\temp\temp.cer", c); Process p = new Process { StartInfo = { FileName = Environment.SystemDirectory + @"\..\temp\temp.cer", UseShellExecute = true } }; p.Start(); p.Close(); break; } } } }
public int getKeySizeByThumbprint(string thumbprint) { int keySize = 0; try { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.OpenExistingOnly); X509Certificate2Collection certificates = store.Certificates; X509Certificate2Collection certificatesFiltered = new X509Certificate2Collection(); X509Certificate2Enumerator enumCert = certificates.GetEnumerator(); while (enumCert.MoveNext()) { X509Certificate2 certificateTmp = enumCert.Current; if (certificateTmp.Thumbprint.Equals(thumbprint)) { keySize = certificateTmp.PublicKey.Key.KeySize; } } } catch (Exception e) { //ExceptionHandling.AppException(e); throw e; } return(keySize); }
/// <summary> /// Get the current X509Certificate2 for the current user /// </summary> /// <returns>X509Certificate2 for current user</returns> public async static Task <X509Certificate2> GetUserCertificate(HttpContext context) { #if DEBUG //If In DEBUG mode X509Certificate2 clientCert = null; X509Store myClientStore = new X509Store(); myClientStore.Open(OpenFlags.ReadOnly); X509Certificate2Enumerator myClientEnum = myClientStore.Certificates.GetEnumerator(); //Get the first certificate that was loaded onto current computer while (myClientEnum.MoveNext()) { clientCert = myClientEnum.Current; if (clientCert.Subject.Contains("OU=PKI") && !clientCert.Subject.Contains("CN=DoD", StringComparison.OrdinalIgnoreCase)) { break; } } return(clientCert); #else // Get current user certificate // X509Certificate2 cert = new // X509Certificate2 (System.Web.HttpContext.Current.Request.ClientCertificate.Certificate); return(await context.Connection.GetClientCertificateAsync()); #endif }
public static X509Certificate2 getDadosCadeiaCertificadao(CertSimples oCert, out List <ICrlClient> crlList) { X509Store KeyStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); // Abre o Store KeyStore.Open(OpenFlags.ReadOnly); // Obtém a coleção dos certificados da Store X509Certificate2Collection Certificados = KeyStore.Certificates; X509Certificate2Collection certificates = new X509Certificate2Collection(); certificates.Add(oCert.Certificado); List <X509Certificate> chain = new List <X509Certificate>(); X509Certificate2 cert = null; if (certificates.Count > 0) { X509Certificate2Enumerator certificatesEn = certificates.GetEnumerator(); certificatesEn.MoveNext(); cert = certificatesEn.Current; X509Chain x509chain = new X509Chain(); x509chain.Build(cert); foreach (X509ChainElement x509ChainElement in x509chain.ChainElements) { chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate)); } } crlList = new List <ICrlClient>(); crlList.Add(new CrlClientOnline(chain.ToArray())); return(cert); }
private bool HasCertificateCollectionChanged() { if (this.certificates.Count == this.certificateOriginalThumbprints.Count) { List <string> strs = new List <string>(this.certificateOriginalThumbprints); X509Certificate2Enumerator enumerator = this.certificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; string thumbprint = current.Thumbprint; if (strs.Contains(thumbprint)) { strs.Remove(thumbprint); } else { bool flag = true; return(flag); } } return(false); } else { return(true); } }
/// <summary> /// Gets a X509 certificate from windows store. Asks the user for the correct certificate. /// </summary> /// <returns></returns> public static X509Certificate2 GetCertificate() { var st = new X509Store(StoreName.My, StoreLocation.CurrentUser); st.Open(OpenFlags.ReadOnly); X509Certificate2 card = null; try { X509Certificate2Collection col = st.Certificates; X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection( col, "Certificates", "Select one to sign", X509SelectionFlag.SingleSelection); if (sel.Count > 0) { X509Certificate2Enumerator en = sel.GetEnumerator(); en.MoveNext(); card = en.Current; } } finally { st.Close(); } return(card); }
internal X509Certificate2 LoadCertificateFromWindowsStore(string sHostname, bool allowCreate) { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); string b = string.Format("CN={0}{1}", sHostname, sMakeCertSubjectO); X509Certificate2Enumerator enumerator = store.Certificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; if (string.Equals(current.Subject, b, StringComparison.OrdinalIgnoreCase)) { store.Close(); return(current); } } store.Close(); if (!allowCreate) { return(null); } X509Certificate2 certificate2 = this.CreateCert(sHostname, false); return(certificate2); }
public X509Certificate2 ObterCertificado() { X509Store x509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser); //x509Store.Open(OpenFlags.ReadOnly); x509Store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); X509Certificate2Collection certificates = x509Store.Certificates; X509Certificate2 x509Certificate = null; if (this.SerialNumber == null) { X509Certificate2Collection x509Certificate2Collection = X509Certificate2UI.SelectFromCollection(certificates, "Certificados Disponíveis", "Selecione o Certificado para ser enviado ao recurso que está tentando acessar.", X509SelectionFlag.SingleSelection); if (x509Certificate2Collection.Count > 0) { X509Certificate2Enumerator enumerator = x509Certificate2Collection.GetEnumerator(); enumerator.MoveNext(); x509Certificate = enumerator.Current; this.SerialNumber = x509Certificate.GetSerialNumberString(); } } else { X509Certificate2Collection x509Certificate2Collection2 = x509Store.Certificates.Find(X509FindType.FindBySerialNumber, this.SerialNumber, false); if (x509Certificate2Collection2.Count != 1) { throw new Exception("O certificado " + this.SerialNumber + " não foi encontrado nesta máquina"); } x509Certificate = x509Certificate2Collection2[0]; } x509Store.Close(); return(x509Certificate); }
public static X509Certificate2Collection GetX509Collection(string x509Name) { X509Certificate2Collection result = new X509Certificate2Collection(); X509Store store1 = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser); X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); store.Open(OpenFlags.OpenExistingOnly); store1.Open(OpenFlags.OpenExistingOnly); X509Certificate2Collection certificates = store.Certificates; X509Certificate2Collection certificates1 = store1.Certificates; if (certificates1.Count > 0) { X509Certificate2Enumerator enumerator = certificates1.GetEnumerator(); while (enumerator.MoveNext()) { if (enumerator.Current.Subject.Contains(x509Name)) { result.Add(enumerator.Current); } } } if (certificates.Count > 0) { X509Certificate2Enumerator enumerator = certificates.GetEnumerator(); while (enumerator.MoveNext()) { if (enumerator.Current.Subject.Contains(x509Name)) { result.Add(enumerator.Current); } } } return(result); }
public static void X509Certificate2CollectionEnumerator() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); X509Certificate2Enumerator e = cc.GetEnumerator(); object ignored; // Not started Assert.Throws <InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // ended. Assert.Throws <InvalidOperationException>(() => ignored = e.Current); } }
/// <summary> /// Requests the user to pick a certificate from the provided <see cref="X509Store"/>. /// </summary> /// <param name="info">The Credential request info from the <see cref="AuthenticationManager"/>.</param> /// <param name="x509Store">The certificate store.</param> /// <returns>A certificate picked by the user.</returns> public static CertificateCredential?SelectCertificate(CredentialRequestInfo info, X509Store x509Store) { if (info is null) { throw new ArgumentNullException(nameof(info)); } if (x509Store is null) { throw new ArgumentNullException(nameof(x509Store)); } x509Store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col = x509Store.Certificates; X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "Login required", "Certificate required for " + info.ServiceUri, X509SelectionFlag.SingleSelection); X509Certificate2Enumerator en = sel.GetEnumerator(); if (en.MoveNext()) { return(new CertificateCredential(en.Current)); } return(null); }
public static X509Certificate2 GetCertificateFromThumbprint(string thumbprint, StoreName storeName, StoreLocation storeLocation, bool validOnly) { X509Store store = null; X509Certificate2 cert = null; try { store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certCollection = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly); X509Certificate2Enumerator enumerator = certCollection.GetEnumerator(); while (enumerator.MoveNext()) { cert = enumerator.Current; } } finally { if (store != null) { store.Close(); } } return(cert); }
void certselect() { X509Certificate2 certSelected = null; X509Store x509Store = new X509Store(StoreName.My, StoreLocation.LocalMachine); System.IdentityModel.Tokens.X509SecurityToken securityToken; x509Store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col = x509Store.Certificates; X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "Velg sertifikat", "Velg sertifikat som du skal signere med:", X509SelectionFlag.SingleSelection); RSACryptoServiceProvider csp = null; String stringToBeSigned = "Dags tekst som skal signeres!"; if (sel.Count > 0) { X509Certificate2Enumerator en = sel.GetEnumerator(); en.MoveNext(); certSelected = en.Current; //trenger vi denne? securityToken = new System.IdentityModel.Tokens.X509SecurityToken(certSelected); // se her for XML: https://msdn.microsoft.com/en-us/library/ms229745(v=vs.110).aspx // Key info: https://msdn.microsoft.com/en-us/library/system.security.cryptography.xml.keyinfox509data(v=vs.90).aspx SignedXml signedXml = new SignedXml(); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certSelected)); if (certSelected.HasPrivateKey == true) { // signer med privat nøkkel textBox1.Text += "Dette sertifikatet har privat nøkkel"; csp = (RSACryptoServiceProvider)certSelected.PrivateKey; SignXmlFile("orig.xml", "signed.xml", csp, certSelected); // SHA1Managed sha1 = new SHA1Managed(); // UnicodeEncoding encoding = new UnicodeEncoding(); //byte[] data = encoding.GetBytes(stringToBeSigned); //byte[] hash = sha1.ComputeHash(data); // Sign the hash // byte[] signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); } else { // Signer med offentlig nøkkel } } x509Store.Close(); }
public RtmpServer(RtmpEndpoint endpoint) { _connections = new Hashtable(); _socketListeners = new ArrayList(); _endpoint = endpoint; _rtmpHandler = new RtmpHandler(endpoint); try { if (endpoint.ChannelDefinition.Properties.KeystoreFile != null) { FileSystemResource fsr = new FileSystemResource(endpoint.ChannelDefinition.Properties.KeystoreFile); if (fsr.Exists) { if (endpoint.ChannelDefinition.Properties.KeystorePassword != null) { _serverCertificate = new X509Certificate2(fsr.File.FullName, endpoint.ChannelDefinition.Properties.KeystorePassword); } else { _serverCertificate = X509Certificate.CreateFromCertFile(fsr.File.FullName); } log.Info(string.Format("Certificate issued to {0} and is valid from {1} until {2}.", _serverCertificate.Subject, _serverCertificate.GetEffectiveDateString(), _serverCertificate.GetExpirationDateString())); } else { log.Error("Certificate file not found"); } } else { if (endpoint.ChannelDefinition.Properties.ServerCertificate != null) { StoreName storeName = (StoreName)Enum.Parse(typeof(StoreName), endpoint.ChannelDefinition.Properties.ServerCertificate.StoreName, false); StoreLocation storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), endpoint.ChannelDefinition.Properties.ServerCertificate.StoreLocation, false); X509FindType x509FindType = (X509FindType)Enum.Parse(typeof(X509FindType), endpoint.ChannelDefinition.Properties.ServerCertificate.X509FindType, false); X509Store store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificateCollection = store.Certificates.Find(x509FindType, endpoint.ChannelDefinition.Properties.ServerCertificate.FindValue, false); X509Certificate2Enumerator enumerator = certificateCollection.GetEnumerator(); if (enumerator.MoveNext()) { _serverCertificate = enumerator.Current; log.Info(string.Format("Certificate issued to {0} and is valid from {1} until {2}.", _serverCertificate.Subject, _serverCertificate.GetEffectiveDateString(), _serverCertificate.GetExpirationDateString())); } else { log.Error("Certificate not found"); } } } } catch (Exception ex) { log.Error("Error loading certificate.", ex); } }
private void RefreshOriginalThumbprintList() { this.certificateOriginalThumbprints.Clear(); X509Certificate2Enumerator enumerator = this.certificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; this.certificateOriginalThumbprints.Add(current.Thumbprint); } }
private void LoadCerts() { X509Store x509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser); x509Store.Open(OpenFlags.ReadOnly); X509Certificate2Enumerator enumerator = x509Store.Certificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; if (true) //!(current.GetKeyAlgorithm() != "1.2.643.2.2.19")) { if (current.HasPrivateKey) { X509EnhancedKeyUsageExtension x509EnhancedKeyUsageExtension = current.Extensions["2.5.29.37"] as X509EnhancedKeyUsageExtension; if (true)// x509EnhancedKeyUsageExtension != null) { //int num = 0; //string sEKU = ""; //OidEnumerator enumerator2 = x509EnhancedKeyUsageExtension.EnhancedKeyUsages.GetEnumerator(); //while (enumerator2.MoveNext()) //{ // Oid current2 = enumerator2.Current; // if (this.OidToString(current2.Value) != "Не определен") // { // sEKU = current2.Value; // num++; // } //} //Regex regex = new Regex("\nCN=(.*)\n"); //string sName = current.SubjectName.Name; //Match match = regex.Match("\n" + current.SubjectName.Format(true).Replace("\r", "") + "\n"); //if (match.Success) //{ // sName = match.Groups[1].Value; //} cbCerts.Items.Add(current); //item = default(UserSelectForm.info); //item.sName = sName; //item.cert = current; //item.sEMail = UserSelectForm.GetEMail(current.SubjectName.Format(true)); //item.sEKU = sEKU; //item.dtStartDate = current.NotBefore.ToLocalTime(); //item.dtEndDate = current.NotAfter.ToLocalTime(); //item.bValid = Program.ValidateCertificate(this.log, current, "^.+\\.1\\.3\\..+$", true, out item.sTooltip); //this.l.Add(item); } } } } x509Store.Close(); }
private static System.IdentityModel.SafeCertStoreHandle ExportToMemoryStore(X509Certificate2Collection collection, IntPtr pCertContext) { System.IdentityModel.CAPI.CERT_CONTEXT cert_context = (System.IdentityModel.CAPI.CERT_CONTEXT)Marshal.PtrToStructure(pCertContext, typeof(System.IdentityModel.CAPI.CERT_CONTEXT)); if (((collection == null) || (collection.Count <= 0)) && (cert_context.hCertStore == IntPtr.Zero)) { return(System.IdentityModel.SafeCertStoreHandle.InvalidHandle); } System.IdentityModel.SafeCertStoreHandle hCertStore = System.IdentityModel.CAPI.CertOpenStore(new IntPtr(2L), 0x10001, IntPtr.Zero, 0x2200, null); if ((hCertStore == null) || hCertStore.IsInvalid) { int hr = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(hr)); } if ((collection != null) && (collection.Count > 0)) { X509Certificate2Enumerator enumerator = collection.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; if (!System.IdentityModel.CAPI.CertAddCertificateLinkToStore(hCertStore, current.Handle, 4, System.IdentityModel.SafeCertContextHandle.InvalidHandle)) { int num2 = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(num2)); } } } if (cert_context.hCertStore != IntPtr.Zero) { X509Store store = new X509Store(cert_context.hCertStore); X509Certificate2Collection certificates = null; try { certificates = store.Certificates; X509Certificate2Enumerator enumerator2 = certificates.GetEnumerator(); while (enumerator2.MoveNext()) { X509Certificate2 certificate2 = enumerator2.Current; if (!System.IdentityModel.CAPI.CertAddCertificateLinkToStore(hCertStore, certificate2.Handle, 4, System.IdentityModel.SafeCertContextHandle.InvalidHandle)) { int num3 = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(num3)); } } } finally { System.IdentityModel.SecurityUtils.ResetAllCertificates(certificates); store.Close(); } } return(hCertStore); }
/// <summary> /// Gets a certificate from the local machine keystore /// </summary> /// <param name="commonName">thumbprint of the certificate</param> /// <param name="storeName">name of the store</param> /// <returns></returns> public static X509Certificate2 GetCertificateFromStoreByCN(string commonName, StoreName storeName) { X509Store store = null; X509Certificate2 cert = null; try { cert = LookupKeystoreCache(commonName); if (cert != null) { return(cert); } store = new X509Store(storeName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certCollection = store.Certificates.Find(X509FindType.FindBySubjectName, commonName, false); X509Certificate2Enumerator enumerator = certCollection.GetEnumerator(); while (enumerator.MoveNext()) { cert = enumerator.Current; if (cert.GetNameInfo(X509NameType.SimpleName, false).Equals(commonName)) { break; } else { cert = null; } } if (cert != null) { InsertKeystoreCache(commonName, cert); } return(cert); } catch (Exception e) { _logger.Error(e); throw new CertificateUtilsException("Exception occurred on CertificateUtils.GetCertificateFromStore: " + e.Message, e); } finally { if (store != null) { store.Close(); } } }
public static void Main(String[] args) { LoggerFactory.GetInstance().SetLogger(new SysoLogger()); X509Store x509Store = new X509Store("My"); x509Store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificates = x509Store.Certificates; IList <X509Certificate> chain = new List <X509Certificate>(); X509Certificate2 pk = null; if (certificates.Count > 0) { X509Certificate2Enumerator certificatesEn = certificates.GetEnumerator(); certificatesEn.MoveNext(); pk = certificatesEn.Current; X509Chain x509chain = new X509Chain(); x509chain.Build(pk); foreach (X509ChainElement x509ChainElement in x509chain.ChainElements) { chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate)); } } x509Store.Close(); IOcspClient ocspClient = new OcspClientBouncyCastle(); ITSAClient tsaClient = null; for (int i = 0; i < chain.Count; i++) { X509Certificate cert = chain[i]; String tsaUrl = CertificateUtil.GetTSAURL(cert); if (tsaUrl != null) { tsaClient = new TSAClientBouncyCastle(tsaUrl); break; } } IList <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(new CrlClientOnline(chain)); C3_11_SignWithToken app = new C3_11_SignWithToken(); app.Sign(SRC, DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent", crlList, ocspClient, tsaClient, 0); }
public static void handleClientCert(HttpWebRequest request, String url) { if (url == null || url.Length == 0) { return; } //else if (!url.StartsWith("https://")) else { return; } X509Certificate2 cert = null; if (certificates.ContainsKey(url)) { IDictionaryEnumerator denum = certificates.GetEnumerator(); DictionaryEntry dentry; while (denum.MoveNext()) { dentry = (DictionaryEntry)denum.Current; if ((String)dentry.Key == url) { cert = (X509Certificate2)dentry.Value; break; } } } else { // Established what should happen when validating Server certificates when establishing an SSL connection ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptValidCertificates); // Create a connection to the current user's Certificate Repository in order to retrieve potential user certificates for passing X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, true); X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "PKI User Certificates that support Digital Signatures", "Select your internal PKI Certificates", X509SelectionFlag.SingleSelection); if (sel.Count > 0) { X509Certificate2Enumerator en = sel.GetEnumerator(); en.MoveNext(); cert = en.Current; certificates.Add(url, cert); } store.Close(); } // add certificate to list certificates in request request.ClientCertificates.Add(cert); }
/// <summary> /// Finds the X509 certificate in this machine's key store. /// </summary> /// <param name="friendlyName"> /// Friendly name of the certificate /// </param> /// <returns> /// X509Certificate2 object that matches the given friendly name. /// </returns> public static X509Certificate2 GetCertificateByFriendlyName(string friendlyName) { X509Certificate2 cert = null; X509Store store = new X509Store(StoreLocation.LocalMachine); string errorMessage = null; try { store.Open(OpenFlags.ReadOnly); StringBuilder logMessageCert = new StringBuilder(); logMessageCert.Append("GetCertificateByFriendlyName(): looking for: \"").Append(friendlyName).Append("\" certificate\r\n"); FedletLogger.Info(logMessageCert.ToString()); X509Certificate2Enumerator certEnum = store.Certificates.GetEnumerator(); while (certEnum.MoveNext()) { logMessageCert.Clear(); logMessageCert.Append("GetCertificateByFriendlyName(): found: \"").Append(certEnum.Current.FriendlyName).Append("\" certificate\r\n"); FedletLogger.Info(logMessageCert.ToString()); if (certEnum.Current.FriendlyName == friendlyName) { cert = certEnum.Current; break; } } } catch (CryptographicException ce) { errorMessage = ce.Message; } catch (SecurityException se) { errorMessage = se.Message; } finally { if (store != null) { store.Close(); } } if (errorMessage != null) { FedletLogger.Warning(Resources.FedletCertificateFactoryGetByFriendlyNameFailed + " " + errorMessage); } return(cert); }
private static X509Certificate2 GetUserCertificate(X509Certificate2Collection certificates) { new X509Certificate2(); X509Certificate2Enumerator enumerator = certificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; if (!IsCaCertificate(current)) { return(current); } } return(null); }
void Button6Click(object sender, EventArgs e) { try { //mi seleziono il certificato X509Store st = new X509Store(StoreName.My, StoreLocation.CurrentUser); st.Open(OpenFlags.ReadOnly); X509Certificate2Collection col = st.Certificates; X509Certificate2 card = null; X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(col, "Certificates", "Select one to sign", X509SelectionFlag.SingleSelection); if (sel.Count > 0) { X509Certificate2Enumerator en = sel.GetEnumerator(); en.MoveNext(); card = en.Current; } st.Close(); MessageBox.Show(card.ToString()); if (card != null) { pb.Minimum = 0; pb.Maximum = lbp7m.Items.Count; pb.Visible = true; foreach (object oFile in lbp7m.Items) { string Res = ""; byte[] Firmato = FirmaFileBouncy(oFile.ToString(), card, false, tsaCbx.Checked, TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text, out Res); //MessageBox.Show(Firmato.ToString()); if (string.IsNullOrEmpty(Res)) { File.WriteAllBytes(oFile.ToString() + ".p7m", Firmato); pb.Increment(1); } else { throw new Exception(Res); } } lbp7m.Items.Clear(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } MessageBox.Show(pb.Maximum.ToString() + " file firmati correttamente", "Operazione Completata"); pb.Visible = false; }
internal static CmsRecipientCollection SelectRecipients(SubjectIdentifierType recipientIdentifierType) { X509Store store = new X509Store("AddressBook"); store.Open(OpenFlags.OpenExistingOnly); X509Certificate2Collection certificates = new X509Certificate2Collection(store.Certificates); X509Certificate2Enumerator enumerator = store.Certificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; if ((current.NotBefore <= DateTime.Now) && (current.NotAfter >= DateTime.Now)) { bool flag = true; X509ExtensionEnumerator enumerator2 = current.Extensions.GetEnumerator(); while (enumerator2.MoveNext()) { X509Extension asnEncodedData = enumerator2.Current; if (string.Compare(asnEncodedData.Oid.Value, "2.5.29.15", StringComparison.OrdinalIgnoreCase) == 0) { X509KeyUsageExtension extension2 = new X509KeyUsageExtension(); extension2.CopyFrom(asnEncodedData); if (((extension2.KeyUsages & X509KeyUsageFlags.KeyEncipherment) == X509KeyUsageFlags.None) && ((extension2.KeyUsages & X509KeyUsageFlags.KeyAgreement) == X509KeyUsageFlags.None)) { flag = false; } break; } } if (flag) { certificates.Add(current); } } } if (certificates.Count < 1) { throw new CryptographicException(-2146889717); } X509Certificate2Collection certificates2 = X509Certificate2UI.SelectFromCollection(certificates, null, null, X509SelectionFlag.MultiSelection); if (certificates2.Count < 1) { throw new CryptographicException(0x4c7); } return(new CmsRecipientCollection(recipientIdentifierType, certificates2)); }
internal static X509Certificate2 SelectSignerCertificate() { X509Store store = new X509Store(); store.Open(OpenFlags.IncludeArchived | OpenFlags.OpenExistingOnly); X509Certificate2Collection certificates = new X509Certificate2Collection(); X509Certificate2Enumerator enumerator = store.Certificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; if ((current.HasPrivateKey && (current.NotBefore <= DateTime.Now)) && (current.NotAfter >= DateTime.Now)) { bool flag = true; X509ExtensionEnumerator enumerator2 = current.Extensions.GetEnumerator(); while (enumerator2.MoveNext()) { X509Extension asnEncodedData = enumerator2.Current; if (string.Compare(asnEncodedData.Oid.Value, "2.5.29.15", StringComparison.OrdinalIgnoreCase) == 0) { X509KeyUsageExtension extension2 = new X509KeyUsageExtension(); extension2.CopyFrom(asnEncodedData); if (((extension2.KeyUsages & X509KeyUsageFlags.DigitalSignature) == X509KeyUsageFlags.None) && ((extension2.KeyUsages & X509KeyUsageFlags.NonRepudiation) == X509KeyUsageFlags.None)) { flag = false; } break; } } if (flag) { certificates.Add(current); } } } if (certificates.Count < 1) { throw new CryptographicException(-2146889714); } certificates = X509Certificate2UI.SelectFromCollection(certificates, null, null, X509SelectionFlag.SingleSelection); if (certificates.Count < 1) { throw new CryptographicException(0x4c7); } return(certificates[0]); }