internal static bool GetPrivateKeyInfo(System.Security.Cryptography.SafeCertContextHandle safeCertContext, ref CspParameters parameters)
        {
            SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle;
            uint pcbData = 0;

            if (!CAPISafe.CertGetCertificateContextProperty(safeCertContext, 2, invalidHandle, ref pcbData))
            {
                if (Marshal.GetLastWin32Error() != -2146885628)
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                return(false);
            }
            invalidHandle = CAPI.LocalAlloc(0, new IntPtr((long)pcbData));
            if (!CAPISafe.CertGetCertificateContextProperty(safeCertContext, 2, invalidHandle, ref pcbData))
            {
                if (Marshal.GetLastWin32Error() != -2146885628)
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                return(false);
            }
            CAPIBase.CRYPT_KEY_PROV_INFO crypt_key_prov_info = (CAPIBase.CRYPT_KEY_PROV_INFO)Marshal.PtrToStructure(invalidHandle.DangerousGetHandle(), typeof(CAPIBase.CRYPT_KEY_PROV_INFO));
            parameters.ProviderName     = crypt_key_prov_info.pwszProvName;
            parameters.KeyContainerName = crypt_key_prov_info.pwszContainerName;
            parameters.ProviderType     = (int)crypt_key_prov_info.dwProvType;
            parameters.KeyNumber        = (int)crypt_key_prov_info.dwKeySpec;
            parameters.Flags            = ((crypt_key_prov_info.dwFlags & 0x20) == 0x20) ? CspProviderFlags.UseMachineKeyStore : CspProviderFlags.NoFlags;
            invalidHandle.Dispose();
            return(true);
        }
