Пример #1
0
 public byte[] Export(X509ContentType contentType, string password)
 {
     new StorePermission(StorePermissionFlags.AllFlags).Assert();
     System.Security.Cryptography.SafeCertStoreHandle safeCertStoreHandle = System.Security.Cryptography.X509Certificates.X509Utils.ExportToMemoryStore(this);
     byte[] buffer = ExportCertificatesToBlob(safeCertStoreHandle, contentType, password);
     safeCertStoreHandle.Dispose();
     return(buffer);
 }
Пример #2
0
        private static void FindByCert(System.Security.Cryptography.SafeCertStoreHandle safeSourceStoreHandle, uint dwFindType, IntPtr pvFindPara, bool validOnly, FindProcDelegate pfnCertCallback1, FindProcDelegate pfnCertCallback2, object pvCallbackData1, object pvCallbackData2, System.Security.Cryptography.SafeCertStoreHandle safeTargetStoreHandle)
        {
            int hr = 0;

            System.Security.Cryptography.SafeCertContextHandle invalidHandle = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
            invalidHandle = CAPI.CertFindCertificateInStore(safeSourceStoreHandle, 0x10001, 0, dwFindType, pvFindPara, invalidHandle);
            while ((invalidHandle != null) && !invalidHandle.IsInvalid)
            {
                if (pfnCertCallback1 != null)
                {
                    hr = pfnCertCallback1(invalidHandle, pvCallbackData1);
                    if (hr == 1)
                    {
                        if (pfnCertCallback2 != null)
                        {
                            hr = pfnCertCallback2(invalidHandle, pvCallbackData2);
                        }
                        if (hr == 1)
                        {
                            goto Label_008D;
                        }
                    }
                    if (hr != 0)
                    {
                        break;
                    }
                }
                if (validOnly)
                {
                    hr = System.Security.Cryptography.X509Certificates.X509Utils.VerifyCertificate(invalidHandle, null, null, X509RevocationMode.NoCheck, X509RevocationFlag.ExcludeRoot, DateTime.Now, new TimeSpan(0, 0, 0), null, new IntPtr(1L), IntPtr.Zero);
                    if (hr == 1)
                    {
                        goto Label_008D;
                    }
                    if (hr != 0)
                    {
                        break;
                    }
                }
                if (!CAPI.CertAddCertificateLinkToStore(safeTargetStoreHandle, invalidHandle, 4, System.Security.Cryptography.SafeCertContextHandle.InvalidHandle))
                {
                    hr = Marshal.GetHRForLastWin32Error();
                    break;
                }
Label_008D:
                GC.SuppressFinalize(invalidHandle);
                invalidHandle = CAPI.CertFindCertificateInStore(safeSourceStoreHandle, 0x10001, 0, dwFindType, pvFindPara, invalidHandle);
            }
            if ((invalidHandle != null) && !invalidHandle.IsInvalid)
            {
                invalidHandle.Dispose();
            }
            if ((hr != 1) && (hr != 0))
            {
                throw new CryptographicException(hr);
            }
        }
Пример #3
0
 public X509Store(string storeName, StoreLocation storeLocation)
 {
     this.m_safeCertStoreHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle;
     if ((storeLocation != StoreLocation.CurrentUser) && (storeLocation != StoreLocation.LocalMachine))
     {
         throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.GetString("Arg_EnumIllegalVal"), new object[] { "storeLocation" }));
     }
     this.m_storeName = storeName;
     this.m_location  = storeLocation;
 }
Пример #4
0
        public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly)
        {
            new StorePermission(StorePermissionFlags.AllFlags).Assert();
            System.Security.Cryptography.SafeCertStoreHandle safeSourceStoreHandle = System.Security.Cryptography.X509Certificates.X509Utils.ExportToMemoryStore(this);
            System.Security.Cryptography.SafeCertStoreHandle safeCertStoreHandle   = FindCertInStore(safeSourceStoreHandle, findType, findValue, validOnly);
            X509Certificate2Collection certificates = System.Security.Cryptography.X509Certificates.X509Utils.GetCertificates(safeCertStoreHandle);

            safeCertStoreHandle.Dispose();
            safeSourceStoreHandle.Dispose();
            return(certificates);
        }
