Exemplo n.º 1
0
 private static uint OidToAlgorithmId(Oid oid)
 {
     using (SafeLocalAllocHandle oidHandle = X509Utils.StringToAnsiPtr(oid.Value))
     {
         CapiNative.CRYPT_OID_INFO oidInfo = CapiNative.CryptFindOIDInfo(CapiNative.CRYPT_OID_INFO_OID_KEY, oidHandle, 0);
         return(oidInfo.Algid);
     }
 }
Exemplo n.º 2
0
        internal static SafeLocalAllocHandle StringToUniPtr(string s)
        {
            byte[] arr = new byte[2 * (s.Length + 1)];
            Encoding.Unicode.GetBytes(s, 0, s.Length, arr, 0);
            SafeLocalAllocHandle pb = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(arr.Length));

            Marshal.Copy(arr, 0, pb.DangerousGetHandle(), arr.Length);
            return(pb);
        }
Exemplo n.º 3
0
        internal static SafeLocalAllocHandle StringToUniPtr(string s)
        {
            byte[] bytes = new byte[2 * (s.Length + 1)];
            Encoding.Unicode.GetBytes(s, 0, s.Length, bytes, 0);
            SafeLocalAllocHandle handle = CAPI.LocalAlloc(0, new IntPtr(bytes.Length));

            Marshal.Copy(bytes, 0, handle.DangerousGetHandle(), bytes.Length);
            return(handle);
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
0
        private void DecodeExtension()
        {
            uint cbDecoded = 0;
            SafeLocalAllocHandle decoded = null;

            if (Oid.Value == CAPI.szOID_BASIC_CONSTRAINTS)
            {
                bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_BASIC_CONSTRAINTS),
                                                m_rawData,
                                                out decoded,
                                                out cbDecoded);
                if (result == false)
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }

                CAPI.CERT_BASIC_CONSTRAINTS_INFO pBasicConstraints = (CAPI.CERT_BASIC_CONSTRAINTS_INFO)Marshal.PtrToStructure(decoded.DangerousGetHandle(),
                                                                                                                              typeof(CAPI.CERT_BASIC_CONSTRAINTS_INFO));

                // take the first byte.
                byte[] isCA = new byte[1];
                Marshal.Copy(pBasicConstraints.SubjectType.pbData, isCA, 0, 1);

                m_isCA = (isCA[0] & CAPI.CERT_CA_SUBJECT_FLAG) != 0 ? true : false;
                m_hasPathLenConstraint = pBasicConstraints.fPathLenConstraint;
                m_pathLenConstraint    = (int)pBasicConstraints.dwPathLenConstraint;
            }
            else
            {
                bool result = CAPI.DecodeObject(new IntPtr(CAPI.X509_BASIC_CONSTRAINTS2),
                                                m_rawData,
                                                out decoded,
                                                out cbDecoded);
                if (result == false)
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }

                CAPI.CERT_BASIC_CONSTRAINTS2_INFO pBasicConstraints2 = (CAPI.CERT_BASIC_CONSTRAINTS2_INFO)Marshal.PtrToStructure(decoded.DangerousGetHandle(),
                                                                                                                                 typeof(CAPI.CERT_BASIC_CONSTRAINTS2_INFO));

                m_isCA = pBasicConstraints2.fCA == 0 ? false : true;
                m_hasPathLenConstraint = pBasicConstraints2.fPathLenConstraint == 0 ? false : true;
                m_pathLenConstraint    = (int)pBasicConstraints2.dwPathLenConstraint;
            }

            m_decoded = true;
            decoded.Dispose();
        }
        internal static bool GetPrivateKeyInfo(SafeCertContextHandle safeCertContext, ref CspParameters parameters)
        {
            SafeLocalAllocHandle ptr = SafeLocalAllocHandle.InvalidHandle;
            uint cbData = 0;

            if (!CAPI.CAPISafe.CertGetCertificateContextProperty(safeCertContext,
                                                                 CAPI.CERT_KEY_PROV_INFO_PROP_ID,
                                                                 ptr,
                                                                 ref cbData))
            {
                int dwErrorCode = Marshal.GetLastWin32Error();
                if (dwErrorCode == CAPI.CRYPT_E_NOT_FOUND)
                {
                    return(false);
                }
                else
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }

            ptr = CAPI.LocalAlloc(CAPI.LMEM_FIXED, new IntPtr(cbData));
            if (!CAPI.CAPISafe.CertGetCertificateContextProperty(safeCertContext,
                                                                 CAPI.CERT_KEY_PROV_INFO_PROP_ID,
                                                                 ptr,
                                                                 ref cbData))
            {
                int dwErrorCode = Marshal.GetLastWin32Error();
                if (dwErrorCode == CAPI.CRYPT_E_NOT_FOUND)
                {
                    return(false);
                }
                else
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }

            CAPI.CRYPT_KEY_PROV_INFO pKeyProvInfo = (CAPI.CRYPT_KEY_PROV_INFO)Marshal.PtrToStructure(ptr.DangerousGetHandle(), typeof(CAPI.CRYPT_KEY_PROV_INFO));
            parameters.ProviderName     = pKeyProvInfo.pwszProvName;
            parameters.KeyContainerName = pKeyProvInfo.pwszContainerName;
            parameters.ProviderType     = (int)pKeyProvInfo.dwProvType;
            parameters.KeyNumber        = (int)pKeyProvInfo.dwKeySpec;
            parameters.Flags            = (CspProviderFlags)((pKeyProvInfo.dwFlags & CAPI.CRYPT_MACHINE_KEYSET) == CAPI.CRYPT_MACHINE_KEYSET ? CspProviderFlags.UseMachineKeyStore : 0);

            ptr.Dispose();
            return(true);
        }