예제 #2
0
        internal static unsafe X509Certificate2 CreateDummyCertificate(CspParameters parameters)
        {
            System.Security.Cryptography.SafeCertContextHandle invalidHandle = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
            SafeCryptProvHandle hCryptProv = SafeCryptProvHandle.InvalidHandle;
            uint dwFlags = 0U;

            if ((parameters.Flags & CspProviderFlags.UseMachineKeyStore) != CspProviderFlags.NoFlags)
            {
                dwFlags |= 32U;
            }
            if ((parameters.Flags & CspProviderFlags.UseDefaultKeyContainer) != CspProviderFlags.NoFlags)
            {
                dwFlags |= 4026531840U;
            }
            if ((parameters.Flags & CspProviderFlags.NoPrompt) != CspProviderFlags.NoFlags)
            {
                dwFlags |= 64U;
            }
            if (!CAPI.CryptAcquireContext(ref hCryptProv, parameters.KeyContainerName, parameters.ProviderName, (uint)parameters.ProviderType, dwFlags))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            CAPI.CRYPT_KEY_PROV_INFO cryptKeyProvInfo = new CAPI.CRYPT_KEY_PROV_INFO();
            cryptKeyProvInfo.pwszProvName      = parameters.ProviderName;
            cryptKeyProvInfo.pwszContainerName = parameters.KeyContainerName;
            cryptKeyProvInfo.dwProvType        = (uint)parameters.ProviderType;
            cryptKeyProvInfo.dwKeySpec         = (uint)parameters.KeyNumber;
            cryptKeyProvInfo.dwFlags           = (parameters.Flags & CspProviderFlags.UseMachineKeyStore) == CspProviderFlags.UseMachineKeyStore ? 32U : 0U;
            SafeLocalAllocHandle localAllocHandle1 = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CRYPT_KEY_PROV_INFO))));

            Marshal.StructureToPtr((object)cryptKeyProvInfo, localAllocHandle1.DangerousGetHandle(), false);
            CAPI.CRYPT_ALGORITHM_IDENTIFIER algorithmIdentifier = new CAPI.CRYPT_ALGORITHM_IDENTIFIER();
            algorithmIdentifier.pszObjId = "1.3.14.3.2.29";
            SafeLocalAllocHandle localAllocHandle2 = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER))));

            Marshal.StructureToPtr((object)algorithmIdentifier, localAllocHandle2.DangerousGetHandle(), false);
            X500DistinguishedName distinguishedName = new X500DistinguishedName("cn=CMS Signer Dummy Certificate");

            System.Security.Cryptography.SafeCertContextHandle selfSignCertificate;

            fixed(byte *numPtr = distinguishedName.RawData)
            selfSignCertificate = CAPI.CAPIUnsafe.CertCreateSelfSignCertificate(hCryptProv, new IntPtr((void *)&new CAPI.CRYPTOAPI_BLOB()
            {
                cbData = (uint)distinguishedName.RawData.Length,
                pbData = new IntPtr((void *)numPtr)
            }), 1U, localAllocHandle1.DangerousGetHandle(), localAllocHandle2.DangerousGetHandle(), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

            Marshal.DestroyStructure(localAllocHandle1.DangerousGetHandle(), typeof(CAPI.CRYPT_KEY_PROV_INFO));
            localAllocHandle1.Dispose();
            Marshal.DestroyStructure(localAllocHandle2.DangerousGetHandle(), typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER));
            localAllocHandle2.Dispose();
            if (selfSignCertificate == null || selfSignCertificate.IsInvalid)
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            X509Certificate2 x509Certificate2 = new X509Certificate2(selfSignCertificate.DangerousGetHandle());

            selfSignCertificate.Dispose();
            return(x509Certificate2);
        }
        internal static unsafe X509Certificate2 CreateDummyCertificate(CspParameters parameters)
        {
            System.Security.Cryptography.SafeCertContextHandle invalidHandle = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
            System.Security.Cryptography.SafeCryptProvHandle   hCryptProv    = System.Security.Cryptography.SafeCryptProvHandle.InvalidHandle;
            uint dwFlags = 0;

            if ((parameters.Flags & CspProviderFlags.UseMachineKeyStore) != CspProviderFlags.NoFlags)
            {
                dwFlags |= 0x20;
            }
            if ((parameters.Flags & CspProviderFlags.UseDefaultKeyContainer) != CspProviderFlags.NoFlags)
            {
                dwFlags |= 0xf0000000;
            }
            if ((parameters.Flags & CspProviderFlags.NoPrompt) != CspProviderFlags.NoFlags)
            {
                dwFlags |= 0x40;
            }
            if (!System.Security.Cryptography.CAPI.CryptAcquireContext(ref hCryptProv, parameters.KeyContainerName, parameters.ProviderName, (uint)parameters.ProviderType, dwFlags))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            System.Security.Cryptography.CAPI.CRYPT_KEY_PROV_INFO structure = new System.Security.Cryptography.CAPI.CRYPT_KEY_PROV_INFO {
                pwszProvName      = parameters.ProviderName,
                pwszContainerName = parameters.KeyContainerName,
                dwProvType        = (uint)parameters.ProviderType,
                dwKeySpec         = (uint)parameters.KeyNumber,
                dwFlags           = ((parameters.Flags & CspProviderFlags.UseMachineKeyStore) == CspProviderFlags.UseMachineKeyStore) ? 0x20 : 0
            };
            System.Security.Cryptography.SafeLocalAllocHandle handle3 = System.Security.Cryptography.CAPI.LocalAlloc(0x40, new IntPtr(Marshal.SizeOf(typeof(System.Security.Cryptography.CAPI.CRYPT_KEY_PROV_INFO))));
            Marshal.StructureToPtr(structure, handle3.DangerousGetHandle(), false);
            System.Security.Cryptography.CAPI.CRYPT_ALGORITHM_IDENTIFIER crypt_algorithm_identifier = new System.Security.Cryptography.CAPI.CRYPT_ALGORITHM_IDENTIFIER {
                pszObjId = "1.3.14.3.2.29"
            };
            System.Security.Cryptography.SafeLocalAllocHandle handle4 = System.Security.Cryptography.CAPI.LocalAlloc(0x40, new IntPtr(Marshal.SizeOf(typeof(System.Security.Cryptography.CAPI.CRYPT_ALGORITHM_IDENTIFIER))));
            Marshal.StructureToPtr(crypt_algorithm_identifier, handle4.DangerousGetHandle(), false);
            X500DistinguishedName name = new X500DistinguishedName("cn=CMS Signer Dummy Certificate");

            fixed(byte *numRef = name.RawData)
            {
                System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB cryptoapi_blob = new System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB {
                    cbData = (uint)name.RawData.Length,
                    pbData = new IntPtr((void *)numRef)
                };
                invalidHandle = System.Security.Cryptography.CAPI.CAPIUnsafe.CertCreateSelfSignCertificate(hCryptProv, new IntPtr((void *)&cryptoapi_blob), 1, handle3.DangerousGetHandle(), handle4.DangerousGetHandle(), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            }

            Marshal.DestroyStructure(handle3.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CRYPT_KEY_PROV_INFO));
            handle3.Dispose();
            Marshal.DestroyStructure(handle4.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CRYPT_ALGORITHM_IDENTIFIER));
            handle4.Dispose();
            if ((invalidHandle == null) || invalidHandle.IsInvalid)
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            X509Certificate2 certificate = new X509Certificate2(invalidHandle.DangerousGetHandle());

            invalidHandle.Dispose();
            return(certificate);
        }
