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);
        }
 internal static unsafe byte[] EncodeOctetString(byte[] octets)
 {
     fixed(byte *numRef = octets)
     {
         System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB cryptoapi_blob = new System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB {
             cbData = (uint)octets.Length,
             pbData = new IntPtr((void *)numRef)
         };
         byte[] encodedData = new byte[0];
         if (!System.Security.Cryptography.CAPI.EncodeObject(new IntPtr(0x19L), new IntPtr((long)((ulong)((IntPtr) & cryptoapi_blob))), out encodedData))
         {
             throw new CryptographicException(Marshal.GetLastWin32Error());
         }
         return(encodedData);
     }
 }
        internal static string DecodeOctetString(byte[] encodedOctetString)
        {
            uint cbDecodedValue = 0;

            System.Security.Cryptography.SafeLocalAllocHandle decodedValue = null;
            if (!System.Security.Cryptography.CAPI.DecodeObject(new IntPtr(0x19L), encodedOctetString, out decodedValue, out cbDecodedValue))
            {
                throw new CryptographicException(Marshal.GetLastWin32Error());
            }
            if (cbDecodedValue == 0)
            {
                return(string.Empty);
            }
            System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB cryptoapi_blob = (System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB)Marshal.PtrToStructure(decodedValue.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB));
            if (cryptoapi_blob.cbData == 0)
            {
                return(string.Empty);
            }
            string str = Marshal.PtrToStringUni(cryptoapi_blob.pbData);

            decodedValue.Dispose();
            return(str);
        }
 internal static unsafe uint AddCertsToMessage(System.Security.Cryptography.SafeCryptMsgHandle safeCryptMsgHandle, X509Certificate2Collection bagOfCerts, X509Certificate2Collection chainOfCerts)
 {
     uint num = 0;
     X509Certificate2Enumerator enumerator = chainOfCerts.GetEnumerator();
     while (enumerator.MoveNext())
     {
         X509Certificate2 current = enumerator.Current;
         if (bagOfCerts.Find(X509FindType.FindByThumbprint, current.Thumbprint, false).Count == 0)
         {
             System.Security.Cryptography.CAPI.CERT_CONTEXT cert_context = *((System.Security.Cryptography.CAPI.CERT_CONTEXT*) System.Security.Cryptography.X509Certificates.X509Utils.GetCertContext(current).DangerousGetHandle());
             System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB cryptoapi_blob = new System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB {
                 cbData = cert_context.cbCertEncoded,
                 pbData = cert_context.pbCertEncoded
             };
             if (!System.Security.Cryptography.CAPI.CryptMsgControl(safeCryptMsgHandle, 0, 10, new IntPtr((long) ((ulong) ((IntPtr) &cryptoapi_blob)))))
             {
                 throw new CryptographicException(Marshal.GetLastWin32Error());
             }
             num++;
         }
     }
     return num;
 }
        internal static unsafe uint AddCertsToMessage(System.Security.Cryptography.SafeCryptMsgHandle safeCryptMsgHandle, X509Certificate2Collection bagOfCerts, X509Certificate2Collection chainOfCerts)
        {
            uint num = 0;
            X509Certificate2Enumerator enumerator = chainOfCerts.GetEnumerator();

            while (enumerator.MoveNext())
            {
                X509Certificate2 current = enumerator.Current;
                if (bagOfCerts.Find(X509FindType.FindByThumbprint, current.Thumbprint, false).Count == 0)
                {
                    System.Security.Cryptography.CAPI.CERT_CONTEXT   cert_context   = *((System.Security.Cryptography.CAPI.CERT_CONTEXT *)System.Security.Cryptography.X509Certificates.X509Utils.GetCertContext(current).DangerousGetHandle());
                    System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB cryptoapi_blob = new System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB {
                        cbData = cert_context.cbCertEncoded,
                        pbData = cert_context.pbCertEncoded
                    };
                    if (!System.Security.Cryptography.CAPI.CryptMsgControl(safeCryptMsgHandle, 0, 10, new IntPtr((long)((ulong)((IntPtr) & cryptoapi_blob)))))
                    {
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    }
                    num++;
                }
            }
            return(num);
        }
        internal unsafe SubjectIdentifier(System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB issuer, System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB serialNumber)
        {
            System.Security.Cryptography.CAPI.CERT_ISSUER_SERIAL_NUMBER cert_issuer_serial_number;
            bool  flag   = true;
            byte *pbData = (byte *)serialNumber.pbData;

            for (uint i = 0; i < serialNumber.cbData; i++)
            {
                pbData++;
                if (pbData[0] != 0)
                {
                    flag = false;
                    break;
                }
            }
            if (flag)
            {
                byte[] destination = new byte[issuer.cbData];
                Marshal.Copy(issuer.pbData, destination, 0, destination.Length);
                X500DistinguishedName name = new X500DistinguishedName(destination);
                if (string.Compare("CN=Dummy Signer", name.Name, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    this.Reset(SubjectIdentifierType.NoSignature, null);
                    return;
                }
            }
            if (flag)
            {
                this.m_type  = SubjectIdentifierType.SubjectKeyIdentifier;
                this.m_value = string.Empty;
                uint cbDecodedValue = 0;
                System.Security.Cryptography.SafeLocalAllocHandle invalidHandle = System.Security.Cryptography.SafeLocalAllocHandle.InvalidHandle;
                if (!System.Security.Cryptography.CAPI.DecodeObject(new IntPtr(7L), issuer.pbData, issuer.cbData, out invalidHandle, out cbDecodedValue))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                using (invalidHandle)
                {
                    System.Security.Cryptography.CAPI.CERT_NAME_INFO cert_name_info = (System.Security.Cryptography.CAPI.CERT_NAME_INFO)Marshal.PtrToStructure(invalidHandle.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CERT_NAME_INFO));
                    for (uint j = 0; j < cert_name_info.cRDN; j++)
                    {
                        System.Security.Cryptography.CAPI.CERT_RDN cert_rdn = (System.Security.Cryptography.CAPI.CERT_RDN)Marshal.PtrToStructure(new IntPtr(((long)cert_name_info.rgRDN) + (j * Marshal.SizeOf(typeof(System.Security.Cryptography.CAPI.CERT_RDN)))), typeof(System.Security.Cryptography.CAPI.CERT_RDN));
                        for (uint k = 0; k < cert_rdn.cRDNAttr; k++)
                        {
                            System.Security.Cryptography.CAPI.CERT_RDN_ATTR cert_rdn_attr = (System.Security.Cryptography.CAPI.CERT_RDN_ATTR)Marshal.PtrToStructure(new IntPtr(((long)cert_rdn.rgRDNAttr) + (k * Marshal.SizeOf(typeof(System.Security.Cryptography.CAPI.CERT_RDN_ATTR)))), typeof(System.Security.Cryptography.CAPI.CERT_RDN_ATTR));
                            if ((string.Compare("1.3.6.1.4.1.311.10.7.1", cert_rdn_attr.pszObjId, StringComparison.OrdinalIgnoreCase) == 0) && (cert_rdn_attr.dwValueType == 2))
                            {
                                byte[] buffer2 = new byte[cert_rdn_attr.Value.cbData];
                                Marshal.Copy(cert_rdn_attr.Value.pbData, buffer2, 0, buffer2.Length);
                                this.Reset(SubjectIdentifierType.SubjectKeyIdentifier, System.Security.Cryptography.X509Certificates.X509Utils.EncodeHexString(buffer2));
                                return;
                            }
                        }
                    }
                }
                throw new CryptographicException(-2146889715);
            }
            cert_issuer_serial_number.Issuer       = issuer;
            cert_issuer_serial_number.SerialNumber = serialNumber;
            X509IssuerSerial serial = PkcsUtils.DecodeIssuerSerial(cert_issuer_serial_number);

            this.Reset(SubjectIdentifierType.IssuerAndSerialNumber, serial);
        }