Пример #5
0
        internal static X509Certificate2Collection GetCertificates(System.Security.Cryptography.SafeCertStoreHandle safeCertStoreHandle)
        {
            X509Certificate2Collection certificates = new X509Certificate2Collection();

            for (IntPtr ptr = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, IntPtr.Zero); ptr != IntPtr.Zero; ptr = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, ptr))
            {
                X509Certificate2 certificate = new X509Certificate2(ptr);
                certificates.Add(certificate);
            }
            return(certificates);
        }
 public X509Store(IntPtr storeHandle)
 {
     this.m_safeCertStoreHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle;
     if (storeHandle == IntPtr.Zero)
     {
         throw new ArgumentNullException("storeHandle");
     }
     this.m_safeCertStoreHandle = CAPISafe.CertDuplicateStore(storeHandle);
     if ((this.m_safeCertStoreHandle == null) || this.m_safeCertStoreHandle.IsInvalid)
     {
         throw new CryptographicException(SR.GetString("Cryptography_InvalidStoreHandle"), "storeHandle");
     }
 }
Пример #7
0
 public X509Store(IntPtr storeHandle)
 {
     this.m_safeCertStoreHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle;
     if (storeHandle == IntPtr.Zero)
     {
         throw new ArgumentNullException("storeHandle");
     }
     this.m_safeCertStoreHandle = CAPISafe.CertDuplicateStore(storeHandle);
     if ((this.m_safeCertStoreHandle == null) || this.m_safeCertStoreHandle.IsInvalid)
     {
         throw new CryptographicException(SR.GetString("Cryptography_InvalidStoreHandle"), "storeHandle");
     }
 }
Пример #8
0
        public void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags)
        {
            uint dwFlags = System.Security.Cryptography.X509Certificates.X509Utils.MapKeyStorageFlags(keyStorageFlags);

            System.Security.Cryptography.SafeCertStoreHandle invalidHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle;
            new StorePermission(StorePermissionFlags.AllFlags).Assert();
            invalidHandle = LoadStoreFromFile(fileName, password, dwFlags, (keyStorageFlags & X509KeyStorageFlags.PersistKeySet) != X509KeyStorageFlags.DefaultKeySet);
            X509Certificate2Collection certificates = System.Security.Cryptography.X509Certificates.X509Utils.GetCertificates(invalidHandle);

            invalidHandle.Dispose();
            X509Certificate2[] array = new X509Certificate2[certificates.Count];
            certificates.CopyTo(array, 0);
            this.AddRange(array);
        }
        public X509Store(StoreName storeName, StoreLocation storeLocation)
        {
            this.m_safeCertStoreHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle;
            if ((storeLocation != StoreLocation.CurrentUser) && (storeLocation != StoreLocation.LocalMachine))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.GetString("Arg_EnumIllegalVal"), new object[] { "storeLocation" }));
            }
            switch (storeName)
            {
                case StoreName.AddressBook:
                    this.m_storeName = "AddressBook";
                    break;

                case StoreName.AuthRoot:
                    this.m_storeName = "AuthRoot";
                    break;

                case StoreName.CertificateAuthority:
                    this.m_storeName = "CA";
                    break;

                case StoreName.Disallowed:
                    this.m_storeName = "Disallowed";
                    break;

                case StoreName.My:
                    this.m_storeName = "My";
                    break;

                case StoreName.Root:
                    this.m_storeName = "Root";
                    break;

                case StoreName.TrustedPeople:
                    this.m_storeName = "TrustedPeople";
                    break;

                case StoreName.TrustedPublisher:
                    this.m_storeName = "TrustedPublisher";
                    break;

                default:
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.GetString("Arg_EnumIllegalVal"), new object[] { "storeName" }));
            }
            this.m_location = storeLocation;
        }
