Ejemplo n.º 1
0
 private static extern SafeCertContextHandle CertCreateSelfSignCertificate(SafeNCryptKeyHandle hCryptProvOrNCryptKey,
                                                                           [In] ref CRYPTOAPI_BLOB pSubjectIssuerBlob,
                                                                           X509CertificateCreationOptions dwFlags,
                                                                           [In] ref CRYPT_KEY_PROV_INFO pKeyProvInfo,
                                                                           [In] ref CRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
                                                                           [In] ref SYSTEMTIME pStartTime,
                                                                           [In] ref SYSTEMTIME pEndTime,
                                                                           [In] ref CERT_EXTENSIONS pExtensions);
Ejemplo n.º 2
0
 internal static extern SafeCertContextHandle CertCreateSelfSignCertificate(
     SafeCryptProvHandle providerHandle,
     [In] ref CRYPTOAPI_BLOB subjectIssuerBlob,
     uint flags,
     [In] ref CRYPT_KEY_PROV_INFO keyProviderInformation,
     [In] ref CRYPT_ALGORITHM_IDENTIFIER signatureAlgorithm,
     [In] ref SYSTEMTIME startTime,
     [In] ref SYSTEMTIME endTime,
     [In] ref CERT_EXTENSIONS extensions);
Ejemplo n.º 3
0
 public static extern IntPtr CertCreateSelfSignCertificate(
     SafeCryptProviderHandle hCryptProvOrNCryptKey,
     [Out] CRYPTOAPI_BLOB pSubjectIssuerBlob,
     CertCreationFlags dwFlags,
     CRYPT_KEY_PROV_INFO pKeyProvInfo,
     CRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
     SYSTEMTIME pStartTime,
     SYSTEMTIME pEndTime,
     CERT_EXTENSIONS pExtension
     );
Ejemplo n.º 4
0
 public static extern IntPtr CertCreateSelfSignCertificate(
     SafeCryptProviderHandle hCryptProvOrNCryptKey,
     [Out] CRYPTOAPI_BLOB pSubjectIssuerBlob,
     CertCreationFlags dwFlags,
     CRYPT_KEY_PROV_INFO pKeyProvInfo,
     CRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
     SYSTEMTIME pStartTime,
     SYSTEMTIME pEndTime,
     CERT_EXTENSIONS pExtension
     );