Beispiel #7
0
        internal AlgorithmIdentifier(System.Security.Cryptography.CAPI.CRYPT_ALGORITHM_IDENTIFIER algorithmIdentifier)
        {
            int  keyLength      = 0;
            uint cbDecodedValue = 0;

            System.Security.Cryptography.SafeLocalAllocHandle invalidHandle = System.Security.Cryptography.SafeLocalAllocHandle.InvalidHandle;
            byte[] destination = new byte[0];
            uint   num3        = System.Security.Cryptography.X509Certificates.X509Utils.OidToAlgId(algorithmIdentifier.pszObjId);

            if (num3 == 0x6602)
            {
                if (algorithmIdentifier.Parameters.cbData > 0)
                {
                    if (!System.Security.Cryptography.CAPI.DecodeObject(new IntPtr(0x29L), algorithmIdentifier.Parameters.pbData, algorithmIdentifier.Parameters.cbData, out invalidHandle, out cbDecodedValue))
                    {
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    }
                    System.Security.Cryptography.CAPI.CRYPT_RC2_CBC_PARAMETERS crypt_rc_cbc_parameters = (System.Security.Cryptography.CAPI.CRYPT_RC2_CBC_PARAMETERS)Marshal.PtrToStructure(invalidHandle.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CRYPT_RC2_CBC_PARAMETERS));
                    switch (crypt_rc_cbc_parameters.dwVersion)
                    {
                    case 0x34:
                        keyLength = 0x38;
                        break;

                    case 0x3a:
                        keyLength = 0x80;
                        break;

                    case 160:
                        keyLength = 40;
                        break;
                    }
                    if (crypt_rc_cbc_parameters.fIV)
                    {
                        destination = (byte[])crypt_rc_cbc_parameters.rgbIV.Clone();
                    }
                }
            }
            else if (((num3 == 0x6801) || (num3 == 0x6601)) || (num3 == 0x6603))
            {
                if (algorithmIdentifier.Parameters.cbData > 0)
                {
                    if (!System.Security.Cryptography.CAPI.DecodeObject(new IntPtr(0x19L), algorithmIdentifier.Parameters.pbData, algorithmIdentifier.Parameters.cbData, out invalidHandle, out cbDecodedValue))
                    {
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    }
                    if (cbDecodedValue > 0)
                    {
                        if (num3 == 0x6801)
                        {
                            System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB cryptoapi_blob = (System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB)Marshal.PtrToStructure(invalidHandle.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB));
                            if (cryptoapi_blob.cbData > 0)
                            {
                                destination = new byte[cryptoapi_blob.cbData];
                                Marshal.Copy(cryptoapi_blob.pbData, destination, 0, destination.Length);
                            }
                        }
                        else
                        {
                            destination = new byte[cbDecodedValue];
                            Marshal.Copy(invalidHandle.DangerousGetHandle(), destination, 0, destination.Length);
                        }
                    }
                }
                if (num3 == 0x6801)
                {
                    keyLength = 0x80 - (destination.Length * 8);
                }
                else if (num3 == 0x6601)
                {
                    keyLength = 0x40;
                }
                else
                {
                    keyLength = 0xc0;
                }
            }
            else if (algorithmIdentifier.Parameters.cbData > 0)
            {
                destination = new byte[algorithmIdentifier.Parameters.cbData];
                Marshal.Copy(algorithmIdentifier.Parameters.pbData, destination, 0, destination.Length);
            }
            this.Reset(new System.Security.Cryptography.Oid(algorithmIdentifier.pszObjId), keyLength, destination);
            invalidHandle.Dispose();
        }
 internal CRYPT_OID_INFO(int size)
 {
     this.cbSize = (uint) size;
     this.pszOID = null;
     this.pwszName = null;
     this.dwGroupId = 0;
     this.Algid = 0;
     this.ExtraInfo = new System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB();
 }
 internal CMSG_CTRL_ADD_SIGNER_UNAUTH_ATTR_PARA(int size)
 {
     this.cbSize = (uint) size;
     this.dwSignerIndex = 0;
     this.blob = new System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB();
 }
        public static unsafe byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope)
        {
            byte[] buffer2;
            if (encryptedData == null)
            {
                throw new ArgumentNullException("encryptedData");
            }
            if (Environment.OSVersion.Platform == PlatformID.Win32Windows)
            {
                throw new NotSupportedException(SecurityResources.GetResourceString("NotSupported_PlatformRequiresNT"));
            }
            GCHandle handle  = new GCHandle();
            GCHandle handle2 = new GCHandle();

            System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB cryptoapi_blob = new System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB();
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                handle = GCHandle.Alloc(encryptedData, GCHandleType.Pinned);
                System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB cryptoapi_blob2 = new System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB {
                    cbData = (uint)encryptedData.Length,
                    pbData = handle.AddrOfPinnedObject()
                };
                System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB cryptoapi_blob3 = new System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB();
                if (optionalEntropy != null)
                {
                    handle2 = GCHandle.Alloc(optionalEntropy, GCHandleType.Pinned);
                    cryptoapi_blob3.cbData = (uint)optionalEntropy.Length;
                    cryptoapi_blob3.pbData = handle2.AddrOfPinnedObject();
                }
                uint dwFlags = 1;
                if (scope == DataProtectionScope.LocalMachine)
                {
                    dwFlags |= 4;
                }
                if (!System.Security.Cryptography.CAPI.CryptUnprotectData(new IntPtr((void *)&cryptoapi_blob2), IntPtr.Zero, new IntPtr((void *)&cryptoapi_blob3), IntPtr.Zero, IntPtr.Zero, dwFlags, new IntPtr((void *)&cryptoapi_blob)))
                {
                    throw new CryptographicException(Marshal.GetLastWin32Error());
                }
                if (cryptoapi_blob.pbData == IntPtr.Zero)
                {
                    throw new OutOfMemoryException();
                }
                byte[] destination = new byte[cryptoapi_blob.cbData];
                Marshal.Copy(cryptoapi_blob.pbData, destination, 0, destination.Length);
                buffer2 = destination;
            }
            catch (EntryPointNotFoundException)
            {
                throw new NotSupportedException(SecurityResources.GetResourceString("NotSupported_PlatformRequiresNT"));
            }
            finally
            {
                if (handle.IsAllocated)
                {
                    handle.Free();
                }
                if (handle2.IsAllocated)
                {
                    handle2.Free();
                }
                if (cryptoapi_blob.pbData != IntPtr.Zero)
                {
                    System.Security.Cryptography.CAPI.CAPISafe.ZeroMemory(cryptoapi_blob.pbData, cryptoapi_blob.cbData);
                    System.Security.Cryptography.CAPI.CAPISafe.LocalFree(cryptoapi_blob.pbData);
                }
            }
            return(buffer2);
        }
 internal static unsafe byte[] EncodeOctetString(byte[] octets)
 {
     fixed (byte* numRef = octets)
     {
         System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB cryptoapi_blob = new System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB {
             cbData = (uint) octets.Length,
             pbData = new IntPtr((void*) numRef)
         };
         byte[] encodedData = new byte[0];
         if (!System.Security.Cryptography.CAPI.EncodeObject(new IntPtr(0x19L), new IntPtr((long) ((ulong) ((IntPtr) &cryptoapi_blob))), out encodedData))
         {
             throw new CryptographicException(Marshal.GetLastWin32Error());
         }
         return encodedData;
     }
 }
 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;
 }
 private unsafe void EncryptContent(CmsRecipientCollection recipients)
 {
     CMSG_ENCRYPT_PARAM encryptParam = new CMSG_ENCRYPT_PARAM();
     if (recipients.Count < 1)
     {
         throw new CryptographicException(-2146889717);
     }
     CmsRecipientEnumerator enumerator = recipients.GetEnumerator();
     while (enumerator.MoveNext())
     {
         CmsRecipient current = enumerator.Current;
         if (current.Certificate == null)
         {
             throw new ArgumentNullException(SecurityResources.GetResourceString("Cryptography_Cms_RecipientCertificateNotFound"));
         }
         if ((PkcsUtils.GetRecipientInfoType(current.Certificate) == RecipientInfoType.KeyAgreement) || (current.RecipientIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier))
         {
             encryptParam.useCms = true;
         }
     }
     if (!encryptParam.useCms && ((this.Certificates.Count > 0) || (this.UnprotectedAttributes.Count > 0)))
     {
         encryptParam.useCms = true;
     }
     if (encryptParam.useCms && !PkcsUtils.CmsSupported())
     {
         throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Cms_Not_Supported"));
     }
     System.Security.Cryptography.CAPI.CMSG_ENVELOPED_ENCODE_INFO structure = new System.Security.Cryptography.CAPI.CMSG_ENVELOPED_ENCODE_INFO(Marshal.SizeOf(typeof(System.Security.Cryptography.CAPI.CMSG_ENVELOPED_ENCODE_INFO)));
     System.Security.Cryptography.SafeLocalAllocHandle handle = System.Security.Cryptography.CAPI.LocalAlloc(0x40, new IntPtr(Marshal.SizeOf(typeof(System.Security.Cryptography.CAPI.CMSG_ENVELOPED_ENCODE_INFO))));
     SetCspParams(this.ContentEncryptionAlgorithm, ref encryptParam);
     structure.ContentEncryptionAlgorithm.pszObjId = this.ContentEncryptionAlgorithm.Oid.Value;
     if ((encryptParam.pvEncryptionAuxInfo != null) && !encryptParam.pvEncryptionAuxInfo.IsInvalid)
     {
         structure.pvEncryptionAuxInfo = encryptParam.pvEncryptionAuxInfo.DangerousGetHandle();
     }
     structure.cRecipients = (uint) recipients.Count;
     List<System.Security.Cryptography.SafeCertContextHandle> certContexts = null;
     if (encryptParam.useCms)
     {
         SetCmsRecipientParams(recipients, this.Certificates, this.UnprotectedAttributes, this.ContentEncryptionAlgorithm, ref encryptParam);
         structure.rgCmsRecipients = encryptParam.rgpRecipients.DangerousGetHandle();
         if ((encryptParam.rgCertEncoded != null) && !encryptParam.rgCertEncoded.IsInvalid)
         {
             structure.cCertEncoded = (uint) this.Certificates.Count;
             structure.rgCertEncoded = encryptParam.rgCertEncoded.DangerousGetHandle();
         }
         if ((encryptParam.rgUnprotectedAttr != null) && !encryptParam.rgUnprotectedAttr.IsInvalid)
         {
             structure.cUnprotectedAttr = (uint) this.UnprotectedAttributes.Count;
             structure.rgUnprotectedAttr = encryptParam.rgUnprotectedAttr.DangerousGetHandle();
         }
     }
     else
     {
         SetPkcs7RecipientParams(recipients, ref encryptParam, out certContexts);
         structure.rgpRecipients = encryptParam.rgpRecipients.DangerousGetHandle();
     }
     Marshal.StructureToPtr(structure, handle.DangerousGetHandle(), false);
     try
     {
         System.Security.Cryptography.SafeCryptMsgHandle handle2 = System.Security.Cryptography.CAPI.CryptMsgOpenToEncode(0x10001, 0, 3, handle.DangerousGetHandle(), this.ContentInfo.ContentType.Value, IntPtr.Zero);
         if ((handle2 == null) || handle2.IsInvalid)
         {
             throw new CryptographicException(Marshal.GetLastWin32Error());
         }
         if ((this.m_safeCryptMsgHandle != null) && !this.m_safeCryptMsgHandle.IsInvalid)
         {
             this.m_safeCryptMsgHandle.Dispose();
         }
         this.m_safeCryptMsgHandle = handle2;
     }
     finally
     {
         Marshal.DestroyStructure(handle.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CMSG_ENVELOPED_ENCODE_INFO));
         handle.Dispose();
     }
     byte[] encodedData = new byte[0];
     if (string.Compare(this.ContentInfo.ContentType.Value, "1.2.840.113549.1.7.1", StringComparison.OrdinalIgnoreCase) == 0)
     {
         byte[] content = this.ContentInfo.Content;
         fixed (byte* numRef = content)
         {
             System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB cryptoapi_blob = new System.Security.Cryptography.CAPI.CRYPTOAPI_BLOB {
                 cbData = (uint) content.Length,
                 pbData = new IntPtr((void*) numRef)
             };
             if (!System.Security.Cryptography.CAPI.EncodeObject(new IntPtr(0x19L), new IntPtr((void*) &cryptoapi_blob), out encodedData))
             {
                 throw new CryptographicException(Marshal.GetLastWin32Error());
             }
         }
     }
     else
     {
         encodedData = this.ContentInfo.Content;
     }
     if ((encodedData.Length > 0) && !System.Security.Cryptography.CAPI.CAPISafe.CryptMsgUpdate(this.m_safeCryptMsgHandle, encodedData, (uint) encodedData.Length, true))
     {
         throw new CryptographicException(Marshal.GetLastWin32Error());
     }
     GC.KeepAlive(encryptParam);
     GC.KeepAlive(recipients);
     GC.KeepAlive(certContexts);
 }