예제 #4
0
        private static unsafe int FindApplicationPolicyCallback(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData)
        {
            string strA = (string)pvCallbackData;

            if (strA.Length != 0)
            {
                IntPtr ptr  = safeCertContextHandle.DangerousGetHandle();
                int    num  = 0;
                uint   num2 = 0;
                SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle;
                if (!CAPISafe.CertGetValidUsages(1, new IntPtr((void *)&ptr), new IntPtr((void *)&num), invalidHandle, new IntPtr((void *)&num2)))
                {
                    return(1);
                }
                invalidHandle = CAPI.LocalAlloc(0, new IntPtr((long)num2));
                if (!CAPISafe.CertGetValidUsages(1, new IntPtr((void *)&ptr), new IntPtr((void *)&num), invalidHandle, new IntPtr((void *)&num2)))
                {
                    return(1);
                }
                if (num == -1)
                {
                    return(0);
                }
                for (int i = 0; i < num; i++)
                {
                    string strB = Marshal.PtrToStringAnsi(Marshal.ReadIntPtr(new IntPtr(((long)invalidHandle.DangerousGetHandle()) + (i * Marshal.SizeOf(typeof(IntPtr))))));
                    if (string.Compare(strA, strB, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return(0);
                    }
                }
            }
            return(1);
        }
        private static void SetPrivateKeyProperty(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, ICspAsymmetricAlgorithm asymmetricAlgorithm)
        {
            SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle;

            if (asymmetricAlgorithm != null)
            {
                CAPIBase.CRYPT_KEY_PROV_INFO structure = new CAPIBase.CRYPT_KEY_PROV_INFO {
                    pwszContainerName = asymmetricAlgorithm.CspKeyContainerInfo.KeyContainerName,
                    pwszProvName      = asymmetricAlgorithm.CspKeyContainerInfo.ProviderName,
                    dwProvType        = (uint)asymmetricAlgorithm.CspKeyContainerInfo.ProviderType,
                    dwFlags           = asymmetricAlgorithm.CspKeyContainerInfo.MachineKeyStore ? 0x20 : 0,
                    cProvParam        = 0,
                    rgProvParam       = IntPtr.Zero,
                    dwKeySpec         = (uint)asymmetricAlgorithm.CspKeyContainerInfo.KeyNumber
                };
                invalidHandle = CAPI.LocalAlloc(0x40, new IntPtr(Marshal.SizeOf(typeof(CAPIBase.CRYPT_KEY_PROV_INFO))));
                Marshal.StructureToPtr(structure, invalidHandle.DangerousGetHandle(), false);
            }
            try
            {
                if (!CAPI.CertSetCertificateContextProperty(safeCertContextHandle, 2, 0, invalidHandle))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (!invalidHandle.IsInvalid)
                {
                    Marshal.DestroyStructure(invalidHandle.DangerousGetHandle(), typeof(CAPIBase.CRYPT_KEY_PROV_INFO));
                    invalidHandle.Dispose();
                }
            }
        }
        internal static unsafe X509Certificate2Collection GetCertificates(System.Security.Cryptography.SafeCryptMsgHandle safeCryptMsgHandle)
        {
            uint num  = 0;
            uint num2 = (uint)Marshal.SizeOf(typeof(uint));
            X509Certificate2Collection certificates = new X509Certificate2Collection();

            if (!System.Security.Cryptography.CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle, 11, 0, new IntPtr((void *)&num), new IntPtr((void *)&num2)))
            {
                checkErr(Marshal.GetLastWin32Error());
            }
            for (uint i = 0; i < num; i++)
            {
                uint cbData = 0;
                System.Security.Cryptography.SafeLocalAllocHandle invalidHandle = System.Security.Cryptography.SafeLocalAllocHandle.InvalidHandle;
                GetParam(safeCryptMsgHandle, 12, i, out invalidHandle, out cbData);
                if (cbData > 0)
                {
                    System.Security.Cryptography.SafeCertContextHandle handle2 = System.Security.Cryptography.CAPI.CAPISafe.CertCreateCertificateContext(0x10001, invalidHandle, cbData);
                    if ((handle2 == null) || handle2.IsInvalid)
                    {
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    }
                    certificates.Add(new X509Certificate2(handle2.DangerousGetHandle()));
                    handle2.Dispose();
                }
            }
            return(certificates);
        }