Exemplo n.º 7
0
        private static void DecodePublicKeyObject(uint aiPubKey, byte[] encodedKeyValue, byte[] encodedParameters, out byte[] decodedData)
        {
            decodedData = null;
            IntPtr zero = IntPtr.Zero;

            switch (aiPubKey)
            {
            case 0xaa01:
            case 0xaa02:
                throw new NotSupportedException(SR.GetString("NotSupported_KeyAlgorithm"));

            case 0xa400:
            case 0x2400:
                zero = new IntPtr(0x13L);
                break;

            case 0x2200:
                zero = new IntPtr(0x26L);
                break;

            default:
                throw new NotSupportedException(SR.GetString("NotSupported_KeyAlgorithm"));
            }
            SafeLocalAllocHandle decodedValue = null;
            uint cbDecodedValue = 0;

            if (!CAPI.DecodeObject(zero, encodedKeyValue, out decodedValue, out cbDecodedValue))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            if (((int)zero) == 0x13)
            {
                decodedData = new byte[cbDecodedValue];
                Marshal.Copy(decodedValue.DangerousGetHandle(), decodedData, 0, decodedData.Length);
            }
            else if (((int)zero) == 0x26)
            {
                SafeLocalAllocHandle handle2 = null;
                uint num2 = 0;
                if (!CAPI.DecodeObject(new IntPtr(0x27L), encodedParameters, out handle2, out num2))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                decodedData = ConstructDSSPubKeyCspBlob(decodedValue, handle2);
                handle2.Dispose();
            }
            decodedValue.Dispose();
        }
        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());
                }
            }
        }
        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);
        }
        private void DecodeExtension()
        {
            uint cbDecodedValue = 0;
            SafeLocalAllocHandle decodedValue = null;
            SafeLocalAllocHandle handle2      = System.Security.Cryptography.X509Certificates.X509Utils.StringToAnsiPtr("2.5.29.14");

            if (!CAPI.DecodeObject(handle2.DangerousGetHandle(), base.m_rawData, out decodedValue, out cbDecodedValue))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            CAPIBase.CRYPTOAPI_BLOB blob = (CAPIBase.CRYPTOAPI_BLOB)Marshal.PtrToStructure(decodedValue.DangerousGetHandle(), typeof(CAPIBase.CRYPTOAPI_BLOB));
            byte[] sArray = CAPI.BlobToByteArray(blob);
            this.m_subjectKeyIdentifier = System.Security.Cryptography.X509Certificates.X509Utils.EncodeHexString(sArray);
            this.m_decoded = true;
            decodedValue.Dispose();
            handle2.Dispose();
        }
Exemplo n.º 11
0
        internal static string FindOidInfo(uint keyType, string keyValue, OidGroup oidGroup)
        {
            if (keyValue == null)
            {
                throw new ArgumentNullException("keyValue");
            }
            if (keyValue.Length == 0)
            {
                return(null);
            }

            SafeLocalAllocHandle pvKey = SafeLocalAllocHandle.InvalidHandle;

            try {
                switch (keyType)
                {
                case CAPI.CRYPT_OID_INFO_OID_KEY:
                    pvKey = StringToAnsiPtr(keyValue);
                    break;

                case CAPI.CRYPT_OID_INFO_NAME_KEY:
                    pvKey = StringToUniPtr(keyValue);
                    break;

                default:
                    Debug.Assert(false);
                    break;
                }

                CAPI.CRYPT_OID_INFO pOidInfo = CAPI.CryptFindOIDInfo(keyType, pvKey, oidGroup);


                if (keyType == CAPI.CRYPT_OID_INFO_OID_KEY)
                {
                    return(pOidInfo.pwszName);
                }
                else
                {
                    return(pOidInfo.pszOID);
                }
            }
            finally {
                pvKey.Dispose();
            }
        }
        private void DecodeExtension()
        {
            uint cbDecodedValue = 0;
            SafeLocalAllocHandle decodedValue = null;

            if (!CAPI.DecodeObject(new IntPtr(0x24L), base.m_rawData, out decodedValue, out cbDecodedValue))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            CAPIBase.CERT_ENHKEY_USAGE cert_enhkey_usage = (CAPIBase.CERT_ENHKEY_USAGE)Marshal.PtrToStructure(decodedValue.DangerousGetHandle(), typeof(CAPIBase.CERT_ENHKEY_USAGE));
            this.m_enhancedKeyUsages = new OidCollection();
            for (int i = 0; i < cert_enhkey_usage.cUsageIdentifier; i++)
            {
                Oid oid = new Oid(Marshal.PtrToStringAnsi(Marshal.ReadIntPtr(new IntPtr(((long)cert_enhkey_usage.rgpszUsageIdentifier) + (i * Marshal.SizeOf(typeof(IntPtr)))))), System.Security.Cryptography.OidGroup.ExtensionOrAttribute, false);
                this.m_enhancedKeyUsages.Add(oid);
            }
            this.m_decoded = true;
            decodedValue.Dispose();
        }
