public static void Rc4AndCngWrappersDontMixTest() { // // Combination of RC4 over a CAPI certificate. // // This works as long as the PKCS implementation opens the cert using CAPI. If he creates a CNG wrapper handle (by passing CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG), // the test fails with a NOTSUPPORTED crypto exception inside Decrypt(). The same happens if the key is genuinely CNG. // byte[] content = { 6, 3, 128, 33, 44 }; AlgorithmIdentifier rc4 = new AlgorithmIdentifier(new Oid(Oids.Rc4)); EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), rc4); CmsRecipientCollection recipients = new CmsRecipientCollection(new CmsRecipient(Certificates.RSAKeyTransferCapi1.GetCertificate())); ecms.Encrypt(recipients); byte[] encodedMessage = ecms.Encode(); ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { if (cert == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. X509Certificate2Collection extraStore = new X509Certificate2Collection(); extraStore.Add(cert); ecms.Decrypt(extraStore); } ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(content, contentInfo.Content); }
/// <summary> /// Initialisiert eine neue Instanz der <see cref="ReceiverCertificates"/> Klasse. /// </summary> /// <param name="certificates">Die Empfänger-Zertifikate</param> public ReceiverCertificates(IReadOnlyCollection<X509Certificate2> certificates) { var receiverCertificates = new Dictionary<string, X509Certificate2>(); var rootCertificates = new List<X509Certificate2>(); var intermediateCertificates = new X509Certificate2Collection(); foreach (var certificate in certificates) { var key = GetKey(certificate); if (key == null) { if (certificate.SubjectName.Name == certificate.IssuerName.Name) { rootCertificates.Add(certificate); } else { intermediateCertificates.Add(certificate); } } else { receiverCertificates.Add(key, certificate); } } _rootCertificates = rootCertificates.ToArray(); _intermediateCertificates = intermediateCertificates; Certificates = receiverCertificates; }
void VerifyIsOrgCert(X509Certificate2Collection matches, string org) { foreach (X509Certificate2 cert in matches) { Assert.True(cert.MatchEmailNameOrName(org)); } }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("ERROR! Missing parameter"); Console.WriteLine("syntax: certlimit.exe <cert-file.pfx> <password>"); Environment.Exit(1); } int day_threshold = 30; string password = args[1]; // System.Environment.GetEnvironmentVariable("signtoolpassword"); string certfile = args[0]; X509Certificate2Collection coll = new X509Certificate2Collection(); coll.Import(certfile, password, X509KeyStorageFlags.PersistKeySet); foreach (X509Certificate2 cert in coll) { Console.WriteLine("Subject: {0}", cert.Subject); Console.WriteLine("Issuer: {0}", cert.Issuer); if (cert.Subject.ToString().Contains("Rackspace")) { Console.WriteLine("Effective: {0}", cert.GetEffectiveDateString()); Console.WriteLine("Expiration: {0}", cert.GetExpirationDateString()); Console.WriteLine("Serial #: {0}", cert.SerialNumber.ToLower()); int days_to_expiration = (int)((Convert.ToDateTime(cert.GetExpirationDateString()) - DateTime.Now).TotalDays); Console.WriteLine("Days to expiration: {0}", days_to_expiration); if (days_to_expiration < day_threshold) { Console.WriteLine("ERROR! Code signing cert expires in fewer than {0} days", day_threshold); Environment.Exit(1); } } } }
public override void OnHttpRequest(IYandexApiClient client, HttpWebRequest request) { if (_certificates == null) { lock (_syncLock) { if (_certificates == null) { X509Store store = new X509Store(); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); try { _certificates = store.Certificates.Find(X509FindType.FindByIssuerDistinguishedName, YandexIssuerName, false); } finally { store.Close(); } } } } request.ClientCertificates = _certificates; }
private static SafeCertStoreHandle ConvertExtraStoreToSafeHandle(X509Certificate2Collection extraStore) { if (extraStore == null || extraStore.Count == 0) return SafeCertStoreHandle.InvalidHandle; return ((StorePal)StorePal.LinkFromCertificateCollection(extraStore)).SafeCertStoreHandle; }
public static void ImportEdgeCase() { // // Pfx's imported into a certificate collection propagate their "delete on Dispose" behavior to its cloned instances: // a subtle difference from Pfx's created using the X509Certificate2 constructor that can lead to premature or // double key deletion. Since EnvelopeCms.Decrypt() has no legitimate reason to clone the extraStore certs, this shouldn't // be a problem, but this test will verify that it isn't. // byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport()) { X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); byte[] expectedContent = { 1, 2, 3 }; ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(expectedContent, contentInfo.Content); } }
public void AddRange(X509Certificate2Collection certificates) { if (certificates == null) { throw new ArgumentNullException("certificates"); } int num = 0; try { X509Certificate2Enumerator enumerator = certificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; this.Add(current); num++; } } catch { for (int i = 0; i < num; i++) { this.Remove(certificates[i]); } throw; } }
public CmsSigner (SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate) { switch (signerIdentifierType) { case SubjectIdentifierType.Unknown: this.SignerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber; this.IncludeOption = X509IncludeOption.ExcludeRoot; break; case SubjectIdentifierType.IssuerAndSerialNumber: this.SignerIdentifierType = signerIdentifierType; this.IncludeOption = X509IncludeOption.ExcludeRoot; break; case SubjectIdentifierType.SubjectKeyIdentifier: this.SignerIdentifierType = signerIdentifierType; this.IncludeOption = X509IncludeOption.ExcludeRoot; break; case SubjectIdentifierType.NoSignature: this.SignerIdentifierType = signerIdentifierType; this.IncludeOption = X509IncludeOption.None; break; default: this.SignerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber; this.IncludeOption = X509IncludeOption.ExcludeRoot; break; } this.Certificate = certificate; this.DigestAlgorithm = Oid.FromOidValue(CAPI.szOID_OIWSEC_sha1, OidGroup.HashAlgorithm); m_signedAttributes = new CryptographicAttributeObjectCollection(); m_unsignedAttributes = new CryptographicAttributeObjectCollection(); m_certificates = new X509Certificate2Collection(); }
public CertificateStore() { IntermediateCertList = new X509Certificate2Collection(); RootCertList = new X509Certificate2Collection(); AuthRootCertList = new X509Certificate2Collection(); LoadStore(); }
private static System.Security.Cryptography.SafeCertStoreHandle BuildDecryptorStore(X509Certificate2Collection extraStore) { X509Certificate2Collection collection = new X509Certificate2Collection(); try { X509Store store = new X509Store("MY", StoreLocation.CurrentUser); store.Open(OpenFlags.IncludeArchived | OpenFlags.OpenExistingOnly); collection.AddRange(store.Certificates); } catch (SecurityException) { } try { X509Store store2 = new X509Store("MY", StoreLocation.LocalMachine); store2.Open(OpenFlags.IncludeArchived | OpenFlags.OpenExistingOnly); collection.AddRange(store2.Certificates); } catch (SecurityException) { } if (extraStore != null) { collection.AddRange(extraStore); } if (collection.Count == 0) { throw new CryptographicException(-2146889717); } return System.Security.Cryptography.X509Certificates.X509Utils.ExportToMemoryStore(collection); }
public void Connect() { this.tcpClient = new TcpClient(this.host, this.port); this.sslStream = new SslStream( this.tcpClient.GetStream(), false, ValidateServerCertificate, null); var certificatesCollection = new X509Certificate2Collection(this.certificate); try { this.sslStream.AuthenticateAsClient(this.host, certificatesCollection, SslProtocols.Tls, false); } catch (AuthenticationException ex) { throw new NotificationException("Failed to authenticate", ex); } if (!this.sslStream.IsMutuallyAuthenticated) { throw new NotificationException("Failed to authenticate"); } }
public CmsRecipientCollection (SubjectIdentifierType recipientIdentifierType, X509Certificate2Collection certificates) : base () { foreach (X509Certificate2 x509 in certificates) { CmsRecipient p7r = new CmsRecipient (recipientIdentifierType, x509); _list.Add (p7r); } }
public void Execute(object parameter) { var pfx = CertificateManager.GeneratePfx(CertificateName, CertificatePassword); var certificate = CertificateManager.GetCertificateForBytes(pfx.GetBytes(), CertificatePassword); File.WriteAllBytes(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx"), pfx.GetBytes()); File.WriteAllBytes(Path.Combine(AppHelper.CachePath, "AzureAutomation.cer"), certificate); var collection = new X509Certificate2Collection(); collection.Import(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx"), CertificatePassword, X509KeyStorageFlags.PersistKeySet); var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); // Store the certificate foreach (var cert in collection) store.Add(cert); store.Close(); // Delete the certificate that contains the private key - this is already imported into the cert store File.Delete(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx")); MessageBox.Show("The certificate has been generated. Please refresh the certificates list.", "Certificate", MessageBoxButton.OK); // Open the folder containing the certificate Process.Start("explorer.exe", AppHelper.CachePath); }
internal static X509Certificate2Collection GetRemoteCertificatesFromStoreContext(SafeFreeCertContext certContext) { X509Certificate2Collection result = new X509Certificate2Collection(); if (certContext.IsInvalid) { return result; } Interop.Crypt32.CERT_CONTEXT context = Marshal.PtrToStructure<Interop.Crypt32.CERT_CONTEXT>(certContext.DangerousGetHandle()); if (context.hCertStore != IntPtr.Zero) { X509Store store = null; try { store = X509StoreExtensions.CreateFromNativeHandle(context.hCertStore); result = store.Certificates; } finally { if (store != null) { store.Dispose(); } } } return result; }
public void CloneTo(X509Certificate2Collection collection) { Debug.Assert(collection != null); if (!Directory.Exists(_storePath)) { return; } var loadedCerts = new HashSet<X509Certificate2>(); foreach (string filePath in Directory.EnumerateFiles(_storePath, PfxWildcard)) { try { var cert = new X509Certificate2(filePath); // If we haven't already loaded a cert .Equal to this one, copy it to the collection. if (loadedCerts.Add(cert)) { collection.Add(cert); } else { cert.Dispose(); } } catch (CryptographicException) { // The file wasn't a certificate, move on to the next one. } } }
/// <summary> /// Initializes a new instance of the <see cref="X509Certificate2Collection"/> class. /// </summary> /// <param name="collection"> /// The collection of certificates. /// </param> public void Initialize(X509Certificate2Collection collection) { foreach (var certificate in collection) { this.List.Add(certificate); } }
public sealed override byte[] Encrypt(CmsRecipientCollection recipients, ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes) { using (SafeCryptMsgHandle hCryptMsg = EncodeHelpers.CreateCryptMsgHandleToEncode(recipients, contentInfo.ContentType, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes)) { byte[] encodedContent; if (contentInfo.ContentType.Value.Equals(Oids.Pkcs7Data, StringComparison.OrdinalIgnoreCase)) { unsafe { byte[] content = contentInfo.Content; fixed (byte* pContent = content) { DATA_BLOB blob = new DATA_BLOB((IntPtr)pContent, (uint)(content.Length)); encodedContent = Interop.Crypt32.CryptEncodeObjectToByteArray(CryptDecodeObjectStructType.X509_OCTET_STRING, &blob); } } } else { encodedContent = contentInfo.Content; } if (encodedContent.Length > 0) { if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, encodedContent, encodedContent.Length, fFinal: true)) throw Marshal.GetLastWin32Error().ToCryptographicException(); } byte[] encodedMessage = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CONTENT_PARAM); return encodedMessage; } }
public void MoveTo(X509Certificate2Collection collection) { CopyTo(collection); // ILoaderPal expects to only be called once. Dispose(); }
internal static X509Certificate2Collection CreateBagOfCertificates(CmsSigner signer) { X509Certificate2Collection certificates = new X509Certificate2Collection(); certificates.AddRange(signer.Certificates); if (signer.IncludeOption != X509IncludeOption.None) { if (signer.IncludeOption == X509IncludeOption.EndCertOnly) { certificates.Add(signer.Certificate); return certificates; } int count = 1; X509Chain chain = new X509Chain(); chain.Build(signer.Certificate); if ((chain.ChainStatus.Length > 0) && ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain)) { throw new CryptographicException(-2146762486); } if (signer.IncludeOption == X509IncludeOption.WholeChain) { count = chain.ChainElements.Count; } else if (chain.ChainElements.Count > 1) { count = chain.ChainElements.Count - 1; } for (int i = 0; i < count; i++) { certificates.Add(chain.ChainElements[i].Certificate); } } return certificates; }
public CmsSigner(SubjectIdentifierType signerIdentifierType, X509Certificate2 certificate) { switch (signerIdentifierType) { case SubjectIdentifierType.Unknown: this.SignerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber; this.IncludeOption = X509IncludeOption.ExcludeRoot; break; case SubjectIdentifierType.IssuerAndSerialNumber: this.SignerIdentifierType = signerIdentifierType; this.IncludeOption = X509IncludeOption.ExcludeRoot; break; case SubjectIdentifierType.SubjectKeyIdentifier: this.SignerIdentifierType = signerIdentifierType; this.IncludeOption = X509IncludeOption.ExcludeRoot; break; case SubjectIdentifierType.NoSignature: this.SignerIdentifierType = signerIdentifierType; this.IncludeOption = X509IncludeOption.None; break; default: this.SignerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber; this.IncludeOption = X509IncludeOption.ExcludeRoot; break; } this.Certificate = certificate; this.DigestAlgorithm = new Oid("1.3.14.3.2.26"); this.m_signedAttributes = new CryptographicAttributeObjectCollection(); this.m_unsignedAttributes = new CryptographicAttributeObjectCollection(); this.m_certificates = new X509Certificate2Collection(); }
X509Certificate2 FindCertificateByCommonName(X509Certificate2Collection collection, X509Certificate2 find) { var str = GetCommonName(find); return (from X509Certificate2 cert in collection where GetCommonName(cert) == str select cert).FirstOrDefault(); }
public static X509Certificate2 PickCertificate() { var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); var collection = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, false); var gostOnlyCollection = new X509Certificate2Collection(); foreach ( var cert in collection.Cast<X509Certificate2>() .Where(cert => cert.SignatureAlgorithm.Value.Equals("1.2.643.2.2.3"))) gostOnlyCollection.Add(cert); if (gostOnlyCollection.Count == 0) throw new ApplicationException("Не найдено ни одной подписи соответствующей ГОСТ Р 34.11/34.10-2001. \n"); var found = X509Certificate2UI.SelectFromCollection( gostOnlyCollection, "Выберите сертификат", "Выбранная ЭЦП будет использована при подписании файла, и является эквивалентом собственноручной подписи либо печати организации", X509SelectionFlag.SingleSelection ); if (found.Count == 0) { throw new ApplicationException("Сертификат не выбран.\n"); } if (found.Count > 1) { throw new ApplicationException("Найдено больше одного сертификата.\n"); } return found[0]; }
internal static bool TrustEvaluateSsl (X509Certificate2Collection collection, object sender, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors errors) { var certsRawData = new List <byte[]> (collection.Count); foreach (var cert in collection) certsRawData.Add (cert.RawData); return trustEvaluateSsl (certsRawData); }
internal static bool VerifyWithExtraRoots( this X509Chain chain, X509Certificate certificate, X509Certificate2Collection extraRoots) { chain.ChainPolicy.ExtraStore.AddRange(extraRoots); if (chain.Build(new X509Certificate2(certificate))) return true; else { // .NET returns UntrustedRoot status flag if the certificate is not in // the SYSTEM trust store. Check if it's the only problem with the chain. var onlySystemUntrusted = chain.ChainStatus.Length == 1 && chain.ChainStatus[0].Status == X509ChainStatusFlags.UntrustedRoot; // Sanity check that indeed that is the only problem with the root // certificate. var rootCert = chain.ChainElements[chain.ChainElements.Count - 1]; var rootOnlySystemUntrusted = rootCert.ChainElementStatus.Length == 1 && rootCert.ChainElementStatus[0].Status == X509ChainStatusFlags.UntrustedRoot; // Double check it's indeed one of the extra roots we've been given. var rootIsUserTrusted = extraRoots.Contains(rootCert.Certificate); return onlySystemUntrusted && rootOnlySystemUntrusted && rootIsUserTrusted; } }
public void testSignSimpleECDsa() { string testFileName = @"..\..\..\resources\circles.pdf"; string storePath = @"..\..\..\..\simple\keystore\test1234.p12"; string storePass = "******"; string storeAlias = "ECDSAkey"; SystemCertificates.X509Certificate2Collection pkcs12 = new SystemCertificates.X509Certificate2Collection(); pkcs12.Import(storePath, storePass, SystemCertificates.X509KeyStorageFlags.DefaultKeySet); SystemCertificates.X509Certificate2 certificate = null; foreach (SystemCertificates.X509Certificate2 aCertificate in pkcs12) { if (storeAlias.Equals(aCertificate.FriendlyName, StringComparison.InvariantCultureIgnoreCase)) { certificate = aCertificate; break; } } Assert.NotNull(certificate, "Key with alias {0} not found.", storeAlias); X509Certificate bcCertificate = new X509Certificate(X509CertificateStructure.GetInstance(certificate.RawData)); X509Certificate[] chain = { bcCertificate }; X509Certificate2Signature signature = new X509Certificate2Signature(certificate, "SHA512"); using (PdfReader pdfReader = new PdfReader(testFileName)) using (FileStream result = File.Create("circles-ECDSA-signed-simple.pdf")) { PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode()); ITSAClient tsaClient = null; pdfSigner.SignDetached(signature, chain, null, null, tsaClient, 0, PdfSigner.CryptoStandard.CMS); } }
public void testSignSimpleContainerECDsa() { string testFileName = @"..\..\..\resources\circles.pdf"; string storePath = @"..\..\..\..\simple\keystore\test1234.p12"; string storePass = "******"; string storeAlias = "ECDSAkey"; SystemCertificates.X509Certificate2Collection pkcs12 = new SystemCertificates.X509Certificate2Collection(); pkcs12.Import(storePath, storePass, SystemCertificates.X509KeyStorageFlags.DefaultKeySet); SystemCertificates.X509Certificate2 certificate = null; foreach (SystemCertificates.X509Certificate2 aCertificate in pkcs12) { if (storeAlias.Equals(aCertificate.FriendlyName, StringComparison.InvariantCultureIgnoreCase)) { certificate = aCertificate; break; } } Assert.NotNull(certificate, "Key with alias {0} not found.", storeAlias); X509Certificate2SignatureContainer signature = new X509Certificate2SignatureContainer(certificate, signer => { signer.DigestAlgorithm = Oid.FromFriendlyName("SHA512", OidGroup.HashAlgorithm); }); using (PdfReader pdfReader = new PdfReader(testFileName)) using (FileStream result = File.Create("circles-ECDSA-signed-simple-container.pdf")) { PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode()); pdfSigner.SignExternalContainer(signature, 8192); } }
/* * /// <summary> * /// Create a key pair * /// </summary> * /// <param name="pkSize">Key size</param> * /// <param name="pkAlgo">Key algorithm</param> * /// <param name="name">Key container name</param> * /// <returns></returns> * internal static CspParameters Create(int pkSize, string pkAlgo, string name) * { * // Normalise the name * string _name = name.Replace(' ', '_'); * * CspParameters cp = null; * switch (pkAlgo) * { * case "RSA": * cp = new CspParameters(24, "Microsoft Enhanced RSA and AES Cryptographic Provider"); * cp.KeyContainerName = _name; * cp.Flags = CspProviderFlags.UseArchivableKey; * using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(pkSize, cp)) * { * rsa.PersistKeyInCsp = true; * if (!rsa.CspKeyContainerInfo.Exportable) * throw new CryptoException("Key not exportable"); * } * break; * case "DSA": * cp = new CspParameters(13, "Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider"); * cp.KeyContainerName = _name; * cp.Flags = CspProviderFlags.UseArchivableKey; * DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(pkSize, cp); * dsa.PersistKeyInCsp = true; * break; * //case "ECDSA": * //ECKeyPairGenerator ecGenerator = new ECKeyPairGenerator(pkAlgo); * //ecGenerator.Init(genParam); * //keyPair = ecGenerator.GenerateKeyPair(); * //break; * default: * throw new ArgumentException("Algorithm not supported", pkAlgo); * } * return cp; * } */ #endregion //internal static X509Certificate storeKey(CspParameters cp, X509Certificate cert) internal static X509Certificate storeKey(X509Certificate cert) { //SysX509.X509KeyStorageFlags keyFlags = (SysX509.X509KeyStorageFlags.UserKeySet | SysX509.X509KeyStorageFlags.Exportable); //SysX509.X509KeyStorageFlags keyFlags = SysX509.X509KeyStorageFlags.Exportable; Sys.X509Certificate2 sCert = new Sys.X509Certificate2(cert.GetEncoded()); Sys.X509Store store = new Sys.X509Store(Sys.StoreName.My, Sys.StoreLocation.CurrentUser); store.Open(Sys.OpenFlags.MaxAllowed); store.Add(sCert); Sys.X509Certificate2Collection coll = store.Certificates.Find(Sys.X509FindType.FindBySerialNumber, sCert.SerialNumber, false); if (coll.Count > 1) { throw new CryptoException("Too many certs"); } if (coll.Count < 1) { throw new CryptoException("Cert not found"); } sCert = coll[0]; if (!sCert.HasPrivateKey) { throw new CryptoException("No private key"); } return(cert); }
internal static unsafe int BuildChain(IntPtr hChainEngine, System.Security.Cryptography.SafeCertContextHandle pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, ref SafeCertChainHandle ppChainContext) { if (pCertContext == null || pCertContext.IsInvalid) throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_InvalidContextHandle"), "pCertContext"); SafeCertStoreHandle hAdditionalStore = SafeCertStoreHandle.InvalidHandle; if (extraStore != null && extraStore.Count > 0) hAdditionalStore = X509Utils.ExportToMemoryStore(extraStore); CAPI.CERT_CHAIN_PARA pChainPara = new CAPI.CERT_CHAIN_PARA(); pChainPara.cbSize = (uint)Marshal.SizeOf((object)pChainPara); SafeLocalAllocHandle localAllocHandle1 = SafeLocalAllocHandle.InvalidHandle; if (applicationPolicy != null && applicationPolicy.Count > 0) { pChainPara.RequestedUsage.dwType = 0U; pChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint)applicationPolicy.Count; localAllocHandle1 = X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy); pChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = localAllocHandle1.DangerousGetHandle(); } SafeLocalAllocHandle localAllocHandle2 = SafeLocalAllocHandle.InvalidHandle; if (certificatePolicy != null && certificatePolicy.Count > 0) { pChainPara.RequestedIssuancePolicy.dwType = 0U; pChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint)certificatePolicy.Count; localAllocHandle2 = X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy); pChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = localAllocHandle2.DangerousGetHandle(); } pChainPara.dwUrlRetrievalTimeout = (uint)timeout.Milliseconds; System.Runtime.InteropServices.ComTypes.FILETIME pTime = new System.Runtime.InteropServices.ComTypes.FILETIME(); *(long*)&pTime = verificationTime.ToFileTime(); uint dwFlags = X509Utils.MapRevocationFlags(revocationMode, revocationFlag); if (!CAPI.CAPISafe.CertGetCertificateChain(hChainEngine, pCertContext, ref pTime, hAdditionalStore, ref pChainPara, dwFlags, IntPtr.Zero, out ppChainContext)) return Marshal.GetHRForLastWin32Error(); localAllocHandle1.Dispose(); localAllocHandle2.Dispose(); return 0; }
/** * <summary> * Constructs SSL context with permanent validation result.</summary> * * <param name="permanentResult">Permanent validation result: allow all certificates or deny all.</param> */ public GridClientSslContext(bool permanentResult) { ValidateCallback = permanentResult ? AllowAllCerts : DenyAllCerts; ClientCertificates = new X509Certificate2Collection(); EnabledSslProtocols = SslProtocols.Default; CheckCertificateRevocation = false; }
public CertificateValidationClientServer() { _serverCertificateCollection = Configuration.Certificates.GetServerCertificateCollection(); _serverCertificate = Configuration.Certificates.GetServerCertificate(); _clientCertificateCollection = Configuration.Certificates.GetClientCertificateCollection(); _clientCertificate = Configuration.Certificates.GetClientCertificate(); }
public CmsRecipientCollection (SubjectIdentifierType recipientIdentifierType, X509Certificate2Collection certificates) { // no null check, MS throws a NullReferenceException here foreach (X509Certificate2 x509 in certificates) { CmsRecipient p7r = new CmsRecipient (recipientIdentifierType, x509); _list.Add (p7r); } }
static string SendAPNS(string deviceToken, string content) { //ref:https://msdn.microsoft.com/en-us/library/txafckwd.aspx //ref2:http://stackoverflow.com/questions/16101100/string-format-input-string-was-not-in-correct-format-for-string-with-curly-brack //要多加雙括號"{{"才能讓參數寫入string的format string jsonContent = String.Format("{{\"aps:\":{{\"alert\":\"{0}\",\"badge\":8,\"sound\":\"default\"}}}}", deviceToken); //Json: { MID = 1000242, MsgID = 12345, RegID = "c1564dd73cd73a003d2ad143d96c9e6d651f8b48b45ba8c0ae9c5db87513fde8", Subj = "測試12 主題一:88個badge", Sum = 88, Title = "test2 Content" }; //str = "{\"aps\":{\"alert\":\"" + s2 + "\",\"badge\":10,\"sound\":\"default\"}}"; //string hostIP = "gateway.sandbox.push.apple.com";//"gateway.push.apple.com";//;//feedback.sandbox.push.apple.com//"feedback.sandbox.push.apple.com"; int port = 2195; //2196; string password = "******"; //AllPay //certificate load 需要去Apple申請App的憑證才有此檔 string certificatepath = "aps_production_allpay.p12";//"allpay_apns_dev.p12" ;//"AllPayEPAPNS.p12"//企業版prod;// //"allpay.p12";//bin/debug string certificateFullPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppleCertificate", certificatepath); certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(File.ReadAllBytes(certificateFullPath), password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); var certificates = new System.Security.Cryptography.X509Certificates.X509Certificate2Collection(); certificates.Add(certificate); //使用TCP Cient來建立connect(就是走簡易的http) TcpClient apnsClient = new TcpClient(); Stopwatch timer = new Stopwatch(); try { timer.Start(); apnsClient.Connect(hostIP, port); } catch (SocketException ex) { timer.Stop(); Console.WriteLine("TimeSpend:{0}ms ex:{1}", timer.ElapsedMilliseconds, ex.Message); } //主要認證憑證就是這段,可以使用event認證兩方的憑證,目前APNs這邊都只使用Apple給的憑證 System.Net.Security.SslStream apnsStream = new System.Net.Security.SslStream(apnsClient.GetStream(), false, new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate), new System.Net.Security.LocalCertificateSelectionCallback(SelectLocalCertificate)); try { apnsStream.AuthenticateAsClient(hostIP, certificates, System.Security.Authentication.SslProtocols.Tls, false); timer.Stop(); Console.WriteLine("做完認證的TimeSpend:{0}ms", timer.ElapsedMilliseconds); } catch (System.Security.Authentication.AuthenticationException ex) { Console.WriteLine("error:" + ex.Message); } if (!apnsStream.IsMutuallyAuthenticated) { Console.WriteLine("error:" + "Ssl Stream Failed to Authenticate"); } if (!apnsStream.CanWrite) { Console.WriteLine("error:" + "Ssl Stream is not Writable"); return(""); } //需要取得Apple手機給的token來當作裝置的識別碼,送的格式參考APPLE規定的JSON byte[] message = ToBytes(deviceToken, content); apnsStream.Write(message);//這邊就可以開始送資料了 apnsStream.Close(); return(Encoding.UTF8.GetString(message)); }
public void CloneTo(X509Certificate2Collection collection) { // Never show any data. }
internal X509Certificate2Enumerator(X509Certificate2Collection collection) { enumerator = ((IEnumerable)collection).GetEnumerator(); }
internal static partial IExportPal LinkFromCertificateCollection( X509Certificate2Collection certificates) { throw new PlatformNotSupportedException(SR.SystemSecurityCryptographyX509Certificates_PlatformNotSupported); }
public static X509Certificate2Collection SelectFromCollection(X509Certificate2Collection certificates, string title, string message, X509SelectionFlag selectionFlag) { // note: the LinkDemand won't interfere (by design) as this caller is trusted (correct behaviour) return(SelectFromCollection(certificates, title, message, selectionFlag, IntPtr.Zero)); }
public void CloneTo(X509Certificate2Collection collection) { CopyTo(collection); }
static SecTrustResult _TrustEvaluateSsl(X509Certificate2Collection certificates, string hostName) { int certCount = certificates.Count; IntPtr [] cfDataPtrs = new IntPtr [certCount]; IntPtr [] secCerts = new IntPtr [certCount]; IntPtr certArray = IntPtr.Zero; IntPtr sslsecpolicy = IntPtr.Zero; IntPtr host = IntPtr.Zero; IntPtr sectrust = IntPtr.Zero; SecTrustResult result = SecTrustResult.Deny; try { for (int i = 0; i < certCount; i++) { cfDataPtrs [i] = MakeCFData(certificates [i].RawData); } for (int i = 0; i < certCount; i++) { secCerts [i] = SecCertificateCreateWithData(IntPtr.Zero, cfDataPtrs [i]); if (secCerts [i] == IntPtr.Zero) { return(SecTrustResult.Deny); } } certArray = FromIntPtrs(secCerts); host = CFStringCreateWithCharacters(IntPtr.Zero, hostName, (IntPtr)hostName.Length); sslsecpolicy = SecPolicyCreateSSL(true, host); int code = SecTrustCreateWithCertificates(certArray, sslsecpolicy, out sectrust); if (code == 0) { code = SecTrustEvaluate(sectrust, out result); } return(result); } finally { for (int i = 0; i < certCount; i++) { if (cfDataPtrs [i] != IntPtr.Zero) { CFRelease(cfDataPtrs [i]); } } if (certArray != IntPtr.Zero) { CFRelease(certArray); } for (int i = 0; i < certCount; i++) { if (secCerts [i] != IntPtr.Zero) { CFRelease(secCerts [i]); } } if (sslsecpolicy != IntPtr.Zero) { CFRelease(sslsecpolicy); } if (host != IntPtr.Zero) { CFRelease(host); } if (sectrust != IntPtr.Zero) { CFRelease(sectrust); } } }
public X509Certificate2Collection(X509Certificate2Collection certificates) { AddRange(certificates); }
public bool OnSelectClientCertificate(IWebBrowser browserControl, IBrowser browser, bool isProxy, string host, int port, System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates, ISelectClientCertificateCallback callback) { callback.Dispose(); return(false); }
public void RemoveRange(X509Certificate2Collection certificates) { }
public void AddRange(X509Certificate2Collection certificates) { }
internal UnixExportProvider(X509Certificate2Collection certs) { _certs = certs; }
internal static int VerifyCertificate(System.Security.Cryptography.SafeCertContextHandle pCertContext, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, X509Certificate2Collection extraStore, IntPtr pszPolicy, IntPtr pdwErrorStatus) { if ((pCertContext == null) || pCertContext.IsInvalid) { throw new ArgumentException("pCertContext"); } CAPIBase.CERT_CHAIN_POLICY_PARA pPolicyPara = new CAPIBase.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPIBase.CERT_CHAIN_POLICY_PARA))); CAPIBase.CERT_CHAIN_POLICY_STATUS pPolicyStatus = new CAPIBase.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPIBase.CERT_CHAIN_POLICY_STATUS))); SafeCertChainHandle invalidHandle = SafeCertChainHandle.InvalidHandle; int num = X509Chain.BuildChain(new IntPtr(0L), pCertContext, extraStore, applicationPolicy, certificatePolicy, revocationMode, revocationFlag, verificationTime, timeout, ref invalidHandle); if (num != 0) { return(num); } if (!CAPISafe.CertVerifyCertificateChainPolicy(pszPolicy, invalidHandle, ref pPolicyPara, ref pPolicyStatus)) { return(Marshal.GetHRForLastWin32Error()); } if (pdwErrorStatus != IntPtr.Zero) { pdwErrorStatus[0] = (IntPtr)pPolicyStatus.dwError; } if (pPolicyStatus.dwError == 0) { return(0); } return(1); }
private static partial IFindPal OpenPal(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly) { return(new FindPal(findFrom, copyTo, validOnly)); }
public static X509Certificate2Collection SelectFromCollection(X509Certificate2Collection certificates, string?title, string?message, X509SelectionFlag selectionFlag, IntPtr hwndParent) { return(SelectFromCollectionHelper(certificates, title, message, selectionFlag, hwndParent)); }
internal static System.Security.Cryptography.SafeCertStoreHandle ExportToMemoryStore(X509Certificate2Collection collection) { new StorePermission(StorePermissionFlags.AllFlags).Assert(); System.Security.Cryptography.SafeCertStoreHandle invalidHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle; invalidHandle = CAPI.CertOpenStore(new IntPtr(2L), 0x10001, IntPtr.Zero, 0x2200, null); if ((invalidHandle == null) || invalidHandle.IsInvalid) { throw new CryptographicException(Marshal.GetLastWin32Error()); } X509Certificate2Enumerator enumerator = collection.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate2 current = enumerator.Current; if (!CAPI.CertAddCertificateLinkToStore(invalidHandle, current.CertContext, 4, System.Security.Cryptography.SafeCertContextHandle.InvalidHandle)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } return(invalidHandle); }
public static X509Certificate2Collection SelectFromCollection(X509Certificate2Collection certificates, string title, string message, X509SelectionFlag selectionFlag) { return(SelectFromCollectionHelper(certificates, title, message, selectionFlag, IntPtr.Zero)); }
private FindPal(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly) { _storePal = (StorePal)StorePal.LinkFromCertificateCollection(findFrom); _copyTo = copyTo; _validOnly = validOnly; }
internal static partial IExportPal LinkFromCertificateCollection(X509Certificate2Collection certificates) { return(new OpenSslExportProvider(certificates)); }
internal static unsafe int BuildChain(IntPtr hChainEngine, SafeCertContextHandle pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, ref SafeCertChainHandle ppChainContext) { if (pCertContext == null || pCertContext.IsInvalid) { throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_InvalidContextHandle"), "pCertContext"); } SafeCertStoreHandle hCertStore = SafeCertStoreHandle.InvalidHandle; if (extraStore != null && extraStore.Count > 0) { hCertStore = X509Utils.ExportToMemoryStore(extraStore); } CAPI.CERT_CHAIN_PARA ChainPara = new CAPI.CERT_CHAIN_PARA(); // Initialize the structure size. ChainPara.cbSize = (uint)Marshal.SizeOf(ChainPara); // Application policy SafeLocalAllocHandle applicationPolicyHandle = SafeLocalAllocHandle.InvalidHandle; if (applicationPolicy != null && applicationPolicy.Count > 0) { ChainPara.RequestedUsage.dwType = CAPI.USAGE_MATCH_TYPE_AND; ChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint)applicationPolicy.Count; applicationPolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy); ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyHandle.DangerousGetHandle(); } // Certificate policy SafeLocalAllocHandle certificatePolicyHandle = SafeLocalAllocHandle.InvalidHandle; if (certificatePolicy != null && certificatePolicy.Count > 0) { ChainPara.RequestedIssuancePolicy.dwType = CAPI.USAGE_MATCH_TYPE_AND; ChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint)certificatePolicy.Count; certificatePolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy); ChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyHandle.DangerousGetHandle(); } ChainPara.dwUrlRetrievalTimeout = (uint)timeout.Milliseconds; _FILETIME ft = new _FILETIME(); *((long *)&ft) = verificationTime.ToFileTime(); uint flags = X509Utils.MapRevocationFlags(revocationMode, revocationFlag); // Build the chain. if (!CAPI.CAPISafe.CertGetCertificateChain(hChainEngine, pCertContext, ref ft, hCertStore, ref ChainPara, flags, IntPtr.Zero, ref ppChainContext)) { return(Marshal.GetHRForLastWin32Error()); } applicationPolicyHandle.Dispose(); certificatePolicyHandle.Dispose(); return(CAPI.S_OK); }
/// <summary> /// 带证书提交数据并获取返回内容 /// </summary> /// <param name="Url">访问地址</param> /// <param name="Args">提交参数</param> /// <param name="enc">编码格式</param> /// <param name="StoreName">证书存储位置</param> /// <param name="CertName">证书名称</param> /// <returns></returns> public static string PostWithCert(string Url, string Args, Encoding enc, StoreName StoreName, string CertName) { string respHTML = ""; try { X509Store store = new X509Store(StoreName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); System.Security.Cryptography.X509Certificates.X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, CertName, false); if (certs.Count <= 0) { throw new Exception("未发现证书文件"); } //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = //store.Certificates.Find(X509FindType.FindBySubjectName, CertName, false)[0]; System.Net.HttpWebRequest httpReq; System.Net.HttpWebResponse httpResp; System.Uri httpURL = new System.Uri(Url); httpReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(httpURL); httpReq.ClientCertificates.Add(certs[0]); httpReq.Method = "POST"; byte[] bs = enc.GetBytes(Args); httpReq.KeepAlive = false; httpReq.ContentType = "application/x-www-form-urlencoded"; httpReq.ContentLength = bs.Length; httpReq.Timeout = 30000; //httpReq. //post数据 using (System.IO.Stream reqStream = httpReq.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); } httpResp = (System.Net.HttpWebResponse)httpReq.GetResponse(); using (System.IO.Stream MyStream = httpResp.GetResponseStream()) { System.IO.StreamReader reader = new System.IO.StreamReader(MyStream, Encoding.UTF8); //byte[] TheBytes = new byte[MyStream.Length]; //MyStream.Read(TheBytes, 0, (int)MyStream.Length); //respHTML = Encoding.UTF8.GetString(TheBytes); respHTML = reader.ReadToEnd(); reader.Dispose(); MyStream.Dispose(); } httpResp.Close(); httpReq = null; } catch (Exception ex) { throw new Exception("获取HTML发生异常:" + ex.Message); //System.Windows.Forms.MessageBox.Show("获取信息发生异常:\r\n" + ex.Message + "\r\n" + Url); //Debug.WriteLine("Debug\\>GetHTML::Error(" + ex + ")"); } return(respHTML); }
internal X509Certificate2Enumerator(X509Certificate2Collection collection) { Debug.Assert(collection != null); _enumerator = ((IEnumerable)collection).GetEnumerator(); }
public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly) { if (findValue == null) { throw new ArgumentNullException("findValue"); } string str = String.Empty; string oid = String.Empty; X509KeyUsageFlags ku = X509KeyUsageFlags.None; DateTime dt = DateTime.MinValue; switch (findType) { case X509FindType.FindByThumbprint: case X509FindType.FindBySubjectName: case X509FindType.FindBySubjectDistinguishedName: case X509FindType.FindByIssuerName: case X509FindType.FindByIssuerDistinguishedName: case X509FindType.FindBySerialNumber: case X509FindType.FindByTemplateName: case X509FindType.FindBySubjectKeyIdentifier: try { str = (string)findValue; } catch (Exception e) { string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", findValue.GetType(), "string"); throw new CryptographicException(msg, e); } break; case X509FindType.FindByApplicationPolicy: case X509FindType.FindByCertificatePolicy: case X509FindType.FindByExtension: try { oid = (string)findValue; } catch (Exception e) { string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", findValue.GetType(), "X509KeyUsageFlags"); throw new CryptographicException(msg, e); } // OID validation try { CryptoConfig.EncodeOID(oid); } catch (CryptographicUnexpectedOperationException) { string msg = Locale.GetText("Invalid OID value '{0}'.", oid); throw new ArgumentException("findValue", msg); } break; case X509FindType.FindByKeyUsage: try { ku = (X509KeyUsageFlags)findValue; } catch (Exception e) { string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", findValue.GetType(), "X509KeyUsageFlags"); throw new CryptographicException(msg, e); } break; case X509FindType.FindByTimeValid: case X509FindType.FindByTimeNotYetValid: case X509FindType.FindByTimeExpired: try { dt = (DateTime)findValue; } catch (Exception e) { string msg = Locale.GetText("Invalid find value type '{0}', expected '{1}'.", findValue.GetType(), "X509DateTime"); throw new CryptographicException(msg, e); } break; default: { string msg = Locale.GetText("Invalid find type '{0}'.", findType); throw new CryptographicException(msg); } } CultureInfo cinv = CultureInfo.InvariantCulture; X509Certificate2Collection results = new X509Certificate2Collection(); foreach (X509Certificate2 x in InnerList) { bool value_match = false; switch (findType) { case X509FindType.FindByThumbprint: // works with Thumbprint, GetCertHashString in both normal (upper) and lower case value_match = ((String.Compare(str, x.Thumbprint, true, cinv) == 0) || (String.Compare(str, x.GetCertHashString(), true, cinv) == 0)); break; case X509FindType.FindBySubjectName: string sname = x.GetNameInfo(X509NameType.SimpleName, false); value_match = (sname.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) >= 0); break; case X509FindType.FindBySubjectDistinguishedName: value_match = (String.Compare(str, x.Subject, true, cinv) == 0); break; case X509FindType.FindByIssuerName: string iname = x.GetNameInfo(X509NameType.SimpleName, true); value_match = (iname.IndexOf(str, StringComparison.InvariantCultureIgnoreCase) >= 0); break; case X509FindType.FindByIssuerDistinguishedName: value_match = (String.Compare(str, x.Issuer, true, cinv) == 0); break; case X509FindType.FindBySerialNumber: value_match = (String.Compare(str, x.SerialNumber, true, cinv) == 0); break; case X509FindType.FindByTemplateName: // TODO - find a valid test case break; case X509FindType.FindBySubjectKeyIdentifier: X509SubjectKeyIdentifierExtension ski = (x.Extensions ["2.5.29.14"] as X509SubjectKeyIdentifierExtension); if (ski != null) { value_match = (String.Compare(str, ski.SubjectKeyIdentifier, true, cinv) == 0); } break; case X509FindType.FindByApplicationPolicy: // note: include when no extensions are present (even if v3) value_match = (x.Extensions.Count == 0); // TODO - find test case with extension break; case X509FindType.FindByCertificatePolicy: // TODO - find test case with extension break; case X509FindType.FindByExtension: value_match = (x.Extensions [oid] != null); break; case X509FindType.FindByKeyUsage: X509KeyUsageExtension kue = (x.Extensions ["2.5.29.15"] as X509KeyUsageExtension); if (kue == null) { // key doesn't have any hard coded limitations // note: MS doesn't check for ExtendedKeyUsage value_match = true; } else { value_match = ((kue.KeyUsages & ku) == ku); } break; case X509FindType.FindByTimeValid: value_match = ((dt >= x.NotBefore) && (dt <= x.NotAfter)); break; case X509FindType.FindByTimeNotYetValid: value_match = (dt < x.NotBefore); break; case X509FindType.FindByTimeExpired: value_match = (dt > x.NotAfter); break; } if (!value_match) { continue; } if (validOnly) { try { if (x.Verify()) { results.Add(x); } } catch { } } else { results.Add(x); } } return(results); }
internal static unsafe int BuildChain(IntPtr hChainEngine, System.Security.Cryptography.SafeCertContextHandle pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, ref System.Security.Cryptography.SafeCertChainHandle ppChainContext) { System.Security.Cryptography.CAPI.CERT_CHAIN_PARA cert_chain_para; if ((pCertContext == null) || pCertContext.IsInvalid) { throw new ArgumentException(SecurityResources.GetResourceString("Cryptography_InvalidContextHandle"), "pCertContext"); } System.Security.Cryptography.SafeCertStoreHandle invalidHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle; if ((extraStore != null) && (extraStore.Count > 0)) { invalidHandle = ExportToMemoryStore(extraStore); } cert_chain_para = new System.Security.Cryptography.CAPI.CERT_CHAIN_PARA { cbSize = (uint)Marshal.SizeOf(cert_chain_para) }; System.Security.Cryptography.SafeLocalAllocHandle handle2 = System.Security.Cryptography.SafeLocalAllocHandle.InvalidHandle; if ((applicationPolicy != null) && (applicationPolicy.Count > 0)) { cert_chain_para.RequestedUsage.dwType = 0; cert_chain_para.RequestedUsage.Usage.cUsageIdentifier = (uint)applicationPolicy.Count; handle2 = CopyOidsToUnmanagedMemory(applicationPolicy); cert_chain_para.RequestedUsage.Usage.rgpszUsageIdentifier = handle2.DangerousGetHandle(); } System.Security.Cryptography.SafeLocalAllocHandle handle3 = System.Security.Cryptography.SafeLocalAllocHandle.InvalidHandle; if ((certificatePolicy != null) && (certificatePolicy.Count > 0)) { cert_chain_para.RequestedIssuancePolicy.dwType = 0; cert_chain_para.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint)certificatePolicy.Count; handle3 = CopyOidsToUnmanagedMemory(certificatePolicy); cert_chain_para.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = handle3.DangerousGetHandle(); } cert_chain_para.dwUrlRetrievalTimeout = (uint)timeout.Milliseconds; System.Runtime.InteropServices.ComTypes.FILETIME pTime = new System.Runtime.InteropServices.ComTypes.FILETIME(); *((long *)&pTime) = verificationTime.ToFileTime(); uint dwFlags = MapRevocationFlags(revocationMode, revocationFlag); if (!System.Security.Cryptography.CAPI.CAPISafe.CertGetCertificateChain(hChainEngine, pCertContext, ref pTime, invalidHandle, ref cert_chain_para, dwFlags, IntPtr.Zero, ref ppChainContext)) { return(Marshal.GetHRForLastWin32Error()); } handle2.Dispose(); handle3.Dispose(); return(0); }
internal X509CertificateEndpointIdentity(XmlDictionaryReader reader) { this.certificateCollection = new X509Certificate2Collection(); if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } reader.MoveToContent(); if (reader.IsEmptyElement) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedEmptyElementExpectingClaim", new object[] { XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value }))); } reader.ReadStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace); while (reader.IsStartElement(XD.XmlSignatureDictionary.X509Certificate, XD.XmlSignatureDictionary.Namespace)) { X509Certificate2 certificate = new X509Certificate2(Convert.FromBase64String(reader.ReadElementString())); if (this.certificateCollection.Count == 0) { base.Initialize(new Claim(ClaimTypes.Thumbprint, certificate.GetCertHash(), Rights.PossessProperty)); } this.certificateCollection.Add(certificate); } reader.ReadEndElement(); if (this.certificateCollection.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("UnexpectedEmptyElementExpectingClaim", new object[] { XD.AddressingDictionary.X509v3Certificate.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value }))); } }