예제 #7
0
        private static unsafe int FindCertificatePolicyCallback(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData)
        {
            string strA = (string)pvCallbackData;

            if (strA.Length != 0)
            {
                CAPIBase.CERT_CONTEXT cert_context = *((CAPIBase.CERT_CONTEXT *)safeCertContextHandle.DangerousGetHandle());
                CAPIBase.CERT_INFO    cert_info    = (CAPIBase.CERT_INFO)Marshal.PtrToStructure(cert_context.pCertInfo, typeof(CAPIBase.CERT_INFO));
                IntPtr ptr = CAPISafe.CertFindExtension("2.5.29.32", cert_info.cExtension, cert_info.rgExtension);
                if (ptr == IntPtr.Zero)
                {
                    return(1);
                }
                CAPIBase.CERT_EXTENSION cert_extension = (CAPIBase.CERT_EXTENSION)Marshal.PtrToStructure(ptr, typeof(CAPIBase.CERT_EXTENSION));
                byte[] destination = new byte[cert_extension.Value.cbData];
                Marshal.Copy(cert_extension.Value.pbData, destination, 0, destination.Length);
                uint cbDecodedValue = 0;
                SafeLocalAllocHandle decodedValue = null;
                if (CAPI.DecodeObject(new IntPtr(0x10L), destination, out decodedValue, out cbDecodedValue))
                {
                    CAPIBase.CERT_POLICIES_INFO cert_policies_info = (CAPIBase.CERT_POLICIES_INFO)Marshal.PtrToStructure(decodedValue.DangerousGetHandle(), typeof(CAPIBase.CERT_POLICIES_INFO));
                    for (int i = 0; i < cert_policies_info.cPolicyInfo; i++)
                    {
                        IntPtr ptr2 = new IntPtr(((long)cert_policies_info.rgPolicyInfo) + (i * Marshal.SizeOf(typeof(CAPIBase.CERT_POLICY_INFO))));
                        CAPIBase.CERT_POLICY_INFO cert_policy_info = (CAPIBase.CERT_POLICY_INFO)Marshal.PtrToStructure(ptr2, typeof(CAPIBase.CERT_POLICY_INFO));
                        if (string.Compare(strA, cert_policy_info.pszPolicyIdentifier, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            return(0);
                        }
                    }
                }
            }
            return(1);
        }
예제 #8
0
        internal static unsafe 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");
            }
            CAPI.CERT_CHAIN_POLICY_PARA   pPolicyPara   = new CAPI.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_PARA)));
            CAPI.CERT_CHAIN_POLICY_STATUS pPolicyStatus = new CAPI.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_STATUS)));
            SafeCertChainHandle           invalidHandle = SafeCertChainHandle.InvalidHandle;
            int num = X509Utils.BuildChain(new IntPtr(0L), pCertContext, extraStore, applicationPolicy, certificatePolicy, revocationMode, revocationFlag, verificationTime, timeout, ref invalidHandle);

            if (num != 0)
            {
                return(num);
            }
            if (!CAPI.CAPISafe.CertVerifyCertificateChainPolicy(pszPolicy, invalidHandle, ref pPolicyPara, out pPolicyStatus))
            {
                return(Marshal.GetHRForLastWin32Error());
            }
            if (pdwErrorStatus != IntPtr.Zero)
            {
                *(int *)(void *)pdwErrorStatus = (int)pPolicyStatus.dwError;
            }
            return((int)pPolicyStatus.dwError != 0 ? 1 : 0);
        }
예제 #9
0
        private static int FindSubjectKeyIdentifierCallback(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData)
        {
            SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle;
            uint pcbData = 0;

            if (!CAPISafe.CertGetCertificateContextProperty(safeCertContextHandle, 20, invalidHandle, ref pcbData))
            {
                return(1);
            }
            invalidHandle = CAPI.LocalAlloc(0, new IntPtr((long)pcbData));
            if (!CAPISafe.CertGetCertificateContextProperty(safeCertContextHandle, 20, invalidHandle, ref pcbData))
            {
                return(1);
            }
            byte[] buffer = (byte[])pvCallbackData;
            if (buffer.Length != pcbData)
            {
                return(1);
            }
            byte[] destination = new byte[pcbData];
            Marshal.Copy(invalidHandle.DangerousGetHandle(), destination, 0, destination.Length);
            invalidHandle.Dispose();
            for (uint i = 0; i < pcbData; i++)
            {
                if (buffer[i] != destination[i])
                {
                    return(1);
                }
            }
            return(0);
        }
예제 #10
0
        internal static unsafe X509Certificate2Collection GetCertificates(SafeCryptMsgHandle safeCryptMsgHandle)
        {
            uint num1 = 0U;
            uint num2 = (uint)Marshal.SizeOf(typeof(uint));
            X509Certificate2Collection certificate2Collection = new X509Certificate2Collection();

            if (!CAPI.CAPISafe.CryptMsgGetParam(safeCryptMsgHandle, 11U, 0U, new IntPtr((void *)&num1), new IntPtr((void *)&num2)))
            {
                PkcsUtils.checkErr(Marshal.GetLastWin32Error());
            }
            for (uint index = 0U; index < num1; ++index)
            {
                uint cbData = 0U;
                SafeLocalAllocHandle pvData = SafeLocalAllocHandle.InvalidHandle;
                PkcsUtils.GetParam(safeCryptMsgHandle, 12U, index, out pvData, out cbData);
                if (cbData > 0U)
                {
                    System.Security.Cryptography.SafeCertContextHandle certificateContext = CAPI.CAPISafe.CertCreateCertificateContext(65537U, pvData, cbData);
                    if (certificateContext == null || certificateContext.IsInvalid)
                    {
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    }
                    certificate2Collection.Add(new X509Certificate2(certificateContext.DangerousGetHandle()));
                    certificateContext.Dispose();
                }
            }
            return(certificate2Collection);
        }
예제 #11
0
 private static int FindSubjectDistinguishedNameCallback(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData)
 {
     if (string.Compare(CAPI.GetCertNameInfo(safeCertContextHandle, 0, 2), (string)pvCallbackData, StringComparison.OrdinalIgnoreCase) != 0)
     {
         return(1);
     }
     return(0);
 }