Пример #10
0
        public X509Store(StoreName storeName, StoreLocation storeLocation)
        {
            this.m_safeCertStoreHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle;
            if ((storeLocation != StoreLocation.CurrentUser) && (storeLocation != StoreLocation.LocalMachine))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.GetString("Arg_EnumIllegalVal"), new object[] { "storeLocation" }));
            }
            switch (storeName)
            {
            case StoreName.AddressBook:
                this.m_storeName = "AddressBook";
                break;

            case StoreName.AuthRoot:
                this.m_storeName = "AuthRoot";
                break;

            case StoreName.CertificateAuthority:
                this.m_storeName = "CA";
                break;

            case StoreName.Disallowed:
                this.m_storeName = "Disallowed";
                break;

            case StoreName.My:
                this.m_storeName = "My";
                break;

            case StoreName.Root:
                this.m_storeName = "Root";
                break;

            case StoreName.TrustedPeople:
                this.m_storeName = "TrustedPeople";
                break;

            case StoreName.TrustedPublisher:
                this.m_storeName = "TrustedPublisher";
                break;

            default:
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.GetString("Arg_EnumIllegalVal"), new object[] { "storeName" }));
            }
            this.m_location = storeLocation;
        }
        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)
        {
            CAPIBase.CERT_CHAIN_PARA cert_chain_para;
            if ((pCertContext == null) || pCertContext.IsInvalid)
            {
                throw new ArgumentException(SR.GetString("Cryptography_InvalidContextHandle"), "pCertContext");
            }
            System.Security.Cryptography.SafeCertStoreHandle invalidHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle;
            if ((extraStore != null) && (extraStore.Count > 0))
            {
                invalidHandle = System.Security.Cryptography.X509Certificates.X509Utils.ExportToMemoryStore(extraStore);
            }
            cert_chain_para = new CAPIBase.CERT_CHAIN_PARA {
                cbSize = (uint)Marshal.SizeOf(cert_chain_para)
            };
            SafeLocalAllocHandle handle2 = SafeLocalAllocHandle.InvalidHandle;

            if ((applicationPolicy != null) && (applicationPolicy.Count > 0))
            {
                cert_chain_para.RequestedUsage.dwType = 0;
                cert_chain_para.RequestedUsage.Usage.cUsageIdentifier = (uint)applicationPolicy.Count;
                handle2 = System.Security.Cryptography.X509Certificates.X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy);
                cert_chain_para.RequestedUsage.Usage.rgpszUsageIdentifier = handle2.DangerousGetHandle();
            }
            SafeLocalAllocHandle handle3 = SafeLocalAllocHandle.InvalidHandle;

            if ((certificatePolicy != null) && (certificatePolicy.Count > 0))
            {
                cert_chain_para.RequestedIssuancePolicy.dwType = 0;
                cert_chain_para.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint)certificatePolicy.Count;
                handle3 = System.Security.Cryptography.X509Certificates.X509Utils.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 = System.Security.Cryptography.X509Certificates.X509Utils.MapRevocationFlags(revocationMode, revocationFlag);

            if (!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);
        }