Ejemplo n.º 5
0
        internal static SafeCertificateContextHandle CreateSelfSignedCertificate(SafeNCryptKeyHandle key,
                                                                                 byte[] subjectName,
                                                                                 X509CertificateCreationOptions creationOptions,
                                                                                 string signatureAlgorithmOid,
                                                                                 DateTime startTime,
                                                                                 DateTime endTime,
                                                                                 X509ExtensionCollection extensions)
        {
            Debug.Assert(key != null, "key != null");
            Debug.Assert(!key.IsClosed && !key.IsInvalid, "!key.IsClosed && !key.IsInvalid");
            Debug.Assert(subjectName != null, "subjectName != null");
            Debug.Assert(!String.IsNullOrEmpty(signatureAlgorithmOid), "!String.IsNullOrEmpty(signatureAlgorithmOid)");
            Debug.Assert(extensions != null, "extensions != null");

            // Create an algorithm identifier structure for the signature algorithm
            CapiNative.CRYPT_ALGORITHM_IDENTIFIER nativeSignatureAlgorithm = new CapiNative.CRYPT_ALGORITHM_IDENTIFIER();
            nativeSignatureAlgorithm.pszObjId          = signatureAlgorithmOid;
            nativeSignatureAlgorithm.Parameters        = new CapiNative.CRYPTOAPI_BLOB();
            nativeSignatureAlgorithm.Parameters.cbData = 0;
            nativeSignatureAlgorithm.Parameters.pbData = IntPtr.Zero;

            // Convert the begin and expire dates to system time structures
            Win32Native.SYSTEMTIME nativeStartTime = new Win32Native.SYSTEMTIME(startTime);
            Win32Native.SYSTEMTIME nativeEndTime   = new Win32Native.SYSTEMTIME(endTime);

            // Map the extensions into CERT_EXTENSIONS.  This involves several steps to get the
            // CERT_EXTENSIONS ready for interop with the native APIs.
            //   1. Build up the CERT_EXTENSIONS structure in managed code
            //   2. For each extension, create a managed CERT_EXTENSION structure; this requires allocating
            //      native memory for the blob pointer in the CERT_EXTENSION. These extensions are stored in
            //      the nativeExtensionArray variable.
            //   3. Get a block of native memory that can hold a native array of CERT_EXTENSION structures.
            //      This is the block referenced by the CERT_EXTENSIONS structure.
            //   4. For each of the extension structures created in step 2, marshal the extension into the
            //      native buffer allocated in step 3.
            CERT_EXTENSIONS nativeExtensions = new CERT_EXTENSIONS();

            nativeExtensions.cExtension = extensions.Count;
            CERT_EXTENSION[] nativeExtensionArray = new CERT_EXTENSION[extensions.Count];

            // Run this in a CER to ensure that we release any native memory allocated for the certificate
            // extensions.
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                // Copy over each extension into a native extension structure, including allocating native
                // memory for its blob if necessary.
                for (int i = 0; i < extensions.Count; ++i)
                {
                    nativeExtensionArray[i]           = new CERT_EXTENSION();
                    nativeExtensionArray[i].pszObjId  = extensions[i].Oid.Value;
                    nativeExtensionArray[i].fCritical = extensions[i].Critical;

                    nativeExtensionArray[i].Value        = new CapiNative.CRYPTOAPI_BLOB();
                    nativeExtensionArray[i].Value.cbData = extensions[i].RawData.Length;
                    if (nativeExtensionArray[i].Value.cbData > 0)
                    {
                        nativeExtensionArray[i].Value.pbData =
                            Marshal.AllocCoTaskMem(nativeExtensionArray[i].Value.cbData);
                        Marshal.Copy(extensions[i].RawData,
                                     0,
                                     nativeExtensionArray[i].Value.pbData,
                                     nativeExtensionArray[i].Value.cbData);
                    }
                }

                // Now that we've built up the extension array, create a block of native memory to marshal
                // them into.
                if (nativeExtensionArray.Length > 0)
                {
                    checked
                    {
                        // CERT_EXTENSION structures end with a pointer field, which means on all supported
                        // platforms they won't require any padding between elements of the array.
                        nativeExtensions.rgExtension =
                            Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(CERT_EXTENSION)) * nativeExtensionArray.Length);

                        for (int i = 0; i < nativeExtensionArray.Length; ++i)
                        {
                            ulong  offset            = (uint)i * (uint)Marshal.SizeOf(typeof(CERT_EXTENSION));
                            ulong  next              = offset + (ulong)nativeExtensions.rgExtension.ToInt64();
                            IntPtr nextExtensionAddr = new IntPtr((long)next);

                            Marshal.StructureToPtr(nativeExtensionArray[i], nextExtensionAddr, false);
                        }
                    }
                }

                //
                // Now that all of the needed data structures are setup, we can create the certificate
                //

                unsafe
                {
                    fixed(byte *pSubjectName = &subjectName[0])
                    {
                        // Create a CRYPTOAPI_BLOB for the subject of the cert
                        CapiNative.CRYPTOAPI_BLOB nativeSubjectName = new CapiNative.CRYPTOAPI_BLOB();
                        nativeSubjectName.cbData = subjectName.Length;
                        nativeSubjectName.pbData = new IntPtr(pSubjectName);

                        // Now that we've converted all the inputs to native data structures, we can generate
                        // the self signed certificate for the input key.
                        SafeCertificateContextHandle selfSignedCertHandle =
                            UnsafeNativeMethods.CertCreateSelfSignCertificate(key,
                                                                              ref nativeSubjectName,
                                                                              creationOptions,
                                                                              IntPtr.Zero,
                                                                              ref nativeSignatureAlgorithm,
                                                                              ref nativeStartTime,
                                                                              ref nativeEndTime,
                                                                              ref nativeExtensions);

                        if (selfSignedCertHandle.IsInvalid)
                        {
                            throw new CryptographicException(Marshal.GetLastWin32Error());
                        }

                        return(selfSignedCertHandle);
                    }
                }
            }
            finally
            {
                //
                // In order to release all resources held by the CERT_EXTENSIONS we need to do three things
                //   1. Destroy each structure marshaled into the native CERT_EXTENSION array
                //   2. Release the memory used for the CERT_EXTENSION array
                //   3. Release the memory used in each individual CERT_EXTENSION
                //

                // Release each extension marshaled into the native buffer as well
                if (nativeExtensions.rgExtension != IntPtr.Zero)
                {
                    for (int i = 0; i < nativeExtensionArray.Length; ++i)
                    {
                        ulong  offset            = (uint)i * (uint)Marshal.SizeOf(typeof(CERT_EXTENSION));
                        ulong  next              = offset + (ulong)nativeExtensions.rgExtension.ToInt64();
                        IntPtr nextExtensionAddr = new IntPtr((long)next);

                        Marshal.DestroyStructure(nextExtensionAddr, typeof(CERT_EXTENSION));
                    }

                    Marshal.FreeCoTaskMem(nativeExtensions.rgExtension);
                }

                // If we allocated memory for any extensions, make sure to free it now
                for (int i = 0; i < nativeExtensionArray.Length; ++i)
                {
                    if (nativeExtensionArray[i].Value.pbData != IntPtr.Zero)
                    {
                        Marshal.FreeCoTaskMem(nativeExtensionArray[i].Value.pbData);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        internal static SafeCertContextHandle CreateSelfSignedCertificate(CngKey key,
                                                                          bool takeOwnershipOfKey,
                                                                          byte[] subjectName,
                                                                          X509CertificateCreationOptions creationOptions,
                                                                          string signatureAlgorithmOid,
                                                                          DateTime startTime,
                                                                          DateTime endTime,
                                                                          X509ExtensionCollection extensions)
        {
            Debug.Assert(key != null, "key != null");
            Debug.Assert(subjectName != null, "subjectName != null");
            Debug.Assert(!String.IsNullOrEmpty(signatureAlgorithmOid), "!String.IsNullOrEmpty(signatureAlgorithmOid)");
            Debug.Assert(extensions != null, "extensions != null");

            // Create an algorithm identifier structure for the signature algorithm
            CapiNative.CRYPT_ALGORITHM_IDENTIFIER nativeSignatureAlgorithm = new CapiNative.CRYPT_ALGORITHM_IDENTIFIER();
            nativeSignatureAlgorithm.pszObjId          = signatureAlgorithmOid;
            nativeSignatureAlgorithm.Parameters        = new CapiNative.CRYPTOAPI_BLOB();
            nativeSignatureAlgorithm.Parameters.cbData = 0;
            nativeSignatureAlgorithm.Parameters.pbData = IntPtr.Zero;

            // Convert the begin and expire dates to system time structures
            Win32Native.SYSTEMTIME nativeStartTime = new Win32Native.SYSTEMTIME(startTime);
            Win32Native.SYSTEMTIME nativeEndTime   = new Win32Native.SYSTEMTIME(endTime);

            // Map the extensions into CERT_EXTENSIONS.  This involves several steps to get the
            // CERT_EXTENSIONS ready for interop with the native APIs.
            //   1. Build up the CERT_EXTENSIONS structure in managed code
            //   2. For each extension, create a managed CERT_EXTENSION structure; this requires allocating
            //      native memory for the blob pointer in the CERT_EXTENSION. These extensions are stored in
            //      the nativeExtensionArray variable.
            //   3. Get a block of native memory that can hold a native array of CERT_EXTENSION structures.
            //      This is the block referenced by the CERT_EXTENSIONS structure.
            //   4. For each of the extension structures created in step 2, marshal the extension into the
            //      native buffer allocated in step 3.
            CERT_EXTENSIONS nativeExtensions = new CERT_EXTENSIONS();

            nativeExtensions.cExtension = extensions.Count;
            CERT_EXTENSION[] nativeExtensionArray = new CERT_EXTENSION[extensions.Count];

            // Run this in a CER to ensure that we release any native memory allocated for the certificate
            // extensions.
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                // Copy over each extension into a native extension structure, including allocating native
                // memory for its blob if necessary.
                for (int i = 0; i < extensions.Count; ++i)
                {
                    nativeExtensionArray[i]           = new CERT_EXTENSION();
                    nativeExtensionArray[i].pszObjId  = extensions[i].Oid.Value;
                    nativeExtensionArray[i].fCritical = extensions[i].Critical;

                    nativeExtensionArray[i].Value        = new CapiNative.CRYPTOAPI_BLOB();
                    nativeExtensionArray[i].Value.cbData = extensions[i].RawData.Length;
                    if (nativeExtensionArray[i].Value.cbData > 0)
                    {
                        nativeExtensionArray[i].Value.pbData =
                            Marshal.AllocCoTaskMem(nativeExtensionArray[i].Value.cbData);
                        Marshal.Copy(extensions[i].RawData,
                                     0,
                                     nativeExtensionArray[i].Value.pbData,
                                     nativeExtensionArray[i].Value.cbData);
                    }
                }

                // Now that we've built up the extension array, create a block of native memory to marshal
                // them into.
                if (nativeExtensionArray.Length > 0)
                {
                    checked
                    {
                        // CERT_EXTENSION structures end with a pointer field, which means on all supported
                        // platforms they won't require any padding between elements of the array.
                        nativeExtensions.rgExtension =
                            Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(CERT_EXTENSION)) * nativeExtensionArray.Length);

                        for (int i = 0; i < nativeExtensionArray.Length; ++i)
                        {
                            ulong  offset            = (uint)i * (uint)Marshal.SizeOf(typeof(CERT_EXTENSION));
                            ulong  next              = offset + (ulong)nativeExtensions.rgExtension.ToInt64();
                            IntPtr nextExtensionAddr = new IntPtr((long)next);

                            Marshal.StructureToPtr(nativeExtensionArray[i], nextExtensionAddr, false);
                        }
                    }
                }

                // Setup a CRYPT_KEY_PROV_INFO for the key
                CRYPT_KEY_PROV_INFO keyProvInfo = new CRYPT_KEY_PROV_INFO();
                keyProvInfo.pwszContainerName = key.UniqueName;
                keyProvInfo.pwszProvName      = key.Provider.Provider;
                keyProvInfo.dwProvType        = 0; // NCRYPT
                keyProvInfo.dwFlags           = 0;
                keyProvInfo.cProvParam        = 0;
                keyProvInfo.rgProvParam       = IntPtr.Zero;
                keyProvInfo.dwKeySpec         = 0;

                //
                // Now that all of the needed data structures are setup, we can create the certificate
                //

                SafeCertContextHandle selfSignedCertHandle = null;
                unsafe
                {
                    fixed(byte *pSubjectName = &subjectName[0])
                    {
                        // Create a CRYPTOAPI_BLOB for the subject of the cert
                        CapiNative.CRYPTOAPI_BLOB nativeSubjectName = new CapiNative.CRYPTOAPI_BLOB();
                        nativeSubjectName.cbData = subjectName.Length;
                        nativeSubjectName.pbData = new IntPtr(pSubjectName);

                        // Now that we've converted all the inputs to native data structures, we can generate
                        // the self signed certificate for the input key.
                        using (SafeNCryptKeyHandle keyHandle = key.Handle)
                        {
                            selfSignedCertHandle =
                                UnsafeNativeMethods.CertCreateSelfSignCertificate(keyHandle,
                                                                                  ref nativeSubjectName,
                                                                                  creationOptions,
                                                                                  ref keyProvInfo,
                                                                                  ref nativeSignatureAlgorithm,
                                                                                  ref nativeStartTime,
                                                                                  ref nativeEndTime,
                                                                                  ref nativeExtensions);
                            if (selfSignedCertHandle.IsInvalid)
                            {
                                throw new CryptographicException(Marshal.GetLastWin32Error());
                            }
                        }
                    }
                }

                Debug.Assert(selfSignedCertHandle != null, "selfSignedCertHandle != null");

                // Attach a key context to the certificate which will allow Windows to find the private key
                // associated with the certificate if the NCRYPT_KEY_HANDLE is ephemeral.
                // is done.
                using (SafeNCryptKeyHandle keyHandle = key.Handle)
                {
                    CERT_KEY_CONTEXT keyContext = new CERT_KEY_CONTEXT();
                    keyContext.cbSize     = Marshal.SizeOf(typeof(CERT_KEY_CONTEXT));
                    keyContext.hNCryptKey = keyHandle.DangerousGetHandle();
                    keyContext.dwKeySpec  = KeySpec.NCryptKey;

                    bool attachedProperty = false;
                    int  setContextError  = 0;

                    // Run in a CER to ensure accurate tracking of the transfer of handle ownership
                    RuntimeHelpers.PrepareConstrainedRegions();
                    try { }
                    finally
                    {
                        CertificatePropertySetFlags flags = CertificatePropertySetFlags.None;
                        if (!takeOwnershipOfKey)
                        {
                            // If the certificate is not taking ownership of the key handle, then it should
                            // not release the handle when the context is released.
                            flags |= CertificatePropertySetFlags.NoCryptRelease;
                        }

                        attachedProperty =
                            UnsafeNativeMethods.CertSetCertificateContextProperty(selfSignedCertHandle,
                                                                                  CertificateProperty.KeyContext,
                                                                                  flags,
                                                                                  ref keyContext);
                        setContextError = Marshal.GetLastWin32Error();

                        // If we succesfully transferred ownership of the key to the certificate,
                        // then we need to ensure that we no longer release its handle.
                        if (attachedProperty && takeOwnershipOfKey)
                        {
                            keyHandle.SetHandleAsInvalid();
                        }
                    }

                    if (!attachedProperty)
                    {
                        throw new CryptographicException(setContextError);
                    }
                }

                return(selfSignedCertHandle);
            }
            finally
            {
                //
                // In order to release all resources held by the CERT_EXTENSIONS we need to do three things
                //   1. Destroy each structure marshaled into the native CERT_EXTENSION array
                //   2. Release the memory used for the CERT_EXTENSION array
                //   3. Release the memory used in each individual CERT_EXTENSION
                //

                // Release each extension marshaled into the native buffer as well
                if (nativeExtensions.rgExtension != IntPtr.Zero)
                {
                    for (int i = 0; i < nativeExtensionArray.Length; ++i)
                    {
                        ulong  offset            = (uint)i * (uint)Marshal.SizeOf(typeof(CERT_EXTENSION));
                        ulong  next              = offset + (ulong)nativeExtensions.rgExtension.ToInt64();
                        IntPtr nextExtensionAddr = new IntPtr((long)next);

                        Marshal.DestroyStructure(nextExtensionAddr, typeof(CERT_EXTENSION));
                    }

                    Marshal.FreeCoTaskMem(nativeExtensions.rgExtension);
                }

                // If we allocated memory for any extensions, make sure to free it now
                for (int i = 0; i < nativeExtensionArray.Length; ++i)
                {
                    if (nativeExtensionArray[i].Value.pbData != IntPtr.Zero)
                    {
                        Marshal.FreeCoTaskMem(nativeExtensionArray[i].Value.pbData);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        // returns a list of IntPtr's; the first IntPtr is the pointer to the CERT_EXTENSIONS
        // strucuture; the other pointers are pointers that have to be released in order
        // to avoid leaking memory
        private static unsafe List<IntPtr> ConvertExtensions(X509ExtensionCollection extensions)
        {
            List<IntPtr> ret = new List<IntPtr>();
            if (extensions == null && extensions.Count == 0) {
                ret.Add(IntPtr.Zero);
                return ret;
            }

            int extensionStructSize = Marshal.SizeOf(typeof(CERT_EXTENSION));
            // create the pointer to the CERT_EXTENSIONS object
            CERT_EXTENSIONS extensionsStruct = new CERT_EXTENSIONS();
            IntPtr extensionsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CERT_EXTENSIONS)));
            ret.Add(extensionsPtr);
            extensionsStruct.cExtension = extensions.Count;
            extensionsStruct.rgExtension = Marshal.AllocHGlobal(extensionStructSize * extensions.Count); ;
            ret.Add(extensionsStruct.rgExtension);
            Marshal.StructureToPtr(extensionsStruct, extensionsPtr, false);

            // create the array of CERT_EXTENSION objects
            CERT_EXTENSION extensionStruct = new CERT_EXTENSION();
            byte* workPointer = (byte*)extensionsStruct.rgExtension.ToPointer();
            foreach(X509Extension ext in extensions) {
                // initialize the extension structure
                extensionStruct.pszObjId = Marshal.StringToHGlobalAnsi(ext.Oid.Value);
                ret.Add(extensionStruct.pszObjId);
                extensionStruct.fCritical = ext.Critical ? 1 : 0;
                byte[] rawData = ext.RawData;
                extensionStruct.cbData = rawData.Length;
                extensionStruct.pbData = Marshal.AllocHGlobal(rawData.Length); ;
                Marshal.Copy(rawData, 0, extensionStruct.pbData, rawData.Length);
                ret.Add(extensionStruct.pbData);
                // copy it to unmanaged memory
                Marshal.StructureToPtr(extensionStruct, new IntPtr(workPointer), false);
                workPointer += extensionStructSize;
            }
            // everything successfully created; return
            return ret;
        }
Ejemplo n.º 8
0
        private static SafeCertContextHandle CreateSelfSignedCertificate(CngKey key,
                                                                         bool takeOwnershipOfKey,
                                                                         byte[] subjectName,
                                                                         X509CertificateCreationOptions creationOptions,
                                                                         string signatureAlgorithmOid,
                                                                         DateTime startTime,
                                                                         DateTime endTime)
        {
            // Create an algorithm identifier structure for the signature algorithm
            CRYPT_ALGORITHM_IDENTIFIER nativeSignatureAlgorithm = new CRYPT_ALGORITHM_IDENTIFIER();
            nativeSignatureAlgorithm.pszObjId = signatureAlgorithmOid;
            nativeSignatureAlgorithm.Parameters = new CRYPTOAPI_BLOB();
            nativeSignatureAlgorithm.Parameters.cbData = 0;
            nativeSignatureAlgorithm.Parameters.pbData = IntPtr.Zero;

            // Convert the begin and expire dates to system time structures
            SYSTEMTIME nativeStartTime = new SYSTEMTIME(startTime);
            SYSTEMTIME nativeEndTime = new SYSTEMTIME(endTime);

            CERT_EXTENSIONS nativeExtensions = new CERT_EXTENSIONS();
            nativeExtensions.cExtension = 0;

            // Setup a CRYPT_KEY_PROV_INFO for the key
            CRYPT_KEY_PROV_INFO keyProvInfo = new CRYPT_KEY_PROV_INFO();
            keyProvInfo.pwszContainerName = key.UniqueName;
            keyProvInfo.pwszProvName = key.Provider.Provider;
            keyProvInfo.dwProvType = 0;     // NCRYPT
            keyProvInfo.dwFlags = 0;
            keyProvInfo.cProvParam = 0;
            keyProvInfo.rgProvParam = IntPtr.Zero;
            keyProvInfo.dwKeySpec = 0;

            //
            // Now that all of the needed data structures are setup, we can create the certificate
            //

            SafeCertContextHandle selfSignedCertHandle = null;
            unsafe
            {
                fixed (byte* pSubjectName = &subjectName[0])
                {
                    // Create a CRYPTOAPI_BLOB for the subject of the cert
                    CRYPTOAPI_BLOB nativeSubjectName = new CRYPTOAPI_BLOB();
                    nativeSubjectName.cbData = subjectName.Length;
                    nativeSubjectName.pbData = new IntPtr(pSubjectName);

                    // Now that we've converted all the inputs to native data structures, we can generate
                    // the self signed certificate for the input key.
                    using (SafeNCryptKeyHandle keyHandle = key.Handle)
                    {
                        selfSignedCertHandle = CertCreateSelfSignCertificate(keyHandle,
                                                                             ref nativeSubjectName,
                                                                             creationOptions,
                                                                             ref keyProvInfo,
                                                                             ref nativeSignatureAlgorithm,
                                                                             ref nativeStartTime,
                                                                             ref nativeEndTime,
                                                                             ref nativeExtensions);
                        if (selfSignedCertHandle.IsInvalid)
                        {
                            throw new CryptographicException(Marshal.GetLastWin32Error());
                        }
                    }
                }
            }

            Debug.Assert(selfSignedCertHandle != null, "selfSignedCertHandle != null");

            // Attach a key context to the certificate which will allow Windows to find the private key
            // associated with the certificate if the NCRYPT_KEY_HANDLE is ephemeral.
            // is done.
            using (SafeNCryptKeyHandle keyHandle = key.Handle)
            {
                CERT_KEY_CONTEXT keyContext = new CERT_KEY_CONTEXT();
                keyContext.cbSize = Marshal.SizeOf(typeof(CERT_KEY_CONTEXT));
                keyContext.hNCryptKey = keyHandle.DangerousGetHandle();
                keyContext.dwKeySpec = KeySpec.NCryptKey;

                bool attachedProperty = false;
                int setContextError = 0;

                // Run in a CER to ensure accurate tracking of the transfer of handle ownership
                RuntimeHelpers.PrepareConstrainedRegions();
                try { }
                finally
                {
                    CertificatePropertySetFlags flags = CertificatePropertySetFlags.None;
                    if (!takeOwnershipOfKey)
                    {
                        // If the certificate is not taking ownership of the key handle, then it should
                        // not release the handle when the context is released.
                        flags |= CertificatePropertySetFlags.NoCryptRelease;
                    }

                    attachedProperty = CertSetCertificateContextProperty(selfSignedCertHandle,
                                                                         CertificateProperty.KeyContext,
                                                                         flags,
                                                                         ref keyContext);
                    setContextError = Marshal.GetLastWin32Error();

                    // If we succesfully transferred ownership of the key to the certificate,
                    // then we need to ensure that we no longer release its handle.
                    if (attachedProperty && takeOwnershipOfKey)
                    {
                        keyHandle.SetHandleAsInvalid();
                    }
                }

                if (!attachedProperty)
                {
                    throw new CryptographicException(setContextError);
                }
            }

            return selfSignedCertHandle;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates the certificate and adds it to the store.
        /// </summary>
        private static string CreateSelfSignedCertificate(
            IntPtr hProvider,
            IntPtr hStore,
            bool useMachineStore,
            string applicationName,
            string applicationUri,
            string subjectName,
            IList<string> hostNames,
            ushort keySize,
            ushort lifetimeInMonths,
            ushort algorithm = 0)
        {
            IntPtr hKey = IntPtr.Zero;
            IntPtr pKpi = IntPtr.Zero;
            IntPtr pThumbprint = IntPtr.Zero;
            IntPtr pContext = IntPtr.Zero;
            IntPtr pAlgorithmId = IntPtr.Zero;
            IntPtr pNewContext = IntPtr.Zero;
            CRYPT_DATA_BLOB publicKeyId = new CRYPT_DATA_BLOB();
            CERT_NAME_BLOB subjectNameBlob = new CERT_NAME_BLOB();
            SYSTEMTIME stValidTo = new SYSTEMTIME();
            CERT_EXTENSIONS extensions = new CERT_EXTENSIONS();
            CRYPT_DATA_BLOB friendlyName = new CRYPT_DATA_BLOB();

            GCHandle hValidTo = new GCHandle();
            GCHandle hExtensionList = new GCHandle();
            GCHandle hSubjectNameBlob = new GCHandle();
            GCHandle hFriendlyName = new GCHandle();

            try
            {
                // create a new key pair.
                int bResult = NativeMethods.CryptGenKey(
                    hProvider,
                    AT_KEYEXCHANGE,
                    CRYPT_EXPORTABLE | (keySize << 16),
                    ref hKey);

                if (bResult == 0)
                {
                    Throw("Could not generate a new key pair. Error={0:X8}", Marshal.GetLastWin32Error());
                }

                // gey the public key identifier.
                GetPublicKeyIdentifier(hProvider, ref publicKeyId);

                // construct the certificate subject name.
                CreateX500Name(subjectName, ref subjectNameBlob);
                GCHandle hSubjectName = GCHandle.Alloc(subjectNameBlob, GCHandleType.Pinned);

                // allocate memory for all possible extensions.
                extensions.cExtension = 0;
                extensions.rgExtension = Marshal.AllocHGlobal(6 * Marshal.SizeOf(typeof(CERT_EXTENSION)));

                // create the subject key info extension.
                IntPtr pPos = extensions.rgExtension;
                CERT_EXTENSION extension = new CERT_EXTENSION();
                CreateSubjectKeyIdentifierExtension(ref extension, ref publicKeyId);
                Marshal.StructureToPtr(extension, pPos, false);
                pPos = new IntPtr(pPos.ToInt64() + Marshal.SizeOf(typeof(CERT_EXTENSION)));
                extensions.cExtension++;

                // create the authority key info extension.
                extension = new CERT_EXTENSION();
                CreateAuthorityKeyIdentifierExtension(ref extension, ref publicKeyId);
                Marshal.StructureToPtr(extension, pPos, false);
                pPos = new IntPtr(pPos.ToInt64() + Marshal.SizeOf(typeof(CERT_EXTENSION)));
                extensions.cExtension++;

                // create the basic constraints extension.
                extension = new CERT_EXTENSION();
                CreateBasicConstraintsExtension(ref extension, false);
                Marshal.StructureToPtr(extension, pPos, false);
                pPos = new IntPtr(pPos.ToInt64() + Marshal.SizeOf(typeof(CERT_EXTENSION)));
                extensions.cExtension++;

                // create the key usage extension.
                extension = new CERT_EXTENSION();
                CreateKeyUsageExtension(ref extension, false);
                Marshal.StructureToPtr(extension, pPos, false);
                pPos = new IntPtr(pPos.ToInt64() + Marshal.SizeOf(typeof(CERT_EXTENSION)));
                extensions.cExtension++;

                // create the extended key usage extension.
                extension = new CERT_EXTENSION();
                CreateExtendedKeyUsageExtension(ref extension);
                Marshal.StructureToPtr(extension, pPos, false);
                pPos = new IntPtr(pPos.ToInt64() + Marshal.SizeOf(typeof(CERT_EXTENSION)));
                extensions.cExtension++;

                // create the subject alternate name extension.
                extension = new CERT_EXTENSION();
                CreateSubjectAltNameExtension(applicationUri, hostNames, ref extension);
                Marshal.StructureToPtr(extension, pPos, false);
                pPos = new IntPtr(pPos.ToInt64() + Marshal.SizeOf(typeof(CERT_EXTENSION)));
                extensions.cExtension++;

                // set the expiration date.
                DateTime validTo = DateTime.UtcNow.AddMonths(lifetimeInMonths);
                System.Runtime.InteropServices.ComTypes.FILETIME ftValidTo = new System.Runtime.InteropServices.ComTypes.FILETIME();
                ulong ticks = (ulong)(validTo.Ticks - new DateTime(1601, 1, 1).Ticks);
                ftValidTo.dwHighDateTime = (int)((0xFFFFFFFF00000000 & (ulong)ticks) >> 32);
                ftValidTo.dwLowDateTime = (int)((ulong)ticks & 0x00000000FFFFFFFF);

                NativeMethods.FileTimeToSystemTime(ref ftValidTo, ref stValidTo);

                // specify what key is being used to sign the certificate.
                CRYPT_KEY_PROV_INFO kpi = new CRYPT_KEY_PROV_INFO();

                kpi.pwszContainerName = KEY_CONTAINER_NAME; // must be the same as the hProvider
                kpi.pwszProvName = DEFAULT_CRYPTO_PROVIDER;
                kpi.dwProvType = PROV_RSA_FULL;
                kpi.dwFlags = CERT_SET_KEY_CONTEXT_PROP_ID;
                kpi.dwKeySpec = AT_KEYEXCHANGE;

                if (useMachineStore)
                {
                    kpi.dwFlags |= CRYPT_MACHINE_KEYSET;
                }
                else
                {
                    kpi.dwFlags |= CRYPT_USER_KEYSET;
                }

                pKpi = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CRYPT_KEY_PROV_INFO)));
                Marshal.StructureToPtr(kpi, pKpi, false);

                hValidTo = GCHandle.Alloc(stValidTo, GCHandleType.Pinned);
                hExtensionList = GCHandle.Alloc(extensions, GCHandleType.Pinned);
                hSubjectNameBlob = GCHandle.Alloc(subjectNameBlob, GCHandleType.Pinned);

                if (algorithm == 1)
                {
                    CRYPT_ALGORITHM_IDENTIFIER algorithmID = new CRYPT_ALGORITHM_IDENTIFIER();
                    algorithmID.pszObjId = "1.2.840.113549.1.1.11"; //SHA256

                    pAlgorithmId = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CRYPT_ALGORITHM_IDENTIFIER)));
                    Marshal.StructureToPtr(algorithmID, pAlgorithmId, false);

                    //create the certificate
                    pContext = NativeMethods.CertCreateSelfSignCertificate(
                         hProvider,
                         hSubjectNameBlob.AddrOfPinnedObject(),
                         0,
                         pKpi,
                         pAlgorithmId,
                         IntPtr.Zero,
                         hValidTo.AddrOfPinnedObject(),
                         hExtensionList.AddrOfPinnedObject());
                }
                else
                {
                    // (default) create the certificate.
                    pContext = NativeMethods.CertCreateSelfSignCertificate(
                    hProvider,
                    hSubjectNameBlob.AddrOfPinnedObject(),
                    0,
                    pKpi,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    hValidTo.AddrOfPinnedObject(),
                    hExtensionList.AddrOfPinnedObject());
                }

                if (pContext == IntPtr.Zero)
                {
                    Throw("Could not create self-signed certificate. Error={0:X8}", Marshal.GetLastWin32Error());
                }

                // get the thumbprint.
                int dwThumbprintSize = 20;
                pThumbprint = Marshal.AllocHGlobal(dwThumbprintSize);

                bResult = NativeMethods.CertGetCertificateContextProperty(
                    pContext,
                    CERT_SHA1_HASH_PROP_ID,
                    pThumbprint,
                    ref dwThumbprintSize);

                if (bResult == 0)
                {
                    Throw("Could not get the thumbprint of the new certificate. Error={0:X8}", Marshal.GetLastWin32Error());
                }

                byte[] bytes = new byte[dwThumbprintSize];
                Marshal.Copy(pThumbprint, bytes, 0, dwThumbprintSize);
                string thumbprint = Utils.ToHexString(bytes);

                // set the friendly name.
                friendlyName.pbData = Marshal.StringToHGlobalUni(applicationName);
                friendlyName.cbData = (applicationName.Length+1)*Marshal.SizeOf(typeof(ushort));
                hFriendlyName = GCHandle.Alloc(friendlyName, GCHandleType.Pinned);

                bResult = NativeMethods.CertSetCertificateContextProperty(
                    pContext,
                    CERT_FRIENDLY_NAME_PROP_ID,
                    0,
                    hFriendlyName.AddrOfPinnedObject());

                if (bResult == 0)
                {
                    Throw("Could not set the friendly name for the certificate. Error={0:X8}", Marshal.GetLastWin32Error());
                }

                // add into store.
                bResult = NativeMethods.CertAddCertificateContextToStore(
                    hStore,
                    pContext,
                    CERT_STORE_ADD_REPLACE_EXISTING,
                    ref pNewContext);

                if (bResult == 0)
                {
                    Throw("Could not add the certificate to the store. Error={0:X8}", Marshal.GetLastWin32Error());
                }

                return thumbprint;
            }
            finally
            {
                if (pContext != IntPtr.Zero)
                {
                    NativeMethods.CertFreeCertificateContext(pContext);
                }

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

                if (friendlyName.pbData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(friendlyName.pbData);
                }

                if (pThumbprint != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pThumbprint);
                }

                if (pAlgorithmId != IntPtr.Zero)
                {
                    Marshal.DestroyStructure(pAlgorithmId, typeof(CRYPT_ALGORITHM_IDENTIFIER));
                    Marshal.FreeHGlobal(pAlgorithmId);
                }

                if (hValidTo.IsAllocated) hValidTo.Free();
                if (hExtensionList.IsAllocated) hExtensionList.Free();
                if (hSubjectNameBlob.IsAllocated) hSubjectNameBlob.Free();
                if (hFriendlyName.IsAllocated) hFriendlyName.Free();

                if (pKpi != IntPtr.Zero)
                {
                    Marshal.DestroyStructure(pKpi, typeof(CRYPT_KEY_PROV_INFO));
                    Marshal.FreeHGlobal(pKpi);
                }

                DeleteExtensions(ref extensions.rgExtension, extensions.cExtension);
                DeleteX500Name(ref subjectNameBlob);

                if (publicKeyId.pbData != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(publicKeyId.pbData);
                }

                if (hKey != IntPtr.Zero)
                {
                    NativeMethods.CryptDestroyKey(hKey);
                }
            }
        }