예제 #12
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);
            }
        }
예제 #13
0
 private static unsafe int FindTimeValidCallback(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData)
 {
     System.Runtime.InteropServices.ComTypes.FILETIME pTimeToVerify = (System.Runtime.InteropServices.ComTypes.FILETIME)pvCallbackData;
     CAPIBase.CERT_CONTEXT cert_context = *((CAPIBase.CERT_CONTEXT *)safeCertContextHandle.DangerousGetHandle());
     if (CAPISafe.CertVerifyTimeValidity(ref pTimeToVerify, cert_context.pCertInfo) == 0)
     {
         return(0);
     }
     return(1);
 }
예제 #14
0
 private static unsafe int FindExtensionCallback(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData)
 {
     CAPIBase.CERT_CONTEXT cert_context = *((CAPIBase.CERT_CONTEXT *)safeCertContextHandle.DangerousGetHandle());
     CAPIBase.CERT_INFO    cert_info    = (CAPIBase.CERT_INFO)Marshal.PtrToStructure(cert_context.pCertInfo, typeof(CAPIBase.CERT_INFO));
     if (CAPISafe.CertFindExtension((string)pvCallbackData, cert_info.cExtension, cert_info.rgExtension) == IntPtr.Zero)
     {
         return(1);
     }
     return(0);
 }
예제 #15
0
        private static unsafe int FindTemplateNameCallback(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData)
        {
            IntPtr zero = IntPtr.Zero;
            IntPtr ptr  = IntPtr.Zero;

            CAPIBase.CERT_CONTEXT cert_context = *((CAPIBase.CERT_CONTEXT *)safeCertContextHandle.DangerousGetHandle());
            CAPIBase.CERT_INFO    cert_info    = (CAPIBase.CERT_INFO)Marshal.PtrToStructure(cert_context.pCertInfo, typeof(CAPIBase.CERT_INFO));
            zero = CAPISafe.CertFindExtension("1.3.6.1.4.1.311.20.2", cert_info.cExtension, cert_info.rgExtension);
            ptr  = CAPISafe.CertFindExtension("1.3.6.1.4.1.311.21.7", cert_info.cExtension, cert_info.rgExtension);
            if ((zero != IntPtr.Zero) || (ptr != IntPtr.Zero))
            {
                if (zero != IntPtr.Zero)
                {
                    CAPIBase.CERT_EXTENSION cert_extension = (CAPIBase.CERT_EXTENSION)Marshal.PtrToStructure(zero, typeof(CAPIBase.CERT_EXTENSION));
                    byte[] destination = new byte[cert_extension.Value.cbData];
                    Marshal.Copy(cert_extension.Value.pbData, destination, 0, destination.Length);
                    uint cbDecodedValue = 0;
                    SafeLocalAllocHandle decodedValue = null;
                    if (CAPI.DecodeObject(new IntPtr(0x18L), destination, out decodedValue, out cbDecodedValue))
                    {
                        CAPIBase.CERT_NAME_VALUE cert_name_value = (CAPIBase.CERT_NAME_VALUE)Marshal.PtrToStructure(decodedValue.DangerousGetHandle(), typeof(CAPIBase.CERT_NAME_VALUE));
                        if (string.Compare(Marshal.PtrToStringUni(cert_name_value.Value.pbData), (string)pvCallbackData, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            return(0);
                        }
                    }
                }
                if (ptr != IntPtr.Zero)
                {
                    CAPIBase.CERT_EXTENSION cert_extension2 = (CAPIBase.CERT_EXTENSION)Marshal.PtrToStructure(ptr, typeof(CAPIBase.CERT_EXTENSION));
                    byte[] buffer2 = new byte[cert_extension2.Value.cbData];
                    Marshal.Copy(cert_extension2.Value.pbData, buffer2, 0, buffer2.Length);
                    uint num2 = 0;
                    SafeLocalAllocHandle handle2 = null;
                    if (CAPI.DecodeObject(new IntPtr(0x40L), buffer2, out handle2, out num2))
                    {
                        CAPIBase.CERT_TEMPLATE_EXT cert_template_ext = (CAPIBase.CERT_TEMPLATE_EXT)Marshal.PtrToStructure(handle2.DangerousGetHandle(), typeof(CAPIBase.CERT_TEMPLATE_EXT));
                        string strB = System.Security.Cryptography.X509Certificates.X509Utils.FindOidInfo(2, (string)pvCallbackData, System.Security.Cryptography.OidGroup.Template);
                        if (strB == null)
                        {
                            strB = (string)pvCallbackData;
                        }
                        if (string.Compare(cert_template_ext.pszObjId, strB, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            return(0);
                        }
                    }
                }
            }
            return(1);
        }
        private static unsafe void SetFriendlyNameExtendedProperty(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, string name)
        {
            SafeLocalAllocHandle handle = System.Security.Cryptography.X509Certificates.X509Utils.StringToUniPtr(name);

            using (handle)
            {
                CAPIBase.CRYPTOAPI_BLOB cryptoapi_blob = new CAPIBase.CRYPTOAPI_BLOB {
                    cbData = (uint)(2 * (name.Length + 1)),
                    pbData = handle.DangerousGetHandle()
                };
                if (!CAPI.CertSetCertificateContextProperty(safeCertContextHandle, 11, 0, new IntPtr((void *)&cryptoapi_blob)))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }
        }
예제 #17
0
        private static unsafe int FindKeyUsageCallback(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData)
        {
            CAPIBase.CERT_CONTEXT cert_context = *((CAPIBase.CERT_CONTEXT *)safeCertContextHandle.DangerousGetHandle());
            uint num = 0;

            if (!CAPISafe.CertGetIntendedKeyUsage(0x10001, cert_context.pCertInfo, new IntPtr((void *)&num), 4))
            {
                return(0);
            }
            uint num2 = Convert.ToUInt32(pvCallbackData, null);

            if ((num & num2) == num2)
            {
                return(0);
            }
            return(1);
        }
        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);
        }