Пример #12
0
        private static unsafe System.Security.Cryptography.SafeCertStoreHandle SelectFromStore(System.Security.Cryptography.SafeCertStoreHandle safeSourceStoreHandle, string title, string message, X509SelectionFlag selectionFlags, IntPtr hwndParent)
        {
            int num = 0;

            System.Security.Cryptography.SafeCertStoreHandle hCertStore = System.Security.Cryptography.CAPI.CertOpenStore((IntPtr)2L, 0x10001, IntPtr.Zero, 0, null);
            if ((hCertStore == null) || hCertStore.IsInvalid)
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            System.Security.Cryptography.CAPI.CRYPTUI_SELECTCERTIFICATE_STRUCTW csc = new System.Security.Cryptography.CAPI.CRYPTUI_SELECTCERTIFICATE_STRUCTW {
                dwSize           = (uint)((int)Marshal.OffsetOf(typeof(System.Security.Cryptography.CAPI.CRYPTUI_SELECTCERTIFICATE_STRUCTW), "hSelectedCertStore")),
                hwndParent       = hwndParent,
                dwFlags          = (uint)selectionFlags,
                szTitle          = title,
                dwDontUseColumn  = 0,
                szDisplayString  = message,
                pFilterCallback  = IntPtr.Zero,
                pDisplayCallback = IntPtr.Zero,
                pvCallbackData   = IntPtr.Zero,
                cDisplayStores   = 1
            };
            IntPtr handle = safeSourceStoreHandle.DangerousGetHandle();

            csc.rghDisplayStores   = new IntPtr((void *)&handle);
            csc.cStores            = 0;
            csc.rghStores          = IntPtr.Zero;
            csc.cPropSheetPages    = 0;
            csc.rgPropSheetPages   = IntPtr.Zero;
            csc.hSelectedCertStore = hCertStore.DangerousGetHandle();
            System.Security.Cryptography.SafeCertContextHandle pCertContext = System.Security.Cryptography.CAPI.CryptUIDlgSelectCertificateW(csc);
            if ((pCertContext != null) && !pCertContext.IsInvalid)
            {
                System.Security.Cryptography.SafeCertContextHandle invalidHandle = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
                if (!System.Security.Cryptography.CAPI.CertAddCertificateContextToStore(hCertStore, pCertContext, 7, invalidHandle))
                {
                    num = Marshal.GetLastWin32Error();
                }
            }
            if (num != 0)
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            return(hCertStore);
        }
Пример #13
0
 private static void RemoveCertificateFromStore(System.Security.Cryptography.SafeCertStoreHandle safeCertStoreHandle, System.Security.Cryptography.SafeCertContextHandle safeCertContext)
 {
     if ((safeCertContext != null) && !safeCertContext.IsInvalid)
     {
         if (((safeCertStoreHandle == null) || safeCertStoreHandle.IsInvalid) || safeCertStoreHandle.IsClosed)
         {
             throw new CryptographicException(SR.GetString("Cryptography_X509_StoreNotOpen"));
         }
         System.Security.Cryptography.SafeCertContextHandle handle = CAPI.CertFindCertificateInStore(safeCertStoreHandle, 0x10001, 0, 0xd0000, safeCertContext.DangerousGetHandle(), System.Security.Cryptography.SafeCertContextHandle.InvalidHandle);
         if ((handle != null) && !handle.IsInvalid)
         {
             GC.SuppressFinalize(handle);
             if (!CAPI.CertDeleteCertificateFromStore(handle))
             {
                 throw new CryptographicException(Marshal.GetLastWin32Error());
             }
         }
     }
 }
Пример #14
0
        public void Open(OpenFlags flags)
        {
            if ((this.m_location != StoreLocation.CurrentUser) && (this.m_location != StoreLocation.LocalMachine))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.GetString("Arg_EnumIllegalVal"), new object[] { "m_location" }));
            }
            uint dwFlags = System.Security.Cryptography.X509Certificates.X509Utils.MapX509StoreFlags(this.m_location, flags);

            if (!this.m_safeCertStoreHandle.IsInvalid)
            {
                this.m_safeCertStoreHandle.Dispose();
            }
            this.m_safeCertStoreHandle = CAPI.CertOpenStore(new IntPtr(10L), 0x10001, IntPtr.Zero, dwFlags, this.m_storeName);
            if ((this.m_safeCertStoreHandle == null) || this.m_safeCertStoreHandle.IsInvalid)
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            CAPISafe.CertControlStore(this.m_safeCertStoreHandle, 0, 4, IntPtr.Zero);
        }
Пример #15
0
        private static unsafe System.Security.Cryptography.SafeCertStoreHandle LoadStoreFromFile(string fileName, string password, uint dwFlags, bool persistKeyContainers)
        {
            uint num = 0;

            System.Security.Cryptography.SafeCertStoreHandle invalidHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle;
            if (!CAPI.CryptQueryObject(1, fileName, 0x1732, 14, 0, IntPtr.Zero, new IntPtr((void *)&num), IntPtr.Zero, ref invalidHandle, IntPtr.Zero, IntPtr.Zero))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            if (num == 12)
            {
                invalidHandle.Dispose();
                invalidHandle = CAPI.PFXImportCertStore(1, fileName, password, dwFlags, persistKeyContainers);
            }
            if ((invalidHandle == null) || invalidHandle.IsInvalid)
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            return(invalidHandle);
        }