Exemplo n.º 13
0
        internal static SafeLocalAllocHandle CopyOidsToUnmanagedMemory(OidCollection oids)
        {
            SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle;

            if (oids == null || oids.Count == 0)
            {
                return(safeLocalAllocHandle);
            }

            // Copy the oid strings to a local list to prevent a security race condition where
            // the OidCollection or individual oids can be modified by another thread and
            // potentially cause a buffer overflow
            List <string> oidStrs = new List <string>();

            foreach (Oid oid in oids)
            {
                oidStrs.Add(oid.Value);
            }

            IntPtr pOid = IntPtr.Zero;

            // Needs to be checked to avoid having large sets of oids overflow the sizes and allow
            // a potential buffer overflow
            checked {
                int ptrSize = oidStrs.Count * Marshal.SizeOf(typeof(IntPtr));
                int oidSize = 0;
                foreach (string oidStr in oidStrs)
                {
                    oidSize += (oidStr.Length + 1);
                }
                safeLocalAllocHandle = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr((uint)ptrSize + (uint)oidSize));
                pOid = new IntPtr((long)safeLocalAllocHandle.DangerousGetHandle() + ptrSize);
            }
            for (int index = 0; index < oidStrs.Count; index++)
            {
                Marshal.WriteIntPtr(new IntPtr((long)safeLocalAllocHandle.DangerousGetHandle() + index * Marshal.SizeOf(typeof(IntPtr))), pOid);
                byte[] ansiOid = Encoding.ASCII.GetBytes(oidStrs[index]);
                Marshal.Copy(ansiOid, 0, pOid, ansiOid.Length);
                pOid = new IntPtr((long)pOid + oidStrs[index].Length + 1);
            }
            return(safeLocalAllocHandle);
        }
        private static unsafe byte[] EncodeExtension(OidCollection enhancedKeyUsages)
        {
            if (enhancedKeyUsages == null)
            {
                throw new ArgumentNullException("enhancedKeyUsages");
            }
            SafeLocalAllocHandle handle = System.Security.Cryptography.X509Certificates.X509Utils.CopyOidsToUnmanagedMemory(enhancedKeyUsages);

            byte[] encodedData = null;
            using (handle)
            {
                CAPIBase.CERT_ENHKEY_USAGE cert_enhkey_usage = new CAPIBase.CERT_ENHKEY_USAGE {
                    cUsageIdentifier     = (uint)enhancedKeyUsages.Count,
                    rgpszUsageIdentifier = handle.DangerousGetHandle()
                };
                if (!CAPI.EncodeObject("2.5.29.37", new IntPtr((void *)&cert_enhkey_usage), out encodedData))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }
            return(encodedData);
        }
Exemplo n.º 15
0
        private static unsafe byte[] EncodeExtension(OidCollection enhancedKeyUsages)
        {
            if (enhancedKeyUsages == null)
            {
                throw new ArgumentNullException("enhancedKeyUsages");
            }

            SafeLocalAllocHandle safeLocalAllocHandle = X509Utils.CopyOidsToUnmanagedMemory(enhancedKeyUsages);

            byte[] encodedEnhancedKeyUsages = null;
            using (safeLocalAllocHandle) {
                CAPI.CERT_ENHKEY_USAGE pEnhKeyUsage = new CAPI.CERT_ENHKEY_USAGE();
                pEnhKeyUsage.cUsageIdentifier     = (uint)enhancedKeyUsages.Count;
                pEnhKeyUsage.rgpszUsageIdentifier = safeLocalAllocHandle.DangerousGetHandle();
                if (!CAPI.EncodeObject(CAPI.szOID_ENHANCED_KEY_USAGE, new IntPtr(&pEnhKeyUsage), out encodedEnhancedKeyUsages))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
            }

            return(encodedEnhancedKeyUsages);
        }