예제 #19
0
        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);
        }
 public override void Reset()
 {
     this.m_version            = 0;
     this.m_notBefore          = DateTime.MinValue;
     this.m_notAfter           = DateTime.MinValue;
     this.m_privateKey         = null;
     this.m_publicKey          = null;
     this.m_extensions         = null;
     this.m_signatureAlgorithm = null;
     this.m_subjectName        = null;
     this.m_issuerName         = null;
     if (!this.m_safeCertContext.IsInvalid)
     {
         this.m_safeCertContext.Dispose();
         this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     }
     base.Reset();
 }
예제 #21
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);
        }
예제 #22
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());
             }
         }
     }
 }
 internal unsafe X509ExtensionCollection(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle)
 {
     this.m_list = new ArrayList();
     using (System.Security.Cryptography.SafeCertContextHandle handle = CAPI.CertDuplicateCertificateContext(safeCertContextHandle))
     {
         CAPIBase.CERT_CONTEXT cert_context = *((CAPIBase.CERT_CONTEXT *)handle.DangerousGetHandle());
         CAPIBase.CERT_INFO    cert_info    = (CAPIBase.CERT_INFO)Marshal.PtrToStructure(cert_context.pCertInfo, typeof(CAPIBase.CERT_INFO));
         uint   cExtension  = cert_info.cExtension;
         IntPtr rgExtension = cert_info.rgExtension;
         for (uint i = 0; i < cExtension; i++)
         {
             X509Extension asnEncodedData = new X509Extension(new IntPtr(((long)rgExtension) + (i * Marshal.SizeOf(typeof(CAPIBase.CERT_EXTENSION)))));
             X509Extension extension2     = CryptoConfig.CreateFromName(asnEncodedData.Oid.Value) as X509Extension;
             if (extension2 != null)
             {
                 extension2.CopyFrom(asnEncodedData);
                 asnEncodedData = extension2;
             }
             this.Add(asnEncodedData);
         }
     }
 }
예제 #24
0
        private static unsafe int FindSerialNumberCallback(System.Security.Cryptography.SafeCertContextHandle safeCertContextHandle, object pvCallbackData)
        {
            CAPIBase.CERT_CONTEXT cert_context = *((CAPIBase.CERT_CONTEXT *)safeCertContextHandle.DangerousGetHandle());
            CAPIBase.CERT_INFO    cert_info    = (CAPIBase.CERT_INFO)Marshal.PtrToStructure(cert_context.pCertInfo, typeof(CAPIBase.CERT_INFO));
            byte[] destination = new byte[cert_info.SerialNumber.cbData];
            Marshal.Copy(cert_info.SerialNumber.pbData, destination, 0, destination.Length);
            int hexArraySize = System.Security.Cryptography.X509Certificates.X509Utils.GetHexArraySize(destination);

            byte[] buffer2 = (byte[])pvCallbackData;
            if (buffer2.Length != hexArraySize)
            {
                return(1);
            }
            for (int i = 0; i < buffer2.Length; i++)
            {
                if (buffer2[i] != destination[i])
                {
                    return(1);
                }
            }
            return(0);
        }