Пример #16
0
        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);
        }
Пример #17
0
        private static X509Certificate2Collection SelectFromCollectionHelper(X509Certificate2Collection certificates, string title, string message, X509SelectionFlag selectionFlag, IntPtr hwndParent)
        {
            X509Certificate2Collection certificates2;

            if (certificates == null)
            {
                throw new ArgumentNullException("certificates");
            }
            if ((selectionFlag < X509SelectionFlag.SingleSelection) || (selectionFlag > X509SelectionFlag.MultiSelection))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Arg_EnumIllegalVal"), new object[] { "selectionFlag" }));
            }
            new StorePermission(StorePermissionFlags.AllFlags).Assert();
            using (System.Security.Cryptography.SafeCertStoreHandle handle = System.Security.Cryptography.X509Certificates.X509Utils.ExportToMemoryStore(certificates))
            {
                using (System.Security.Cryptography.SafeCertStoreHandle handle2 = SelectFromStore(handle, title, message, selectionFlag, hwndParent))
                {
                    certificates2 = System.Security.Cryptography.X509Certificates.X509Utils.GetCertificates(handle2);
                }
            }
            return(certificates2);
        }
Пример #18
0
        private static unsafe byte[] ExportCertificatesToBlob(System.Security.Cryptography.SafeCertStoreHandle safeCertStoreHandle, X509ContentType contentType, string password)
        {
            System.Security.Cryptography.SafeCertContextHandle invalidHandle = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
            uint dwSaveAs = 2;

            byte[] destination = null;
            CAPIBase.CRYPTOAPI_BLOB cryptoapi_blob = new CAPIBase.CRYPTOAPI_BLOB();
            SafeLocalAllocHandle    pbElement      = SafeLocalAllocHandle.InvalidHandle;

            switch (contentType)
            {
            case X509ContentType.Cert:
                invalidHandle = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, invalidHandle);
                if ((invalidHandle != null) && !invalidHandle.IsInvalid)
                {
                    CAPIBase.CERT_CONTEXT cert_context = *((CAPIBase.CERT_CONTEXT *)invalidHandle.DangerousGetHandle());
                    destination = new byte[cert_context.cbCertEncoded];
                    Marshal.Copy(cert_context.pbCertEncoded, destination, 0, destination.Length);
                }
                break;

            case X509ContentType.SerializedCert:
            {
                invalidHandle = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, invalidHandle);
                uint num2 = 0;
                if ((invalidHandle != null) && !invalidHandle.IsInvalid)
                {
                    if (!CAPISafe.CertSerializeCertificateStoreElement(invalidHandle, 0, pbElement, new IntPtr((void *)&num2)))
                    {
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    }
                    pbElement = CAPI.LocalAlloc(0, new IntPtr((long)num2));
                    if (!CAPISafe.CertSerializeCertificateStoreElement(invalidHandle, 0, pbElement, new IntPtr((void *)&num2)))
                    {
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    }
                    destination = new byte[num2];
                    Marshal.Copy(pbElement.DangerousGetHandle(), destination, 0, destination.Length);
                    break;
                }
                break;
            }

            case X509ContentType.Pfx:
                if (!CAPI.PFXExportCertStore(safeCertStoreHandle, new IntPtr((void *)&cryptoapi_blob), password, 6))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                cryptoapi_blob.pbData = CAPI.LocalAlloc(0, new IntPtr((long)cryptoapi_blob.cbData)).DangerousGetHandle();
                if (!CAPI.PFXExportCertStore(safeCertStoreHandle, new IntPtr((void *)&cryptoapi_blob), password, 6))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                destination = new byte[cryptoapi_blob.cbData];
                Marshal.Copy(cryptoapi_blob.pbData, destination, 0, destination.Length);
                break;

            case X509ContentType.SerializedStore:
            case X509ContentType.Pkcs7:
                if (contentType == X509ContentType.SerializedStore)
                {
                    dwSaveAs = 1;
                }
                if (!CAPI.CertSaveStore(safeCertStoreHandle, 0x10001, dwSaveAs, 2, new IntPtr((void *)&cryptoapi_blob), 0))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                pbElement             = CAPI.LocalAlloc(0, new IntPtr((long)cryptoapi_blob.cbData));
                cryptoapi_blob.pbData = pbElement.DangerousGetHandle();
                if (!CAPI.CertSaveStore(safeCertStoreHandle, 0x10001, dwSaveAs, 2, new IntPtr((void *)&cryptoapi_blob), 0))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                destination = new byte[cryptoapi_blob.cbData];
                Marshal.Copy(cryptoapi_blob.pbData, destination, 0, destination.Length);
                break;

            default:
                throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidContentType"));
            }
            pbElement.Dispose();
            invalidHandle.Dispose();
            return(destination);
        }
 public X509Store(string storeName, StoreLocation storeLocation)
 {
     this.m_safeCertStoreHandle = System.Security.Cryptography.SafeCertStoreHandle.InvalidHandle;
     if ((storeLocation != StoreLocation.CurrentUser) && (storeLocation != StoreLocation.LocalMachine))
     {
         throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.GetString("Arg_EnumIllegalVal"), new object[] { "storeLocation" }));
     }
     this.m_storeName = storeName;
     this.m_location = storeLocation;
 }
 public void Open(OpenFlags flags)
 {
     if ((this.m_location != StoreLocation.CurrentUser) && (this.m_location != StoreLocation.LocalMachine))
     {
         throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.GetString("Arg_EnumIllegalVal"), new object[] { "m_location" }));
     }
     uint dwFlags = System.Security.Cryptography.X509Certificates.X509Utils.MapX509StoreFlags(this.m_location, flags);
     if (!this.m_safeCertStoreHandle.IsInvalid)
     {
         this.m_safeCertStoreHandle.Dispose();
     }
     this.m_safeCertStoreHandle = CAPI.CertOpenStore(new IntPtr(10L), 0x10001, IntPtr.Zero, dwFlags, this.m_storeName);
     if ((this.m_safeCertStoreHandle == null) || this.m_safeCertStoreHandle.IsInvalid)
     {
         throw new CryptographicException(Marshal.GetLastWin32Error());
     }
     CAPISafe.CertControlStore(this.m_safeCertStoreHandle, 0, 4, IntPtr.Zero);
 }