Exemplo n.º 16
0
        public string Decode(X500DistinguishedNameFlags flag)
        {
            uint dwStrType = CAPI.CERT_X500_NAME_STR | MapNameToStrFlag(flag);

            unsafe {
                byte[] encodedDistinguishedName = this.m_rawData;
                fixed(byte *pbEncoded = encodedDistinguishedName)
                {
                    CAPI.CRYPTOAPI_BLOB nameBlob;
                    IntPtr pNameBlob = new IntPtr(&nameBlob);

                    nameBlob.cbData = (uint)encodedDistinguishedName.Length;
                    nameBlob.pbData = new IntPtr(pbEncoded);

                    uint cchDecoded = CAPI.CertNameToStrW(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
                                                          pNameBlob,
                                                          dwStrType,
                                                          SafeLocalAllocHandle.InvalidHandle,
                                                          0);

                    if (cchDecoded == 0)
                    {
                        throw new CryptographicException(CAPI.CERT_E_INVALID_NAME);
                    }

                    using (SafeLocalAllocHandle pwszDecodeName = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(2 * cchDecoded))) {
                        if (CAPI.CertNameToStrW(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING,
                                                pNameBlob,
                                                dwStrType,
                                                pwszDecodeName,
                                                cchDecoded) == 0)
                        {
                            throw new CryptographicException(CAPI.CERT_E_INVALID_NAME);
                        }
                        return(Marshal.PtrToStringUni(pwszDecodeName.DangerousGetHandle()));
                    }
                }
            }
        }
        private void DecodeExtension()
        {
            uint cbDecodedValue = 0;
            SafeLocalAllocHandle decodedValue = null;

            if (!CAPI.DecodeObject(new IntPtr(14L), base.m_rawData, out decodedValue, out cbDecodedValue))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            CAPIBase.CRYPTOAPI_BLOB cryptoapi_blob = (CAPIBase.CRYPTOAPI_BLOB)Marshal.PtrToStructure(decodedValue.DangerousGetHandle(), typeof(CAPIBase.CRYPTOAPI_BLOB));
            if (cryptoapi_blob.cbData > 4)
            {
                cryptoapi_blob.cbData = 4;
            }
            byte[] destination = new byte[4];
            if (cryptoapi_blob.pbData != IntPtr.Zero)
            {
                Marshal.Copy(cryptoapi_blob.pbData, destination, 0, (int)cryptoapi_blob.cbData);
            }
            this.m_keyUsages = BitConverter.ToUInt32(destination, 0);
            this.m_decoded   = true;
            decodedValue.Dispose();
        }
Exemplo n.º 18
0
        private static unsafe SafeLocalAllocHandle EncodePublicKey(PublicKey key)
        {
            SafeLocalAllocHandle publicKeyInfo = SafeLocalAllocHandle.InvalidHandle;

            CAPI.CERT_PUBLIC_KEY_INFO2 *pPublicKeyInfo = null;
            string objId = key.Oid.Value;

            byte[] encodedParameters = key.EncodedParameters.RawData;
            byte[] encodedKeyValue   = key.EncodedKeyValue.RawData;

            uint cbPublicKeyInfo = (uint)(Marshal.SizeOf(typeof(CAPI.CERT_PUBLIC_KEY_INFO2)) +
                                          X509Utils.AlignedLength((uint)(objId.Length + 1)) +
                                          X509Utils.AlignedLength((uint)encodedParameters.Length) +
                                          encodedKeyValue.Length);

            publicKeyInfo  = CAPI.LocalAlloc(CAPI.LPTR, new IntPtr(cbPublicKeyInfo));
            pPublicKeyInfo = (CAPI.CERT_PUBLIC_KEY_INFO2 *)publicKeyInfo.DangerousGetHandle();
            IntPtr pszObjId     = new IntPtr((long)pPublicKeyInfo + Marshal.SizeOf(typeof(CAPI.CERT_PUBLIC_KEY_INFO2)));
            IntPtr pbParameters = new IntPtr((long)pszObjId + X509Utils.AlignedLength(((uint)(objId.Length + 1))));
            IntPtr pbPublicKey  = new IntPtr((long)pbParameters + X509Utils.AlignedLength((uint)encodedParameters.Length));

            pPublicKeyInfo->Algorithm.pszObjId = pszObjId;
            byte[] szObjId = new byte[objId.Length + 1];
            Encoding.ASCII.GetBytes(objId, 0, objId.Length, szObjId, 0);
            Marshal.Copy(szObjId, 0, pszObjId, szObjId.Length);
            if (encodedParameters.Length > 0)
            {
                pPublicKeyInfo->Algorithm.Parameters.cbData = (uint)encodedParameters.Length;
                pPublicKeyInfo->Algorithm.Parameters.pbData = pbParameters;
                Marshal.Copy(encodedParameters, 0, pbParameters, encodedParameters.Length);
            }
            pPublicKeyInfo->PublicKey.cbData = (uint)encodedKeyValue.Length;
            pPublicKeyInfo->PublicKey.pbData = pbPublicKey;
            Marshal.Copy(encodedKeyValue, 0, pbPublicKey, encodedKeyValue.Length);
            return(publicKeyInfo);
        }
Exemplo n.º 19
0
        private void DecodeExtension()
        {
            uint cbDecoded = 0;
            SafeLocalAllocHandle decoded = null;

            SafeLocalAllocHandle pb = X509Utils.StringToAnsiPtr(CAPI.szOID_SUBJECT_KEY_IDENTIFIER);
            bool result             = CAPI.DecodeObject(pb.DangerousGetHandle(),
                                                        m_rawData,
                                                        out decoded,
                                                        out cbDecoded);

            if (!result)
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }

            CAPI.CRYPTOAPI_BLOB pSubjectKeyIdentifier = (CAPI.CRYPTOAPI_BLOB)Marshal.PtrToStructure(decoded.DangerousGetHandle(), typeof(CAPI.CRYPTOAPI_BLOB));
            byte[] hexArray = CAPI.BlobToByteArray(pSubjectKeyIdentifier);
            m_subjectKeyIdentifier = X509Utils.EncodeHexString(hexArray);

            m_decoded = true;
            decoded.Dispose();
            pb.Dispose();
        }