예제 #25
0
        private static void DisplayX509Certificate(System.Security.Cryptography.SafeCertContextHandle safeCertContext, IntPtr hwndParent)
        {
            System.Security.Cryptography.CAPI.CRYPTUI_VIEWCERTIFICATE_STRUCTW cryptui_viewcertificate_structw;
            if (safeCertContext.IsInvalid)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_InvalidHandle"), "safeCertContext");
            }
            int num = 0;

            cryptui_viewcertificate_structw = new System.Security.Cryptography.CAPI.CRYPTUI_VIEWCERTIFICATE_STRUCTW {
                dwSize             = Marshal.SizeOf(cryptui_viewcertificate_structw),
                hwndParent         = hwndParent,
                dwFlags            = 0,
                szTitle            = null,
                pCertContext       = safeCertContext.DangerousGetHandle(),
                rgszPurposes       = IntPtr.Zero,
                cPurposes          = 0,
                pCryptProviderData = IntPtr.Zero,
                fpCryptProviderDataTrustedUsage = false,
                idxSigner        = 0,
                idxCert          = 0,
                fCounterSigner   = false,
                idxCounterSigner = 0,
                cStores          = 0,
                rghStores        = IntPtr.Zero,
                cPropSheetPages  = 0,
                rgPropSheetPages = IntPtr.Zero,
                nStartPage       = 0
            };
            if (!System.Security.Cryptography.CAPI.CryptUIDlgViewCertificateW(cryptui_viewcertificate_structw, IntPtr.Zero))
            {
                num = Marshal.GetLastWin32Error();
            }
            if ((num != 0) && (num != 0x4c7))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
        }
 public override void Import(string fileName)
 {
     this.Reset();
     base.Import(fileName);
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }
 public override void Import(byte[] rawData)
 {
     this.Reset();
     base.Import(rawData);
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }
        private static SafeBCryptKeyHandle ImportPublicKeyInfo(SafeCertContextHandle certContext)
        {
#if NETNATIVE
            // CryptImportPublicKeyInfoEx2() not in the UWP api list.
            throw new PlatformNotSupportedException();
#else
            unsafe
            {
                SafeBCryptKeyHandle bCryptKeyHandle;
                bool mustRelease = false;
                certContext.DangerousAddRef(ref mustRelease);
                try
                {
                    unsafe
                    {
                        bool success = Interop.crypt32.CryptImportPublicKeyInfoEx2(CertEncodingType.X509_ASN_ENCODING, &(certContext.CertContext->pCertInfo->SubjectPublicKeyInfo), 0, null, out bCryptKeyHandle);
                        if (!success)
                            throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
                        return bCryptKeyHandle;
                    }
                }
                finally
                {
                    if (mustRelease)
                        certContext.DangerousRelease();
                }
            }
#endif //NETNATIVE
        }