Пример #21
0
        private static unsafe System.Security.Cryptography.SafeCertStoreHandle FindCertInStore(System.Security.Cryptography.SafeCertStoreHandle safeSourceStoreHandle, X509FindType findType, object findValue, bool validOnly)
        {
            string str;
            string str2;

            System.Security.Cryptography.SafeCertStoreHandle handle2;
            if (findValue == null)
            {
                throw new ArgumentNullException("findValue");
            }
            IntPtr           zero          = IntPtr.Zero;
            object           dwKeyUsageBit = null;
            object           obj3          = null;
            FindProcDelegate delegate2     = null;
            FindProcDelegate delegate3     = null;
            uint             dwFindType    = 0;

            CAPIBase.CRYPTOAPI_BLOB cryptoapi_blob = new CAPIBase.CRYPTOAPI_BLOB();
            SafeLocalAllocHandle    invalidHandle  = SafeLocalAllocHandle.InvalidHandle;

            System.Runtime.InteropServices.ComTypes.FILETIME filetime = new System.Runtime.InteropServices.ComTypes.FILETIME();
            string keyValue = null;

            switch (findType)
            {
            case X509FindType.FindByThumbprint:
            {
                if (findValue.GetType() != typeof(string))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                byte[] managed = System.Security.Cryptography.X509Certificates.X509Utils.DecodeHexString((string)findValue);
                cryptoapi_blob.pbData = System.Security.Cryptography.X509Certificates.X509Utils.ByteToPtr(managed).DangerousGetHandle();
                cryptoapi_blob.cbData = (uint)managed.Length;
                dwFindType            = 0x10000;
                zero = new IntPtr((void *)&cryptoapi_blob);
                goto Label_0703;
            }

            case X509FindType.FindBySubjectName:
                if (findValue.GetType() != typeof(string))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                str        = (string)findValue;
                dwFindType = 0x80007;
                zero       = System.Security.Cryptography.X509Certificates.X509Utils.StringToUniPtr(str).DangerousGetHandle();
                goto Label_0703;

            case X509FindType.FindBySubjectDistinguishedName:
                if (findValue.GetType() != typeof(string))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                str           = (string)findValue;
                delegate2     = new FindProcDelegate(X509Certificate2Collection.FindSubjectDistinguishedNameCallback);
                dwKeyUsageBit = str;
                goto Label_0703;

            case X509FindType.FindByIssuerName:
                if (findValue.GetType() != typeof(string))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                str2          = (string)findValue;
                dwFindType    = 0x80004;
                invalidHandle = System.Security.Cryptography.X509Certificates.X509Utils.StringToUniPtr(str2);
                zero          = invalidHandle.DangerousGetHandle();
                goto Label_0703;

            case X509FindType.FindByIssuerDistinguishedName:
                if (findValue.GetType() != typeof(string))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                str2          = (string)findValue;
                delegate2     = new FindProcDelegate(X509Certificate2Collection.FindIssuerDistinguishedNameCallback);
                dwKeyUsageBit = str2;
                goto Label_0703;

            case X509FindType.FindBySerialNumber:
            {
                if (findValue.GetType() != typeof(string))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                delegate2 = new FindProcDelegate(X509Certificate2Collection.FindSerialNumberCallback);
                delegate3 = new FindProcDelegate(X509Certificate2Collection.FindSerialNumberCallback);
                BigInt num2 = new BigInt();
                num2.FromHexadecimal((string)findValue);
                dwKeyUsageBit = num2.ToByteArray();
                num2.FromDecimal((string)findValue);
                obj3 = num2.ToByteArray();
                goto Label_0703;
            }

            case X509FindType.FindByTimeValid:
                if (findValue.GetType() != typeof(DateTime))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                *((long *)&filetime) = ((DateTime)findValue).ToFileTime();
                delegate2            = new FindProcDelegate(X509Certificate2Collection.FindTimeValidCallback);
                dwKeyUsageBit        = filetime;
                goto Label_0703;

            case X509FindType.FindByTimeNotYetValid:
                if (findValue.GetType() != typeof(DateTime))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                *((long *)&filetime) = ((DateTime)findValue).ToFileTime();
                delegate2            = new FindProcDelegate(X509Certificate2Collection.FindTimeNotBeforeCallback);
                dwKeyUsageBit        = filetime;
                goto Label_0703;

            case X509FindType.FindByTimeExpired:
                if (findValue.GetType() != typeof(DateTime))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                *((long *)&filetime) = ((DateTime)findValue).ToFileTime();
                delegate2            = new FindProcDelegate(X509Certificate2Collection.FindTimeNotAfterCallback);
                dwKeyUsageBit        = filetime;
                goto Label_0703;

            case X509FindType.FindByTemplateName:
                if (findValue.GetType() != typeof(string))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                dwKeyUsageBit = (string)findValue;
                delegate2     = new FindProcDelegate(X509Certificate2Collection.FindTemplateNameCallback);
                goto Label_0703;

            case X509FindType.FindByApplicationPolicy:
                if (findValue.GetType() != typeof(string))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                keyValue = System.Security.Cryptography.X509Certificates.X509Utils.FindOidInfo(2, (string)findValue, System.Security.Cryptography.OidGroup.Policy);
                if (keyValue == null)
                {
                    keyValue = (string)findValue;
                    System.Security.Cryptography.X509Certificates.X509Utils.ValidateOidValue(keyValue);
                }
                dwKeyUsageBit = keyValue;
                delegate2     = new FindProcDelegate(X509Certificate2Collection.FindApplicationPolicyCallback);
                goto Label_0703;

            case X509FindType.FindByCertificatePolicy:
                if (findValue.GetType() != typeof(string))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                keyValue = System.Security.Cryptography.X509Certificates.X509Utils.FindOidInfo(2, (string)findValue, System.Security.Cryptography.OidGroup.Policy);
                if (keyValue == null)
                {
                    keyValue = (string)findValue;
                    System.Security.Cryptography.X509Certificates.X509Utils.ValidateOidValue(keyValue);
                }
                dwKeyUsageBit = keyValue;
                delegate2     = new FindProcDelegate(X509Certificate2Collection.FindCertificatePolicyCallback);
                goto Label_0703;

            case X509FindType.FindByExtension:
                if (findValue.GetType() != typeof(string))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                keyValue = System.Security.Cryptography.X509Certificates.X509Utils.FindOidInfo(2, (string)findValue, System.Security.Cryptography.OidGroup.ExtensionOrAttribute);
                if (keyValue == null)
                {
                    keyValue = (string)findValue;
                    System.Security.Cryptography.X509Certificates.X509Utils.ValidateOidValue(keyValue);
                }
                dwKeyUsageBit = keyValue;
                delegate2     = new FindProcDelegate(X509Certificate2Collection.FindExtensionCallback);
                goto Label_0703;

            case X509FindType.FindByKeyUsage:
            {
                if (!(findValue.GetType() == typeof(string)))
                {
                    if (findValue.GetType() == typeof(X509KeyUsageFlags))
                    {
                        dwKeyUsageBit = findValue;
                    }
                    else
                    {
                        if (!(findValue.GetType() == typeof(uint)) && !(findValue.GetType() == typeof(int)))
                        {
                            throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindType"));
                        }
                        dwKeyUsageBit = findValue;
                    }
                    goto Label_06A2;
                }
                CAPIBase.KEY_USAGE_STRUCT[] key_usage_structArray = new CAPIBase.KEY_USAGE_STRUCT[] { new CAPIBase.KEY_USAGE_STRUCT("DigitalSignature", 0x80), new CAPIBase.KEY_USAGE_STRUCT("NonRepudiation", 0x40), new CAPIBase.KEY_USAGE_STRUCT("KeyEncipherment", 0x20), new CAPIBase.KEY_USAGE_STRUCT("DataEncipherment", 0x10), new CAPIBase.KEY_USAGE_STRUCT("KeyAgreement", 8), new CAPIBase.KEY_USAGE_STRUCT("KeyCertSign", 4), new CAPIBase.KEY_USAGE_STRUCT("CrlSign", 2), new CAPIBase.KEY_USAGE_STRUCT("EncipherOnly", 1), new CAPIBase.KEY_USAGE_STRUCT("DecipherOnly", 0x8000) };
                for (uint i = 0; i < key_usage_structArray.Length; i++)
                {
                    if (string.Compare(key_usage_structArray[i].pwszKeyUsage, (string)findValue, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        dwKeyUsageBit = key_usage_structArray[i].dwKeyUsageBit;
                        break;
                    }
                }
                break;
            }

            case X509FindType.FindBySubjectKeyIdentifier:
                if (findValue.GetType() != typeof(string))
                {
                    throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindValue"));
                }
                dwKeyUsageBit = System.Security.Cryptography.X509Certificates.X509Utils.DecodeHexString((string)findValue);
                delegate2     = new FindProcDelegate(X509Certificate2Collection.FindSubjectKeyIdentifierCallback);
                goto Label_0703;

            default:
                throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindType"));
            }
            if (dwKeyUsageBit == null)
            {
                throw new CryptographicException(SR.GetString("Cryptography_X509_InvalidFindType"));
            }
Label_06A2:
            delegate2 = new FindProcDelegate(X509Certificate2Collection.FindKeyUsageCallback);
Label_0703:
            handle2 = CAPI.CertOpenStore(new IntPtr(2L), 0x10001, IntPtr.Zero, 0x2200, null);
            if ((handle2 == null) || handle2.IsInvalid)
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            FindByCert(safeSourceStoreHandle, dwFindType, zero, validOnly, delegate2, delegate3, dwKeyUsageBit, obj3, handle2);
            invalidHandle.Dispose();
            return(handle2);
        }