예제 #1
0
 private static IntPtr GetDynamicMethodAddress(MethodBase method)
 {
     unsafe
     {
         var handle = GetDynamicMethodRuntimeHandle(method);
         var ptr    = (byte *)handle.Value.ToPointer();
         if (IsNet20Sp2OrGreater())
         {
             RuntimeHelpers.PrepareMethod(handle);
             return(handle.GetFunctionPointer());
         }
         else
         {
             if (IntPtr.Size == 8)
             {
                 var address = (ulong *)ptr;
                 address = (ulong *)*(address + 5);
                 return(new IntPtr(address + 12));
             }
             else
             {
                 var address = (uint *)ptr;
                 address = (uint *)*(address + 5);
                 return(new IntPtr(address + 12));
             }
         }
     }
 }
예제 #2
0
 /// <summary>
 /// Returns the internal array to the pool and replaces it with a zero length array.
 /// </summary>
 public void Dispose()
 {
     T[] oldItems = _items;
     _size  = 0;
     _items = s_emptyArray;
     _version++;
     Pool.Return(oldItems, RuntimeHelpers.IsReferenceOrContainsReferences <T>());
 }
예제 #3
0
        /// <summary>
        /// Gets the address of the method stub
        /// </summary>
        /// <param name="method">The method handle.</param>
        /// <returns></returns>
        public static IntPtr GetMethodAddress(MethodBase method)
        {
            if ((method is DynamicMethod))
            {
                return(GetDynamicMethodAddress(method));
            }

            // Prepare the method so it gets jited
            RuntimeHelpers.PrepareMethod(method.MethodHandle);
            return(method.MethodHandle.GetFunctionPointer());
        }