예제 #29
0
 internal static System.Security.Cryptography.SafeCertContextHandle GetCertContext(X509Certificate2 certificate)
 {
     System.Security.Cryptography.SafeCertContextHandle certContextHandle = CAPI.CertDuplicateCertificateContext(certificate.Handle);
     GC.KeepAlive((object)certificate);
     return(certContextHandle);
 }
        internal static unsafe System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO CreateSignerEncodeInfo(CmsSigner signer, bool silent)
        {
            System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO cmsg_signer_encode_info = new System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO(Marshal.SizeOf(typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO)));
            System.Security.Cryptography.SafeCryptProvHandle          invalidHandle           = System.Security.Cryptography.SafeCryptProvHandle.InvalidHandle;
            uint pdwKeySpec       = 0;
            bool pfCallerFreeProv = false;

            cmsg_signer_encode_info.HashAlgorithm.pszObjId = signer.DigestAlgorithm.Value;
            if (string.Compare(signer.Certificate.PublicKey.Oid.Value, "1.2.840.10040.4.1", StringComparison.Ordinal) == 0)
            {
                cmsg_signer_encode_info.HashEncryptionAlgorithm.pszObjId = "1.2.840.10040.4.3";
            }
            cmsg_signer_encode_info.cAuthAttr    = (uint)signer.SignedAttributes.Count;
            cmsg_signer_encode_info.rgAuthAttr   = CreateCryptAttributes(signer.SignedAttributes);
            cmsg_signer_encode_info.cUnauthAttr  = (uint)signer.UnsignedAttributes.Count;
            cmsg_signer_encode_info.rgUnauthAttr = CreateCryptAttributes(signer.UnsignedAttributes);
            if (signer.SignerIdentifierType == SubjectIdentifierType.NoSignature)
            {
                cmsg_signer_encode_info.HashEncryptionAlgorithm.pszObjId = "1.3.6.1.5.5.7.6.2";
                cmsg_signer_encode_info.pCertInfo = IntPtr.Zero;
                cmsg_signer_encode_info.dwKeySpec = pdwKeySpec;
                if (!System.Security.Cryptography.CAPI.CryptAcquireContext(ref invalidHandle, (string)null, (string)null, 1, 0xf0000000))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                cmsg_signer_encode_info.hCryptProv = invalidHandle.DangerousGetHandle();
                GC.SuppressFinalize(invalidHandle);
                cmsg_signer_encode_info.SignerId.dwIdChoice = 1;
                X500DistinguishedName name = new X500DistinguishedName("CN=Dummy Signer")
                {
                    Oid = new Oid("1.3.6.1.4.1.311.21.9")
                };
                cmsg_signer_encode_info.SignerId.Value.IssuerSerialNumber.Issuer.cbData = (uint)name.RawData.Length;
                System.Security.Cryptography.SafeLocalAllocHandle handle2 = System.Security.Cryptography.CAPI.LocalAlloc(0x40, new IntPtr((long)cmsg_signer_encode_info.SignerId.Value.IssuerSerialNumber.Issuer.cbData));
                Marshal.Copy(name.RawData, 0, handle2.DangerousGetHandle(), name.RawData.Length);
                cmsg_signer_encode_info.SignerId.Value.IssuerSerialNumber.Issuer.pbData = handle2.DangerousGetHandle();
                GC.SuppressFinalize(handle2);
                cmsg_signer_encode_info.SignerId.Value.IssuerSerialNumber.SerialNumber.cbData = 1;
                System.Security.Cryptography.SafeLocalAllocHandle handle3 = System.Security.Cryptography.CAPI.LocalAlloc(0x40, new IntPtr((long)cmsg_signer_encode_info.SignerId.Value.IssuerSerialNumber.SerialNumber.cbData));
                byte *handle = (byte *)handle3.DangerousGetHandle();
                handle[0] = 0;
                cmsg_signer_encode_info.SignerId.Value.IssuerSerialNumber.SerialNumber.pbData = handle3.DangerousGetHandle();
                GC.SuppressFinalize(handle3);
                return(cmsg_signer_encode_info);
            }
            System.Security.Cryptography.SafeCertContextHandle certContext = System.Security.Cryptography.X509Certificates.X509Utils.GetCertContext(signer.Certificate);
            if (!System.Security.Cryptography.CAPI.CAPISafe.CryptAcquireCertificatePrivateKey(certContext, silent ? 70 : 6, IntPtr.Zero, ref invalidHandle, ref pdwKeySpec, ref pfCallerFreeProv))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            cmsg_signer_encode_info.dwKeySpec  = pdwKeySpec;
            cmsg_signer_encode_info.hCryptProv = invalidHandle.DangerousGetHandle();
            GC.SuppressFinalize(invalidHandle);
            System.Security.Cryptography.CAPI.CERT_CONTEXT cert_context = *((System.Security.Cryptography.CAPI.CERT_CONTEXT *)certContext.DangerousGetHandle());
            cmsg_signer_encode_info.pCertInfo = cert_context.pCertInfo;
            if (signer.SignerIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier)
            {
                uint pcbData = 0;
                System.Security.Cryptography.SafeLocalAllocHandle pvData = System.Security.Cryptography.SafeLocalAllocHandle.InvalidHandle;
                if (!System.Security.Cryptography.CAPI.CAPISafe.CertGetCertificateContextProperty(certContext, 20, pvData, ref pcbData))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                if (pcbData <= 0)
                {
                    return(cmsg_signer_encode_info);
                }
                pvData = System.Security.Cryptography.CAPI.LocalAlloc(0x40, new IntPtr((long)pcbData));
                if (!System.Security.Cryptography.CAPI.CAPISafe.CertGetCertificateContextProperty(certContext, 20, pvData, ref pcbData))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                cmsg_signer_encode_info.SignerId.dwIdChoice         = 2;
                cmsg_signer_encode_info.SignerId.Value.KeyId.cbData = pcbData;
                cmsg_signer_encode_info.SignerId.Value.KeyId.pbData = pvData.DangerousGetHandle();
                GC.SuppressFinalize(pvData);
            }
            return(cmsg_signer_encode_info);
        }
 public override void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
 {
     this.Reset();
     base.Import(rawData, password, keyStorageFlags);
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }
 public X509Certificate2(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) : base(rawData, password, keyStorageFlags)
 {
     this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }
 public X509Certificate2(byte[] rawData, SecureString password) : base(rawData, password)
 {
     this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }
 public X509Certificate2(byte[] rawData, SecureString password) : base(rawData, password)
 {
     this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }
 public X509Certificate2(string fileName, string password) : base(fileName, password)
 {
     this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }
 public override void Reset()
 {
     this.m_version = 0;
     this.m_notBefore = DateTime.MinValue;
     this.m_notAfter = DateTime.MinValue;
     this.m_privateKey = null;
     this.m_publicKey = null;
     this.m_extensions = null;
     this.m_signatureAlgorithm = null;
     this.m_subjectName = null;
     this.m_issuerName = null;
     if (!this.m_safeCertContext.IsInvalid)
     {
         this.m_safeCertContext.Dispose();
         this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     }
     base.Reset();
 }
 public X509Certificate2(X509Certificate certificate) : base(certificate)
 {
     this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }
 protected X509Certificate2(SerializationInfo info, StreamingContext context) : base(info, context)
 {
     this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }
 public X509Certificate2()
 {
     this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
 }
 public override void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags)
 {
     this.Reset();
     base.Import(fileName, password, keyStorageFlags);
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }
 public X509Certificate2(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) : base(rawData, password, keyStorageFlags)
 {
     this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }
 public X509Certificate2(string fileName, string password) : base(fileName, password)
 {
     this.m_safeCertContext = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     this.m_safeCertContext = CAPI.CertDuplicateCertificateContext(base.Handle);
 }