Ejemplo n.º 10
0
        private static SafeCertContextHandle CreateSelfSignedCertificate(CngKey key,
                                                                         bool takeOwnershipOfKey,
                                                                         byte[] subjectName,
                                                                         X509CertificateCreationOptions creationOptions,
                                                                         string signatureAlgorithmOid,
                                                                         DateTime startTime,
                                                                         DateTime endTime)
        {
            // Create an algorithm identifier structure for the signature algorithm
            CRYPT_ALGORITHM_IDENTIFIER nativeSignatureAlgorithm = new CRYPT_ALGORITHM_IDENTIFIER();

            nativeSignatureAlgorithm.pszObjId          = signatureAlgorithmOid;
            nativeSignatureAlgorithm.Parameters        = new CRYPTOAPI_BLOB();
            nativeSignatureAlgorithm.Parameters.cbData = 0;
            nativeSignatureAlgorithm.Parameters.pbData = IntPtr.Zero;

            // Convert the begin and expire dates to system time structures
            SYSTEMTIME nativeStartTime = new SYSTEMTIME(startTime);
            SYSTEMTIME nativeEndTime   = new SYSTEMTIME(endTime);

            CERT_EXTENSIONS nativeExtensions = new CERT_EXTENSIONS();

            nativeExtensions.cExtension = 0;

            // Setup a CRYPT_KEY_PROV_INFO for the key
            CRYPT_KEY_PROV_INFO keyProvInfo = new CRYPT_KEY_PROV_INFO();

            keyProvInfo.pwszContainerName = key.UniqueName;
            keyProvInfo.pwszProvName      = key.Provider.Provider;
            keyProvInfo.dwProvType        = 0; // NCRYPT
            keyProvInfo.dwFlags           = 0;
            keyProvInfo.cProvParam        = 0;
            keyProvInfo.rgProvParam       = IntPtr.Zero;
            keyProvInfo.dwKeySpec         = 0;

            //
            // Now that all of the needed data structures are setup, we can create the certificate
            //

            SafeCertContextHandle selfSignedCertHandle = null;

            unsafe
            {
                fixed(byte *pSubjectName = &subjectName[0])
                {
                    // Create a CRYPTOAPI_BLOB for the subject of the cert
                    CRYPTOAPI_BLOB nativeSubjectName = new CRYPTOAPI_BLOB();

                    nativeSubjectName.cbData = subjectName.Length;
                    nativeSubjectName.pbData = new IntPtr(pSubjectName);

                    // Now that we've converted all the inputs to native data structures, we can generate
                    // the self signed certificate for the input key.
                    using (SafeNCryptKeyHandle keyHandle = key.Handle)
                    {
                        selfSignedCertHandle = CertCreateSelfSignCertificate(keyHandle,
                                                                             ref nativeSubjectName,
                                                                             creationOptions,
                                                                             ref keyProvInfo,
                                                                             ref nativeSignatureAlgorithm,
                                                                             ref nativeStartTime,
                                                                             ref nativeEndTime,
                                                                             ref nativeExtensions);
                        if (selfSignedCertHandle.IsInvalid)
                        {
                            throw new CryptographicException(Marshal.GetLastWin32Error());
                        }
                    }
                }
            }

            Debug.Assert(selfSignedCertHandle != null, "selfSignedCertHandle != null");

            // Attach a key context to the certificate which will allow Windows to find the private key
            // associated with the certificate if the NCRYPT_KEY_HANDLE is ephemeral.
            // is done.
            using (SafeNCryptKeyHandle keyHandle = key.Handle)
            {
                CERT_KEY_CONTEXT keyContext = new CERT_KEY_CONTEXT();
                keyContext.cbSize     = Marshal.SizeOf(typeof(CERT_KEY_CONTEXT));
                keyContext.hNCryptKey = keyHandle.DangerousGetHandle();
                keyContext.dwKeySpec  = KeySpec.NCryptKey;

                bool attachedProperty = false;
                int  setContextError  = 0;

                // Run in a CER to ensure accurate tracking of the transfer of handle ownership
                RuntimeHelpers.PrepareConstrainedRegions();
                try { }
                finally
                {
                    CertificatePropertySetFlags flags = CertificatePropertySetFlags.None;
                    if (!takeOwnershipOfKey)
                    {
                        // If the certificate is not taking ownership of the key handle, then it should
                        // not release the handle when the context is released.
                        flags |= CertificatePropertySetFlags.NoCryptRelease;
                    }

                    attachedProperty = CertSetCertificateContextProperty(selfSignedCertHandle,
                                                                         CertificateProperty.KeyContext,
                                                                         flags,
                                                                         ref keyContext);
                    setContextError = Marshal.GetLastWin32Error();

                    // If we succesfully transferred ownership of the key to the certificate,
                    // then we need to ensure that we no longer release its handle.
                    if (attachedProperty && takeOwnershipOfKey)
                    {
                        keyHandle.SetHandleAsInvalid();
                    }
                }

                if (!attachedProperty)
                {
                    throw new CryptographicException(setContextError);
                }
            }

            return(selfSignedCertHandle);
        }
        /// <summary>
        /// Create a self-signed x509 certificate.
        /// </summary>
        /// <param name="subjectName">The distinguished name.</param>
        /// <param name="notBefore">The start time.</param>
        /// <param name="notAfter">the end time.</param>
        /// <param name="extensions">the extensions.</param>
        /// <returns>A byte array containing the certificate and private key encoded as PFX.</returns>
        public static byte[] CreateSelfSignCertificatePfx(
            string subjectName,
            DateTime notBefore,
            DateTime notAfter,
            params X509Extension[] extensions)
        {
            if (subjectName == null)
            {
                subjectName = string.Empty;
            }

            byte[] pfxData;

            SYSTEMTIME startSystemTime = ToSystemTime(notBefore);
            SYSTEMTIME endSystemTime = ToSystemTime(notAfter);
            string containerName = $"Created by Workstation. {Guid.NewGuid().ToString()}";

            GCHandle gcHandle = default(GCHandle);
            var providerContext = SafeCryptProvHandle.InvalidHandle;
            var cryptKey = SafeCryptKeyHandle.InvalidHandle;
            var certContext = SafeCertContextHandle.InvalidHandle;
            var certStore = SafeCertStoreHandle.InvalidHandle;
            var storeCertContext = SafeCertContextHandle.InvalidHandle;

            try
            {
                Check(NativeMethods.CryptAcquireContextW(
                    out providerContext,
                    containerName,
                    null,
                    PROV_RSA_FULL,
                    CRYPT_NEWKEYSET));

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

                IntPtr pbEncoded = IntPtr.Zero;
                int cbEncoded = 0;

                Check(NativeMethods.CertStrToNameW(
                    X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                    subjectName,
                    CERT_X500_NAME_STR | CERT_NAME_STR_REVERSE_FLAG,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    ref cbEncoded,
                    IntPtr.Zero));

                pbEncoded = Marshal.AllocHGlobal(cbEncoded);

                Check(NativeMethods.CertStrToNameW(
                    X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                    subjectName,
                    CERT_X500_NAME_STR | CERT_NAME_STR_REVERSE_FLAG,
                    IntPtr.Zero,
                    pbEncoded,
                    ref cbEncoded,
                    IntPtr.Zero));

                var nameBlob = new CRYPTOAPI_BLOB
                {
                    cbData = (uint)cbEncoded,
                    pbData = pbEncoded
                };

                var kpi = new CRYPT_KEY_PROV_INFO
                {
                    pwszContainerName = containerName,
                    dwProvType = PROV_RSA_FULL,
                    dwKeySpec = AT_KEYEXCHANGE
                };

                var signatureAlgorithm = new CRYPT_ALGORITHM_IDENTIFIER
                {
                    pszObjId = OID_RSA_SHA256RSA,
                    Parameters = default(CRYPTOAPI_BLOB)
                };

                IntPtr pInfo = IntPtr.Zero;
                int cbInfo = 0;
                byte[] keyHash = null;
                int cbKeyHash = 0;

                try
                {
                    Check(NativeMethods.CryptExportPublicKeyInfoEx(
                        providerContext,
                        AT_KEYEXCHANGE,
                        X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                        OID_RSA_RSA,
                        0,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        ref cbInfo));

                    pInfo = Marshal.AllocHGlobal(cbInfo);

                    Check(NativeMethods.CryptExportPublicKeyInfoEx(
                        providerContext,
                        AT_KEYEXCHANGE,
                        X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                        OID_RSA_RSA,
                        0,
                        IntPtr.Zero,
                        pInfo,
                        ref cbInfo));

                    Check(NativeMethods.CryptHashPublicKeyInfo(
                        providerContext,
                        CALG_SHA1,
                        0,
                        X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                        pInfo,
                        null,
                        ref cbKeyHash));

                    keyHash = new byte[cbKeyHash];

                    Check(NativeMethods.CryptHashPublicKeyInfo(
                        providerContext,
                        CALG_SHA1,
                        0,
                        X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                        pInfo,
                        keyHash,
                        ref cbKeyHash));
                }
                finally
                {
                    if (pInfo != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(pInfo);
                    }
                }

                var safeExtensions = new List<SafeX509Extension>();
                var blob = IntPtr.Zero;
                try
                {
                    foreach (var item in extensions)
                    {
                        safeExtensions.Add(new SafeX509Extension(item));
                    }

                    // adding SubjectKeyIdentifier TODO: AuthKeyIdentifier?
                    safeExtensions.Add(new SafeX509Extension(new X509SubjectKeyIdentifierExtension(keyHash, false)));

                    var structSize = Marshal.SizeOf<CERT_EXTENSION>();
                    blob = Marshal.AllocHGlobal(structSize * safeExtensions.Count);
                    for (int index = 0, offset = 0; index < safeExtensions.Count; index++, offset += structSize)
                    {
                        var marshalX509Extension = safeExtensions[index];
                        Marshal.StructureToPtr(marshalX509Extension.Value, blob + offset, false);
                    }

                    var certExtensions = new CERT_EXTENSIONS { cExtension = (uint)safeExtensions.Count, rgExtension = blob };

                    certContext = NativeMethods.CertCreateSelfSignCertificate(
                        providerContext,
                        ref nameBlob,
                        0,
                        ref kpi,
                        ref signatureAlgorithm,
                        ref startSystemTime,
                        ref endSystemTime,
                        ref certExtensions);
                    Check(!certContext.IsInvalid);
                }
                finally
                {
                    foreach (var safeExtension in safeExtensions)
                    {
                        safeExtension.Dispose();
                    }

                    safeExtensions.Clear();
                    Marshal.FreeHGlobal(blob);
                    Marshal.FreeHGlobal(pbEncoded);
                }

                certStore = NativeMethods.CertOpenStore(
                    sz_CERT_STORE_PROV_MEMORY,
                    0,
                    IntPtr.Zero,
                    CERT_STORE_CREATE_NEW_FLAG,
                    IntPtr.Zero);
                Check(!certStore.IsInvalid);

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

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

                CRYPTOAPI_BLOB pfxBlob = default(CRYPTOAPI_BLOB);
                Check(NativeMethods.PFXExportCertStoreEx(
                    certStore,
                    ref pfxBlob,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY));

                pfxData = new byte[pfxBlob.cbData];
                gcHandle = GCHandle.Alloc(pfxData, GCHandleType.Pinned);
                pfxBlob.pbData = gcHandle.AddrOfPinnedObject();

                Check(NativeMethods.PFXExportCertStoreEx(
                    certStore,
                    ref pfxBlob,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY));

                gcHandle.Free();
            }
            finally
            {
                if (gcHandle.IsAllocated)
                {
                    gcHandle.Free();
                }

                if (!certContext.IsInvalid)
                {
                    certContext.Dispose();
                }

                if (!storeCertContext.IsInvalid)
                {
                    storeCertContext.Dispose();
                }

                if (!certStore.IsInvalid)
                {
                    certStore.Dispose();
                }

                if (!cryptKey.IsInvalid)
                {
                    cryptKey.Dispose();
                }

                if (!providerContext.IsInvalid)
                {
                    providerContext.Dispose();
                    providerContext = SafeCryptProvHandle.InvalidHandle;

                    // Delete generated keyset. Does not return a providerContext
                    NativeMethods.CryptAcquireContextW(
                        out providerContext,
                        containerName,
                        null,
                        PROV_RSA_FULL,
                        CRYPT_DELETEKEYSET);
                }
            }

            return pfxData;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Create a self-signed x509 certificate.
        /// </summary>
        /// <param name="subjectName">The distinguished name.</param>
        /// <param name="notBefore">The start time.</param>
        /// <param name="notAfter">the end time.</param>
        /// <param name="extensions">the extensions.</param>
        /// <returns>A byte array containing the certificate and private key encoded as PFX.</returns>
        public static byte[] CreateSelfSignCertificatePfx(
            string subjectName,
            DateTime notBefore,
            DateTime notAfter,
            params X509Extension[] extensions)
        {
            if (subjectName == null)
            {
                subjectName = string.Empty;
            }

            byte[] pfxData;

            SYSTEMTIME startSystemTime = ToSystemTime(notBefore);
            SYSTEMTIME endSystemTime   = ToSystemTime(notAfter);
            string     containerName   = $"Created by Workstation. {Guid.NewGuid().ToString()}";

            GCHandle gcHandle         = default(GCHandle);
            var      providerContext  = SafeCryptProvHandle.InvalidHandle;
            var      cryptKey         = SafeCryptKeyHandle.InvalidHandle;
            var      certContext      = SafeCertContextHandle.InvalidHandle;
            var      certStore        = SafeCertStoreHandle.InvalidHandle;
            var      storeCertContext = SafeCertContextHandle.InvalidHandle;

            try
            {
                Check(NativeMethods.CryptAcquireContextW(
                          out providerContext,
                          containerName,
                          null,
                          PROV_RSA_FULL,
                          CRYPT_NEWKEYSET));

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

                IntPtr pbEncoded = IntPtr.Zero;
                int    cbEncoded = 0;

                Check(NativeMethods.CertStrToNameW(
                          X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                          subjectName,
                          CERT_X500_NAME_STR | CERT_NAME_STR_REVERSE_FLAG,
                          IntPtr.Zero,
                          IntPtr.Zero,
                          ref cbEncoded,
                          IntPtr.Zero));

                pbEncoded = Marshal.AllocHGlobal(cbEncoded);

                Check(NativeMethods.CertStrToNameW(
                          X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                          subjectName,
                          CERT_X500_NAME_STR | CERT_NAME_STR_REVERSE_FLAG,
                          IntPtr.Zero,
                          pbEncoded,
                          ref cbEncoded,
                          IntPtr.Zero));

                var nameBlob = new CRYPTOAPI_BLOB
                {
                    cbData = (uint)cbEncoded,
                    pbData = pbEncoded
                };

                var kpi = new CRYPT_KEY_PROV_INFO
                {
                    pwszContainerName = containerName,
                    dwProvType        = PROV_RSA_FULL,
                    dwKeySpec         = AT_KEYEXCHANGE
                };

                var signatureAlgorithm = new CRYPT_ALGORITHM_IDENTIFIER
                {
                    pszObjId   = OID_RSA_SHA256RSA,
                    Parameters = default(CRYPTOAPI_BLOB)
                };

                IntPtr pInfo     = IntPtr.Zero;
                int    cbInfo    = 0;
                byte[] keyHash   = null;
                int    cbKeyHash = 0;

                try
                {
                    Check(NativeMethods.CryptExportPublicKeyInfoEx(
                              providerContext,
                              AT_KEYEXCHANGE,
                              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                              OID_RSA_RSA,
                              0,
                              IntPtr.Zero,
                              IntPtr.Zero,
                              ref cbInfo));

                    pInfo = Marshal.AllocHGlobal(cbInfo);

                    Check(NativeMethods.CryptExportPublicKeyInfoEx(
                              providerContext,
                              AT_KEYEXCHANGE,
                              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                              OID_RSA_RSA,
                              0,
                              IntPtr.Zero,
                              pInfo,
                              ref cbInfo));

                    Check(NativeMethods.CryptHashPublicKeyInfo(
                              providerContext,
                              CALG_SHA1,
                              0,
                              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                              pInfo,
                              null,
                              ref cbKeyHash));

                    keyHash = new byte[cbKeyHash];

                    Check(NativeMethods.CryptHashPublicKeyInfo(
                              providerContext,
                              CALG_SHA1,
                              0,
                              X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
                              pInfo,
                              keyHash,
                              ref cbKeyHash));
                }
                finally
                {
                    if (pInfo != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(pInfo);
                    }
                }

                var safeExtensions = new List <SafeX509Extension>();
                var blob           = IntPtr.Zero;
                try
                {
                    foreach (var item in extensions)
                    {
                        safeExtensions.Add(new SafeX509Extension(item));
                    }

                    // adding SubjectKeyIdentifier TODO: AuthKeyIdentifier?
                    safeExtensions.Add(new SafeX509Extension(new X509SubjectKeyIdentifierExtension(keyHash, false)));

                    var structSize = Marshal.SizeOf <CERT_EXTENSION>();
                    blob = Marshal.AllocHGlobal(structSize * safeExtensions.Count);
                    for (int index = 0, offset = 0; index < safeExtensions.Count; index++, offset += structSize)
                    {
                        var marshalX509Extension = safeExtensions[index];
                        Marshal.StructureToPtr(marshalX509Extension.Value, blob + offset, false);
                    }

                    var certExtensions = new CERT_EXTENSIONS {
                        cExtension = (uint)safeExtensions.Count, rgExtension = blob
                    };

                    certContext = NativeMethods.CertCreateSelfSignCertificate(
                        providerContext,
                        ref nameBlob,
                        0,
                        ref kpi,
                        ref signatureAlgorithm,
                        ref startSystemTime,
                        ref endSystemTime,
                        ref certExtensions);
                    Check(!certContext.IsInvalid);
                }
                finally
                {
                    foreach (var safeExtension in safeExtensions)
                    {
                        safeExtension.Dispose();
                    }

                    safeExtensions.Clear();
                    Marshal.FreeHGlobal(blob);
                    Marshal.FreeHGlobal(pbEncoded);
                }

                certStore = NativeMethods.CertOpenStore(
                    sz_CERT_STORE_PROV_MEMORY,
                    0,
                    IntPtr.Zero,
                    CERT_STORE_CREATE_NEW_FLAG,
                    IntPtr.Zero);
                Check(!certStore.IsInvalid);

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

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

                CRYPTOAPI_BLOB pfxBlob = default(CRYPTOAPI_BLOB);
                Check(NativeMethods.PFXExportCertStoreEx(
                          certStore,
                          ref pfxBlob,
                          IntPtr.Zero,
                          IntPtr.Zero,
                          EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY));

                pfxData        = new byte[pfxBlob.cbData];
                gcHandle       = GCHandle.Alloc(pfxData, GCHandleType.Pinned);
                pfxBlob.pbData = gcHandle.AddrOfPinnedObject();

                Check(NativeMethods.PFXExportCertStoreEx(
                          certStore,
                          ref pfxBlob,
                          IntPtr.Zero,
                          IntPtr.Zero,
                          EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY));

                gcHandle.Free();
            }
            finally
            {
                if (gcHandle.IsAllocated)
                {
                    gcHandle.Free();
                }

                if (!certContext.IsInvalid)
                {
                    certContext.Dispose();
                }

                if (!storeCertContext.IsInvalid)
                {
                    storeCertContext.Dispose();
                }

                if (!certStore.IsInvalid)
                {
                    certStore.Dispose();
                }

                if (!cryptKey.IsInvalid)
                {
                    cryptKey.Dispose();
                }

                if (!providerContext.IsInvalid)
                {
                    providerContext.Dispose();
                    providerContext = SafeCryptProvHandle.InvalidHandle;

                    // Delete generated keyset. Does not return a providerContext
                    NativeMethods.CryptAcquireContextW(
                        out providerContext,
                        containerName,
                        null,
                        PROV_RSA_FULL,
                        CRYPT_DELETEKEYSET);
                }
            }

            return(pfxData);
        }