예제 #4
0
        private static IntPtr GetDynamicMethodAddress(MethodBase method)
        {
            unsafe
            {
                RuntimeMethodHandle handle = GetDynamicMethodRuntimeHandle(method);
                byte *ptr = (byte *)handle.Value.ToPointer();

                if (IsNet20Sp2OrGreater())
                {
                    RuntimeHelpers.PrepareMethod(handle);
                    return(handle.GetFunctionPointer());

                    //if (IntPtr.Size == 8)
                    //{
                    //    ulong* address = (ulong*)ptr;
                    //    address = (ulong*)*(address + 5);
                    //    return new IntPtr(address + 12);
                    //}
                    //else
                    //{
                    //    uint* address = (uint*)ptr;
                    //    address = (uint*)*(address + 5);
                    //    return new IntPtr(address + 12);
                    //}
                }
                else
                {
                    if (IntPtr.Size == 8)
                    {
                        ulong *address = (ulong *)ptr;
                        address += 6;
                        return(new IntPtr(address));
                    }
                    else
                    {
                        uint *address = (uint *)ptr;
                        address += 6;
                        return(new IntPtr(address));
                    }
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Gets the address of the method stub
        /// </summary>
        /// <param name="method">The method handle.</param>
        /// <returns></returns>
        public static IntPtr GetMethodAddress(MethodBase method)
        {
            if ((method is DynamicMethod))
            {
                return(GetDynamicMethodAddress(method));
            }

            // Prepare the method so it gets jited
            RuntimeHelpers.PrepareMethod(method.MethodHandle);

            // If 3.5 sp1 or greater than we have a different layout in memory.
            if (IsNet20Sp2OrGreater())
            {
                return(GetMethodAddress20SP2(method));
            }

            unsafe
            {
                // Skip these
                const int skip = 10;

                // Read the method index.
                var location = (UInt64 *)(method.MethodHandle.Value.ToPointer());
                var index    = (int)(((*location) >> 32) & 0xFF);

                if (IntPtr.Size == 8)
                {
                    // Get the method table
                    var classStart = (ulong *)method.DeclaringType.TypeHandle.Value.ToPointer();
                    var address    = classStart + index + skip;
                    return(new IntPtr(address));
                }
                else
                {
                    // Get the method table
                    uint *classStart = (uint *)method.DeclaringType.TypeHandle.Value.ToPointer();
                    uint *address    = classStart + index + skip;
                    return(new IntPtr(address));
                }
            }
        }
예제 #6
0
        internal static byte[] CreateSelfSignCertificatePfx(
            string x500,
            DateTime startTime,
            DateTime endTime,
            SecureString password)
        {
            byte[] pfxData;

            if (x500 == null)
            {
                x500 = "";
            }

            SystemTime startSystemTime = ToSystemTime(startTime);
            SystemTime endSystemTime   = ToSystemTime(endTime);
            string     containerName   = Guid.NewGuid().ToString();

            GCHandle dataHandle       = new GCHandle();
            IntPtr   providerContext  = IntPtr.Zero;
            IntPtr   cryptKey         = IntPtr.Zero;
            IntPtr   certContext      = IntPtr.Zero;
            IntPtr   certStore        = IntPtr.Zero;
            IntPtr   storeCertContext = IntPtr.Zero;
            IntPtr   passwordPtr      = IntPtr.Zero;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                Check(NativeMethods.CryptAcquireContextW(
                          out providerContext,
                          containerName,
                          null,
                          1,   // PROV_RSA_FULL
                          8)); // CRYPT_NEWKEYSET

                Check(NativeMethods.CryptGenKey(
                          providerContext,
                          1,                // AT_KEYEXCHANGE
                          1 | (2048 << 16), // CRYPT_EXPORTABLE | 2048bit
                          out cryptKey));

                IntPtr errorStringPtr;
                int    nameDataLength = 0;
                byte[] nameData;

                // errorStringPtr gets a pointer into the middle of the x500 string,
                // so x500 needs to be pinned until after we've copied the value
                // of errorStringPtr.
                dataHandle = GCHandle.Alloc(x500, GCHandleType.Pinned);

                if (!NativeMethods.CertStrToNameW(
                        0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
                        dataHandle.AddrOfPinnedObject(),
                        3,          // CERT_X500_NAME_STR = 3
                        IntPtr.Zero,
                        null,
                        ref nameDataLength,
                        out errorStringPtr))
                {
                    string error = Marshal.PtrToStringUni(errorStringPtr);
                    throw new ArgumentException(error);
                }

                nameData = new byte[nameDataLength];

                if (!NativeMethods.CertStrToNameW(
                        0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
                        dataHandle.AddrOfPinnedObject(),
                        3,          // CERT_X500_NAME_STR = 3
                        IntPtr.Zero,
                        nameData,
                        ref nameDataLength,
                        out errorStringPtr))
                {
                    string error = Marshal.PtrToStringUni(errorStringPtr);
                    throw new ArgumentException(error);
                }

                dataHandle.Free();

                dataHandle = GCHandle.Alloc(nameData, GCHandleType.Pinned);
                CryptoApiBlob nameBlob = new CryptoApiBlob(
                    nameData.Length,
                    dataHandle.AddrOfPinnedObject());

                CryptKeyProviderInformation kpi = new CryptKeyProviderInformation();
                kpi.ContainerName = containerName;
                kpi.ProviderType  = 1; // PROV_RSA_FULL
                kpi.KeySpec       = 1; // AT_KEYEXCHANGE

                certContext = NativeMethods.CertCreateSelfSignCertificate(
                    providerContext,
                    ref nameBlob,
                    0,
                    ref kpi,
                    IntPtr.Zero, // default = SHA1RSA
                    ref startSystemTime,
                    ref endSystemTime,
                    IntPtr.Zero);
                Check(certContext != IntPtr.Zero);
                dataHandle.Free();

                certStore = NativeMethods.CertOpenStore(
                    "Memory", // sz_CERT_STORE_PROV_MEMORY
                    0,
                    IntPtr.Zero,
                    0x2000, // CERT_STORE_CREATE_NEW_FLAG
                    IntPtr.Zero);
                Check(certStore != IntPtr.Zero);

                Check(NativeMethods.CertAddCertificateContextToStore(
                          certStore,
                          certContext,
                          1, // CERT_STORE_ADD_NEW
                          out storeCertContext));

                NativeMethods.CertSetCertificateContextProperty(
                    storeCertContext,
                    2, // CERT_KEY_PROV_INFO_PROP_ID
                    0,
                    ref kpi);

                if (password != null)
                {
                    passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password);
                }

                CryptoApiBlob pfxBlob = new CryptoApiBlob();
                Check(NativeMethods.PFXExportCertStoreEx(
                          certStore,
                          ref pfxBlob,
                          passwordPtr,
                          IntPtr.Zero,
                          7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY

                pfxData      = new byte[pfxBlob.DataLength];
                dataHandle   = GCHandle.Alloc(pfxData, GCHandleType.Pinned);
                pfxBlob.Data = dataHandle.AddrOfPinnedObject();
                Check(NativeMethods.PFXExportCertStoreEx(
                          certStore,
                          ref pfxBlob,
                          passwordPtr,
                          IntPtr.Zero,
                          7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY
                dataHandle.Free();
            }
            finally
            {
                if (passwordPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(passwordPtr);
                }

                if (dataHandle.IsAllocated)
                {
                    dataHandle.Free();
                }

                if (certContext != IntPtr.Zero)
                {
                    NativeMethods.CertFreeCertificateContext(certContext);
                }

                if (storeCertContext != IntPtr.Zero)
                {
                    NativeMethods.CertFreeCertificateContext(storeCertContext);
                }

                if (certStore != IntPtr.Zero)
                {
                    NativeMethods.CertCloseStore(certStore, 0);
                }

                if (cryptKey != IntPtr.Zero)
                {
                    NativeMethods.CryptDestroyKey(cryptKey);
                }

                if (providerContext != IntPtr.Zero)
                {
                    NativeMethods.CryptReleaseContext(providerContext, 0);
                    NativeMethods.CryptAcquireContextW(
                        out providerContext,
                        containerName,
                        null,
                        1,     // PROV_RSA_FULL
                        0x10); // CRYPT_DELETEKEYSET
                }
            }

            return(pfxData);
        }
예제 #7
0
 int IEqualityComparer.GetHashCode(object obj)
 {
     return(RuntimeHelpers.GetHashCode(obj));
 }
예제 #8
0
 public int GetHashCode(T obj)
 {
     return(RuntimeHelpers.GetHashCode(obj));
 }
예제 #9
0
        /// <summary>建立自签名证书</summary>
        /// <param name="distName"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static Byte[] CreateSelfSignCertificatePfx(X500DistinguishedName distName, DateTime startTime, DateTime endTime, SecureString password)
        {
            var containerName = Guid.NewGuid().ToString();

            var dataHandle       = new GCHandle();
            var providerContext  = IntPtr.Zero;
            var cryptKey         = IntPtr.Zero;
            var certContext      = IntPtr.Zero;
            var certStore        = IntPtr.Zero;
            var storeCertContext = IntPtr.Zero;
            var passwordPtr      = IntPtr.Zero;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                Check(NativeMethods.CryptAcquireContextW(
                          out providerContext,
                          containerName,
                          null,
                          1,   // PROV_RSA_FULL
                          8)); // CRYPT_NEWKEYSET

                Check(NativeMethods.CryptGenKey(
                          providerContext,
                          1, // AT_KEYEXCHANGE
                          1, // CRYPT_EXPORTABLE
                          out cryptKey));

                var nameData = distName.RawData;

                dataHandle = GCHandle.Alloc(nameData, GCHandleType.Pinned);
                var nameBlob = new CryptoApiBlob(nameData.Length, dataHandle.AddrOfPinnedObject());

                var kpi = new CryptKeyProviderInformation
                {
                    ContainerName = containerName,
                    ProviderType  = 1, // PROV_RSA_FULL
                    KeySpec       = 1  // AT_KEYEXCHANGE
                };

                var startSystemTime = ToSystemTime(startTime);
                var endSystemTime   = ToSystemTime(endTime);
                certContext = NativeMethods.CertCreateSelfSignCertificate(
                    providerContext,
                    ref nameBlob,
                    0,
                    ref kpi,
                    IntPtr.Zero, // default = SHA1RSA
                    ref startSystemTime,
                    ref endSystemTime,
                    IntPtr.Zero);
                Check(certContext != IntPtr.Zero);
                dataHandle.Free();

                certStore = NativeMethods.CertOpenStore(
                    "Memory", // sz_CERT_STORE_PROV_MEMORY
                    0,
                    IntPtr.Zero,
                    0x2000, // CERT_STORE_CREATE_NEW_FLAG
                    IntPtr.Zero);
                Check(certStore != IntPtr.Zero);

                Check(NativeMethods.CertAddCertificateContextToStore(
                          certStore,
                          certContext,
                          1, // CERT_STORE_ADD_NEW
                          out storeCertContext));

                NativeMethods.CertSetCertificateContextProperty(
                    storeCertContext,
                    2, // CERT_KEY_PROV_INFO_PROP_ID
                    0,
                    ref kpi);

                if (password != null)
                {
                    passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password);
                }

                var pfxBlob = new CryptoApiBlob();
                Check(NativeMethods.PFXExportCertStoreEx(
                          certStore,
                          ref pfxBlob,
                          passwordPtr,
                          IntPtr.Zero,
                          7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY

                var pfxData = new Byte[pfxBlob.DataLength];
                dataHandle   = GCHandle.Alloc(pfxData, GCHandleType.Pinned);
                pfxBlob.Data = dataHandle.AddrOfPinnedObject();
                Check(NativeMethods.PFXExportCertStoreEx(
                          certStore,
                          ref pfxBlob,
                          passwordPtr,
                          IntPtr.Zero,
                          7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY
                dataHandle.Free();

                return(pfxData);
            }
            finally
            {
                if (passwordPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(passwordPtr);
                }

                if (dataHandle.IsAllocated)
                {
                    dataHandle.Free();
                }

                if (certContext != IntPtr.Zero)
                {
                    NativeMethods.CertFreeCertificateContext(certContext);
                }

                if (storeCertContext != IntPtr.Zero)
                {
                    NativeMethods.CertFreeCertificateContext(storeCertContext);
                }

                if (certStore != IntPtr.Zero)
                {
                    NativeMethods.CertCloseStore(certStore, 0);
                }

                if (cryptKey != IntPtr.Zero)
                {
                    NativeMethods.CryptDestroyKey(cryptKey);
                }

                if (providerContext != IntPtr.Zero)
                {
                    NativeMethods.CryptReleaseContext(providerContext, 0);
                    NativeMethods.CryptAcquireContextW(
                        out providerContext,
                        containerName,
                        null,
                        1,     // PROV_RSA_FULL
                        0x10); // CRYPT_DELETEKEYSET
                }
            }
        }
예제 #10
0
        /// <summary>
        /// Creates the self sign certificate PFX.
        /// </summary>
        /// <param name="x500">The X500.</param>
        /// <param name="startTime">The start time.</param>
        /// <param name="endTime">The end time.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">
        /// </exception>
        public static byte[] CreateSelfSignCertificatePfx(
            string x500,
            DateTime startTime,
            DateTime endTime,
            SecureString password)
        {
            byte[] pfxData;

            if (x500 == null)
            {
                x500 = "";
            }

#if NETCOREAPP3_1
            SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
            sanBuilder.AddIpAddress(IPAddress.Loopback);
            sanBuilder.AddIpAddress(IPAddress.IPv6Loopback);
            sanBuilder.AddDnsName("localhost");
            sanBuilder.AddDnsName(Environment.MachineName);

            X500DistinguishedName distinguishedName = new X500DistinguishedName(x500);

            using (RSA rsa = RSA.Create(2048))
            {
                var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

                request.CertificateExtensions.Add(
                    new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));


                request.CertificateExtensions.Add(
                    new X509EnhancedKeyUsageExtension(
                        new OidCollection {
                    new Oid("1.3.6.1.5.5.7.3.1")
                }, false));

                request.CertificateExtensions.Add(sanBuilder.Build());

                var certificate = request.CreateSelfSigned(new DateTimeOffset(startTime), new DateTimeOffset(endTime));
                certificate.FriendlyName = "Generated Certificate";

                pfxData = certificate.Export(X509ContentType.Pfx, password);
            }
#else
            SystemTime startSystemTime = ToSystemTime(startTime);
            SystemTime endSystemTime   = ToSystemTime(endTime);
            string     containerName   = Guid.NewGuid().ToString();

            GCHandle dataHandle       = new GCHandle();
            IntPtr   providerContext  = IntPtr.Zero;
            IntPtr   cryptKey         = IntPtr.Zero;
            IntPtr   certContext      = IntPtr.Zero;
            IntPtr   certStore        = IntPtr.Zero;
            IntPtr   storeCertContext = IntPtr.Zero;
            IntPtr   passwordPtr      = IntPtr.Zero;
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                Check(NativeMethods.CryptAcquireContextW(
                          out providerContext,
                          containerName,
                          null,
                          1,   // PROV_RSA_FULL, 2048 bit type: 1 | (2048<<16)
                          8)); // CRYPT_NEWKEYSET

                Check(NativeMethods.CryptGenKey(
                          providerContext,
                          1, // AT_KEYEXCHANGE
                          1, // CRYPT_EXPORTABLE
                          out cryptKey));

                IntPtr errorStringPtr;
                int    nameDataLength = 0;
                byte[] nameData;

                // errorStringPtr gets a pointer into the middle of the x500 string,
                // so x500 needs to be pinned until after we've copied the value
                // of errorStringPtr.
                dataHandle = GCHandle.Alloc(x500, GCHandleType.Pinned);

                if (!NativeMethods.CertStrToNameW(
                        0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
                        dataHandle.AddrOfPinnedObject(),
                        3,          // CERT_X500_NAME_STR = 3
                        IntPtr.Zero,
                        null,
                        ref nameDataLength,
                        out errorStringPtr))
                {
                    string error = Marshal.PtrToStringUni(errorStringPtr);
                    throw new ArgumentException(error);
                }

                nameData = new byte[nameDataLength];

                if (!NativeMethods.CertStrToNameW(
                        0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
                        dataHandle.AddrOfPinnedObject(),
                        3,          // CERT_X500_NAME_STR = 3
                        IntPtr.Zero,
                        nameData,
                        ref nameDataLength,
                        out errorStringPtr))
                {
                    string error = Marshal.PtrToStringUni(errorStringPtr);
                    throw new ArgumentException(error);
                }

                dataHandle.Free();

                dataHandle = GCHandle.Alloc(nameData, GCHandleType.Pinned);
                CryptoApiBlob nameBlob = new CryptoApiBlob(
                    nameData.Length,
                    dataHandle.AddrOfPinnedObject());

                CryptKeyProviderInformation kpi = new CryptKeyProviderInformation();
                kpi.ContainerName = containerName;
                kpi.ProviderType  = 1; // PROV_RSA_FULL
                kpi.KeySpec       = 1; // AT_KEYEXCHANGE

                certContext = NativeMethods.CertCreateSelfSignCertificate(
                    providerContext,
                    ref nameBlob,
                    0,
                    ref kpi,
                    IntPtr.Zero, // default = SHA1RSA
                    ref startSystemTime,
                    ref endSystemTime,
                    IntPtr.Zero);
                Check(certContext != IntPtr.Zero);
                dataHandle.Free();

                certStore = NativeMethods.CertOpenStore(
                    "Memory", // sz_CERT_STORE_PROV_MEMORY
                    0,
                    IntPtr.Zero,
                    0x2000, // CERT_STORE_CREATE_NEW_FLAG
                    IntPtr.Zero);
                Check(certStore != IntPtr.Zero);

                Check(NativeMethods.CertAddCertificateContextToStore(
                          certStore,
                          certContext,
                          1, // CERT_STORE_ADD_NEW
                          out storeCertContext));

                NativeMethods.CertSetCertificateContextProperty(
                    storeCertContext,
                    2, // CERT_KEY_PROV_INFO_PROP_ID
                    0,
                    ref kpi);

                if (password != null)
                {
                    passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password);
                }

                CryptoApiBlob pfxBlob = new CryptoApiBlob();
                Check(NativeMethods.PFXExportCertStoreEx(
                          certStore,
                          ref pfxBlob,
                          passwordPtr,
                          IntPtr.Zero,
                          7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY

                pfxData      = new byte[pfxBlob.DataLength];
                dataHandle   = GCHandle.Alloc(pfxData, GCHandleType.Pinned);
                pfxBlob.Data = dataHandle.AddrOfPinnedObject();
                Check(NativeMethods.PFXExportCertStoreEx(
                          certStore,
                          ref pfxBlob,
                          passwordPtr,
                          IntPtr.Zero,
                          7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY
                dataHandle.Free();
            }
            finally
            {
                if (passwordPtr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(passwordPtr);
                }

                if (dataHandle.IsAllocated)
                {
                    dataHandle.Free();
                }

                if (certContext != IntPtr.Zero)
                {
                    NativeMethods.CertFreeCertificateContext(certContext);
                }

                if (storeCertContext != IntPtr.Zero)
                {
                    NativeMethods.CertFreeCertificateContext(storeCertContext);
                }

                if (certStore != IntPtr.Zero)
                {
                    NativeMethods.CertCloseStore(certStore, 0);
                }

                if (cryptKey != IntPtr.Zero)
                {
                    NativeMethods.CryptDestroyKey(cryptKey);
                }

                if (providerContext != IntPtr.Zero)
                {
                    NativeMethods.CryptReleaseContext(providerContext, 0);
                    NativeMethods.CryptAcquireContextW(
                        out providerContext,
                        containerName,
                        null,
                        1,     // PROV_RSA_FULL
                        0x10); // CRYPT_DELETEKEYSET
                }
            }
#endif
            return(pfxData);
        }
예제 #11
0
 public override int GetHashCode()
 {
     return(RuntimeHelpers.GetHashCode(this));
 }
        public static X509Certificate2 GenerateSelfSignedCertificate(string issuerDN, DateTime?startTime = null, DateTime?endTime = null)
        {
            if (issuerDN == null)
            {
                issuerDN = String.Empty;
            }
            var startSystemTime = default(SystemTime);

            if (startTime == null || (DateTime)startTime < DateTime.FromFileTimeUtc(0))
            {
                startTime       = DateTime.FromFileTimeUtc(0);
                startSystemTime = SystemTime.Create((DateTime)startTime);
            }
            if (endTime == null)
            {
                endTime = DateTime.MaxValue;
            }
            var    endSystemTime      = SystemTime.Create((DateTime)endTime);
            string containerName      = Guid.NewGuid().ToString();
            IntPtr providerContext    = IntPtr.Zero;
            IntPtr cryptKey           = IntPtr.Zero;
            IntPtr certificateContext = IntPtr.Zero;
            IntPtr algorithmPointer   = IntPtr.Zero;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                providerContext = Externs.CryptAcquireContextW(containerName, null, 1, 0x8);
                cryptKey        = Externs.CryptGenKey(providerContext, 1, 0x8000001);
                CryptoApiBlob    nameBlob    = CryptoApiBlob.Create(issuerDN);
                CryptKeyProvInfo keyProvider = new CryptKeyProvInfo
                {
                    pwszContainerName = containerName,
                    dwProvType        = 1,
                    dwKeySpec         = 1
                };
                CryptAlgorithmIdentifier algorithm = new CryptAlgorithmIdentifier
                {
                    pszObjId   = "1.2.840.113549.1.1.13",
                    Parameters = new CryptoApiBlob()
                };
                algorithmPointer = Marshal.AllocHGlobal(Marshal.SizeOf(algorithm));
                Marshal.StructureToPtr(algorithm, algorithmPointer, false);
                certificateContext = Externs.CertCreateSelfSignCertificate(providerContext, nameBlob, 0, keyProvider, algorithmPointer,
                                                                           startSystemTime, endSystemTime, IntPtr.Zero);
                return(new X509Certificate2(certificateContext));
            }
            finally
            {
                if (certificateContext != IntPtr.Zero)
                {
                    Externs.CertFreeCertificateContext(certificateContext);
                }
                if (cryptKey != IntPtr.Zero)
                {
                    Externs.CryptDestroyKey(cryptKey);
                }
                if (providerContext != IntPtr.Zero)
                {
                    Externs.CryptReleaseContext(providerContext, 0);
                }
                if (algorithmPointer != IntPtr.Zero)
                {
                    Marshal.DestroyStructure(algorithmPointer, typeof(CryptAlgorithmIdentifier));
                    Marshal.FreeHGlobal(algorithmPointer);
                }
            }
        }
예제 #13
0
 private static int ReferenceHashCode(object o) =>
 Initial.GetHashCode(o);