Exemplo n.º 20
0
        internal static uint OidToAlgId(string value)
        {
            SafeLocalAllocHandle pvKey = StringToAnsiPtr(value);

            return(CAPI.CryptFindOIDInfo(1, pvKey, System.Security.Cryptography.OidGroup.AllGroups).Algid);
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
0
        public static DSA GetDSAPublicKey(this X509Certificate2 certificate)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }

            if (!IsDSA(certificate))
            {
                return(null);
            }

            unsafe
            {
                DSAParameters dp = new DSAParameters();

                SafeLocalAllocHandle dssKeyLocalAlloc = null;
                try
                {
                    byte[] encodedPublicKey = certificate.PublicKey.EncodedKeyValue.RawData;
                    uint   cbDSSKey;
                    if (!CapiNative.DecodeObject((IntPtr)(CapiNative.X509_DSS_PUBLICKEY), encodedPublicKey, out dssKeyLocalAlloc, out cbDSSKey))
                    {
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    }
                    if (cbDSSKey < Marshal.SizeOf(typeof(CapiNative.CRYPTOAPI_BLOB)))
                    {
                        throw new CryptographicException();
                    }

                    CapiNative.CRYPTOAPI_BLOB *pDssKeyBlob = (CapiNative.CRYPTOAPI_BLOB *)(dssKeyLocalAlloc.DangerousGetHandle());
                    dp.Y = ToBigEndianByteArray(*pDssKeyBlob);
                }
                finally
                {
                    if (dssKeyLocalAlloc != null)
                    {
                        dssKeyLocalAlloc.Dispose();
                        dssKeyLocalAlloc = null;
                    }
                }

                SafeLocalAllocHandle dssParametersLocalHandle = null;
                try
                {
                    byte[] encodedKeyAlgorithmParameters = certificate.GetKeyAlgorithmParameters();
                    uint   cbDSSParams;
                    if (!CapiNative.DecodeObject((IntPtr)(CapiNative.X509_DSS_PARAMETERS), encodedKeyAlgorithmParameters, out dssParametersLocalHandle, out cbDSSParams))
                    {
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    }
                    if (cbDSSParams < Marshal.SizeOf(typeof(CapiNative.CERT_DSS_PARAMETERS)))
                    {
                        throw new CryptographicException();
                    }

                    CapiNative.CERT_DSS_PARAMETERS *pDssParameters = (CapiNative.CERT_DSS_PARAMETERS *)(dssParametersLocalHandle.DangerousGetHandle());
                    dp.P = ToBigEndianByteArray(pDssParameters->p);
                    dp.Q = ToBigEndianByteArray(pDssParameters->q);
                    dp.G = ToBigEndianByteArray(pDssParameters->g);
                }
                finally
                {
                    if (dssParametersLocalHandle != null)
                    {
                        dssParametersLocalHandle.Dispose();
                        dssParametersLocalHandle = null;
                    }
                }

                DSACng dsaCng = new DSACng();
                dsaCng.ImportParameters(dp);
                return(dsaCng);
            }
        }
Exemplo n.º 23
0
        //
        // Builds a certificate chain.
        //

        internal static unsafe int BuildChain(IntPtr hChainEngine,
                                              SafeCertContextHandle pCertContext,
                                              X509Certificate2Collection extraStore,
                                              OidCollection applicationPolicy,
                                              OidCollection certificatePolicy,
                                              X509RevocationMode revocationMode,
                                              X509RevocationFlag revocationFlag,
                                              DateTime verificationTime,
                                              TimeSpan timeout,
                                              ref SafeCertChainHandle ppChainContext)
        {
            if (pCertContext == null || pCertContext.IsInvalid)
            {
                throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidContextHandle), "pCertContext");
            }

            SafeCertStoreHandle hCertStore = SafeCertStoreHandle.InvalidHandle;

            if (extraStore != null && extraStore.Count > 0)
            {
                hCertStore = X509Utils.ExportToMemoryStore(extraStore);
            }

            CAPI.CERT_CHAIN_PARA ChainPara = new CAPI.CERT_CHAIN_PARA();

            // Initialize the structure size.
            ChainPara.cbSize = (uint)Marshal.SizeOf(ChainPara);

            SafeLocalAllocHandle applicationPolicyHandle = SafeLocalAllocHandle.InvalidHandle;
            SafeLocalAllocHandle certificatePolicyHandle = SafeLocalAllocHandle.InvalidHandle;

            try {
                // Application policy
                if (applicationPolicy != null && applicationPolicy.Count > 0)
                {
                    ChainPara.RequestedUsage.dwType = CAPI.USAGE_MATCH_TYPE_AND;
                    ChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint)applicationPolicy.Count;
                    applicationPolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy);
                    ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyHandle.DangerousGetHandle();
                }

                // Certificate policy
                if (certificatePolicy != null && certificatePolicy.Count > 0)
                {
                    ChainPara.RequestedIssuancePolicy.dwType = CAPI.USAGE_MATCH_TYPE_AND;
                    ChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint)certificatePolicy.Count;
                    certificatePolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy);
                    ChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyHandle.DangerousGetHandle();
                }

                ChainPara.dwUrlRetrievalTimeout = (uint)Math.Floor(timeout.TotalMilliseconds);

                _FILETIME ft = new _FILETIME();
                *((long *)&ft) = verificationTime.ToFileTime();

                uint flags = X509Utils.MapRevocationFlags(revocationMode, revocationFlag);

                // Build the chain.
                if (!CAPI.CertGetCertificateChain(hChainEngine,
                                                  pCertContext,
                                                  ref ft,
                                                  hCertStore,
                                                  ref ChainPara,
                                                  flags,
                                                  IntPtr.Zero,
                                                  ref ppChainContext))
                {
                    return(Marshal.GetHRForLastWin32Error());
                }
            }
            finally {
                applicationPolicyHandle.Dispose();
                certificatePolicyHandle.Dispose();
            }

            return(CAPI.S_OK);
        }
Exemplo n.º 24
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);
        }
Exemplo n.º 25
0
        private static unsafe byte[] EncodePublicKey(PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            // Construct CERT_PUBLIC_KEY_INFO2 in unmanged memory from given encoded blobs.
            SafeLocalAllocHandle publicKeyInfo = EncodePublicKey(key);

            CAPI.CERT_PUBLIC_KEY_INFO2 *pPublicKeyInfo = (CAPI.CERT_PUBLIC_KEY_INFO2 *)publicKeyInfo.DangerousGetHandle();

            byte [] buffer     = new byte[20];
            byte [] identifier = null;

            fixed(byte *pBuffer = buffer)
            {
                uint   cbData = (uint)buffer.Length;
                IntPtr pbData = new IntPtr(pBuffer);

                try {
                    if ((X509SubjectKeyIdentifierHashAlgorithm.Sha1 == algorithm) ||
                        (X509SubjectKeyIdentifierHashAlgorithm.ShortSha1 == algorithm))
                    {
                        //+=================================================================
                        // (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of
                        // the value of the BIT STRING subjectPublicKey (excluding the tag,
                        // length, and number of unused bits).
                        if (!CAPI.CryptHashCertificate(
                                IntPtr.Zero,            // hCryptProv
                                CAPI.CALG_SHA1,
                                0,                      // dwFlags,
                                pPublicKeyInfo->PublicKey.pbData,
                                pPublicKeyInfo->PublicKey.cbData,
                                pbData,
                                new IntPtr(&cbData)))
                        {
                            throw new CryptographicException(Marshal.GetHRForLastWin32Error());
                        }
                    }
                    //+=================================================================
                    // Microsoft convention: The keyIdentifier is composed of the
                    // 160-bit SHA-1 hash of the encoded subjectPublicKey BITSTRING
                    // (including the tag, length, and number of unused bits).
                    else if (X509SubjectKeyIdentifierHashAlgorithm.CapiSha1 == algorithm)
                    {
                        if (!CAPI.CryptHashPublicKeyInfo(
                                IntPtr.Zero,            // hCryptProv
                                CAPI.CALG_SHA1,
                                0,                      // dwFlags,
                                CAPI.X509_ASN_ENCODING,
                                new IntPtr(pPublicKeyInfo),
                                pbData,
                                new IntPtr(&cbData)))
                        {
                            throw new CryptographicException(Marshal.GetHRForLastWin32Error());
                        }
                    }
                    else
                    {
                        throw new ArgumentException("algorithm");
                    }

                    //+=================================================================
                    // (2) The keyIdentifier is composed of a four bit type field with
                    //  the value 0100 followed by the least significant 60 bits of the
                    //  SHA-1 hash of the value of the BIT STRING subjectPublicKey
                    // (excluding the tag, length, and number of unused bit string bits)
                    if (X509SubjectKeyIdentifierHashAlgorithm.ShortSha1 == algorithm)
                    {
                        identifier = new byte[8];
                        Array.Copy(buffer, buffer.Length - 8, identifier, 0, identifier.Length);
                        identifier[0] &= 0x0f;
                        identifier[0] |= 0x40;
                    }
                    else
                    {
                        identifier = buffer;
                        // return the meaningful part only
                        if (buffer.Length > (int)cbData)
                        {
                            identifier = new byte[cbData];
                            Array.Copy(buffer, 0, identifier, 0, identifier.Length);
                        }
                    }
                } finally {
                    publicKeyInfo.Dispose();
                }
            }

            return(EncodeExtension(identifier));
        }
        public unsafe string GetNameInfo(X509NameType nameType, bool forIssuer)
        {
            uint dwFlags       = forIssuer ? 1 : 0;
            uint dwDisplayType = System.Security.Cryptography.X509Certificates.X509Utils.MapNameType(nameType);

            switch (dwDisplayType)
            {
            case 1:
                return(CAPI.GetCertNameInfo(this.m_safeCertContext, dwFlags, dwDisplayType));

            case 4:
                return(CAPI.GetCertNameInfo(this.m_safeCertContext, dwFlags, dwDisplayType));
            }
            string str = string.Empty;

            CAPIBase.CERT_CONTEXT cert_context = *((CAPIBase.CERT_CONTEXT *) this.m_safeCertContext.DangerousGetHandle());
            CAPIBase.CERT_INFO    cert_info    = (CAPIBase.CERT_INFO)Marshal.PtrToStructure(cert_context.pCertInfo, typeof(CAPIBase.CERT_INFO));
            IntPtr[] ptrArray = new IntPtr[] { CAPISafe.CertFindExtension(forIssuer ? "2.5.29.8" : "2.5.29.7", cert_info.cExtension, cert_info.rgExtension), CAPISafe.CertFindExtension(forIssuer ? "2.5.29.18" : "2.5.29.17", cert_info.cExtension, cert_info.rgExtension) };
            for (int i = 0; i < ptrArray.Length; i++)
            {
                if (ptrArray[i] != IntPtr.Zero)
                {
                    CAPIBase.CERT_EXTENSION cert_extension = (CAPIBase.CERT_EXTENSION)Marshal.PtrToStructure(ptrArray[i], 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;
                    SafeLocalAllocHandle handle2      = System.Security.Cryptography.X509Certificates.X509Utils.StringToAnsiPtr(cert_extension.pszObjId);
                    bool flag = CAPI.DecodeObject(handle2.DangerousGetHandle(), destination, out decodedValue, out cbDecodedValue);
                    handle2.Dispose();
                    if (flag)
                    {
                        CAPIBase.CERT_ALT_NAME_INFO cert_alt_name_info = (CAPIBase.CERT_ALT_NAME_INFO)Marshal.PtrToStructure(decodedValue.DangerousGetHandle(), typeof(CAPIBase.CERT_ALT_NAME_INFO));
                        for (int j = 0; j < cert_alt_name_info.cAltEntry; j++)
                        {
                            IntPtr ptr = new IntPtr(((long)cert_alt_name_info.rgAltEntry) + (j * Marshal.SizeOf(typeof(CAPIBase.CERT_ALT_NAME_ENTRY))));
                            CAPIBase.CERT_ALT_NAME_ENTRY cert_alt_name_entry = (CAPIBase.CERT_ALT_NAME_ENTRY)Marshal.PtrToStructure(ptr, typeof(CAPIBase.CERT_ALT_NAME_ENTRY));
                            switch (dwDisplayType)
                            {
                            case 6:
                                if (cert_alt_name_entry.dwAltNameChoice == 3)
                                {
                                    str = Marshal.PtrToStringUni(cert_alt_name_entry.Value.pwszDNSName);
                                }
                                break;

                            case 7:
                                if (cert_alt_name_entry.dwAltNameChoice == 7)
                                {
                                    str = Marshal.PtrToStringUni(cert_alt_name_entry.Value.pwszURL);
                                }
                                break;

                            case 8:
                                if (cert_alt_name_entry.dwAltNameChoice == 1)
                                {
                                    CAPIBase.CERT_OTHER_NAME cert_other_name = (CAPIBase.CERT_OTHER_NAME)Marshal.PtrToStructure(cert_alt_name_entry.Value.pOtherName, typeof(CAPIBase.CERT_OTHER_NAME));
                                    if (cert_other_name.pszObjId == "1.3.6.1.4.1.311.20.2.3")
                                    {
                                        uint num6 = 0;
                                        SafeLocalAllocHandle handle3 = null;
                                        if (CAPI.DecodeObject(new IntPtr(0x18L), System.Security.Cryptography.X509Certificates.X509Utils.PtrToByte(cert_other_name.Value.pbData, cert_other_name.Value.cbData), out handle3, out num6))
                                        {
                                            CAPIBase.CERT_NAME_VALUE cert_name_value = (CAPIBase.CERT_NAME_VALUE)Marshal.PtrToStructure(handle3.DangerousGetHandle(), typeof(CAPIBase.CERT_NAME_VALUE));
                                            if (System.Security.Cryptography.X509Certificates.X509Utils.IsCertRdnCharString(cert_name_value.dwValueType))
                                            {
                                                str = Marshal.PtrToStringUni(cert_name_value.Value.pbData);
                                            }
                                            handle3.Dispose();
                                        }
                                    }
                                }
                                break;
                            }
                        }
                        decodedValue.Dispose();
                    }
                }
            }
            if ((nameType != X509NameType.DnsName) || ((str != null) && (str.Length != 0)))
            {
                return(str);
            }
            return(CAPI.GetCertNameInfo(this.m_safeCertContext, dwFlags, 3));
        }
        private static unsafe byte[] EncodePublicKey(PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            SafeLocalAllocHandle handle = EncodePublicKey(key);

            CAPIBase.CERT_PUBLIC_KEY_INFO2 *cert_public_key_infoPtr = (CAPIBase.CERT_PUBLIC_KEY_INFO2 *)handle.DangerousGetHandle();
            byte[] sourceArray      = new byte[20];
            byte[] destinationArray = null;
            fixed(byte *numRef = sourceArray)
            {
                uint   length         = (uint)sourceArray.Length;
                IntPtr pbComputedHash = new IntPtr((void *)numRef);

                try
                {
                    if ((algorithm == X509SubjectKeyIdentifierHashAlgorithm.Sha1) || (X509SubjectKeyIdentifierHashAlgorithm.ShortSha1 == algorithm))
                    {
                        if (!CAPISafe.CryptHashCertificate(IntPtr.Zero, 0x8004, 0, cert_public_key_infoPtr->PublicKey.pbData, cert_public_key_infoPtr->PublicKey.cbData, pbComputedHash, new IntPtr((void *)&length)))
                        {
                            throw new CryptographicException(Marshal.GetHRForLastWin32Error());
                        }
                    }
                    else
                    {
                        if (X509SubjectKeyIdentifierHashAlgorithm.CapiSha1 != algorithm)
                        {
                            throw new ArgumentException("algorithm");
                        }
                        if (!CAPISafe.CryptHashPublicKeyInfo(IntPtr.Zero, 0x8004, 0, 1, new IntPtr((void *)cert_public_key_infoPtr), pbComputedHash, new IntPtr((void *)&length)))
                        {
                            throw new CryptographicException(Marshal.GetHRForLastWin32Error());
                        }
                    }
                    if (X509SubjectKeyIdentifierHashAlgorithm.ShortSha1 == algorithm)
                    {
                        destinationArray = new byte[8];
                        Array.Copy(sourceArray, sourceArray.Length - 8, destinationArray, 0, destinationArray.Length);
                        destinationArray[0] = (byte)(destinationArray[0] & 15);
                        destinationArray[0] = (byte)(destinationArray[0] | 0x40);
                    }
                    else
                    {
                        destinationArray = sourceArray;
                        if (sourceArray.Length > length)
                        {
                            destinationArray = new byte[length];
                            Array.Copy(sourceArray, 0, destinationArray, 0, destinationArray.Length);
                        }
                    }
                }
                finally
                {
                    handle.Dispose();
                }
            }

            return(EncodeExtension(destinationArray));
        }
Exemplo n.º 28
0
        private static byte[] ConstructDSSPubKeyCspBlob(SafeLocalAllocHandle decodedKeyValue, SafeLocalAllocHandle decodedParameters)
        {
            CAPIBase.CRYPTOAPI_BLOB      cryptoapi_blob      = (CAPIBase.CRYPTOAPI_BLOB)Marshal.PtrToStructure(decodedKeyValue.DangerousGetHandle(), typeof(CAPIBase.CRYPTOAPI_BLOB));
            CAPIBase.CERT_DSS_PARAMETERS cert_dss_parameters = (CAPIBase.CERT_DSS_PARAMETERS)Marshal.PtrToStructure(decodedParameters.DangerousGetHandle(), typeof(CAPIBase.CERT_DSS_PARAMETERS));
            uint cbData = cert_dss_parameters.p.cbData;

            if (cbData == 0)
            {
                throw new CryptographicException(-2146893803);
            }
            uint         num2   = ((((0x10 + cbData) + 20) + cbData) + cbData) + 0x18;
            MemoryStream output = new MemoryStream((int)num2);
            BinaryWriter writer = new BinaryWriter(output);

            writer.Write((byte)6);
            writer.Write((byte)2);
            writer.Write((short)0);
            writer.Write((uint)0x2200);
            writer.Write((uint)0x31535344);
            writer.Write((uint)(cbData * 8));
            byte[] destination = new byte[cert_dss_parameters.p.cbData];
            Marshal.Copy(cert_dss_parameters.p.pbData, destination, 0, destination.Length);
            writer.Write(destination);
            uint num3 = cert_dss_parameters.q.cbData;

            if ((num3 == 0) || (num3 > 20))
            {
                throw new CryptographicException(-2146893803);
            }
            byte[] buffer2 = new byte[cert_dss_parameters.q.cbData];
            Marshal.Copy(cert_dss_parameters.q.pbData, buffer2, 0, buffer2.Length);
            writer.Write(buffer2);
            if (20 > num3)
            {
                writer.Write(new byte[20 - num3]);
            }
            num3 = cert_dss_parameters.g.cbData;
            if ((num3 == 0) || (num3 > cbData))
            {
                throw new CryptographicException(-2146893803);
            }
            byte[] buffer3 = new byte[cert_dss_parameters.g.cbData];
            Marshal.Copy(cert_dss_parameters.g.pbData, buffer3, 0, buffer3.Length);
            writer.Write(buffer3);
            if (cbData > num3)
            {
                writer.Write(new byte[cbData - num3]);
            }
            num3 = cryptoapi_blob.cbData;
            if ((num3 == 0) || (num3 > cbData))
            {
                throw new CryptographicException(-2146893803);
            }
            byte[] buffer4 = new byte[cryptoapi_blob.cbData];
            Marshal.Copy(cryptoapi_blob.pbData, buffer4, 0, buffer4.Length);
            writer.Write(buffer4);
            if (cbData > num3)
            {
                writer.Write(new byte[cbData - num3]);
            }
            writer.Write(uint.MaxValue);
            writer.Write(new byte[20]);
            return(output.ToArray());
        }