1

The code below used to work. I think it broke after some .NET Framework or Windows 10 upgrade, but not sure.

It opens a temporary certificate store for generating self-signed certificates.

using System;
using System.Runtime.InteropServices;

namespace MyTestApp
{
    internal static class Program
    {
        public static void Main(string[] arguments)
        {
            var certStore = CertOpenStore(
                "Memory", // sz_CERT_STORE_PROV_MEMORY
                0,
                IntPtr.Zero,
                CERT_STORE_CREATE_NEW_FLAG,
                IntPtr.Zero
            );

            if (certStore != IntPtr.Zero)
            {
                Console.WriteLine("Success!");
            }
            else
            {
                var error = Marshal.GetHRForLastWin32Error();
                Console.WriteLine("Error: " + error.ToString("X"));
            }

            Console.ReadLine();
        }

        private const uint CERT_STORE_CREATE_NEW_FLAG = 0x00002000;

        [DllImport("Crypt32.dll", SetLastError = true, CharSet=CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr CertOpenStore(
            [MarshalAs(UnmanagedType.LPWStr)] string storeProvider,
            uint messageAndCertificateEncodingType,
            IntPtr cryptProvHandle,
            uint flags,
            IntPtr parameters
        );

    }
}

The output is:

Error: 80070002

Which is ERROR_FILE_NOT_FOUND. Tested on .NET 4.5 and 4.5.2.

What can I do to diagnose further or fix?

fernacolo
  • 7,012
  • 5
  • 40
  • 61
  • 3
    the first parameter of `CertOpenStore` is null-terminated **ANSI** string , but you use `[MarshalAs(UnmanagedType.LPWStr)]` dont sure, but think reason that it marshalled as wide char string. need replace this – RbMm Mar 22 '19 at 22:12
  • Thanks. That was the problem. I wonder how could that work before... – fernacolo Mar 22 '19 at 22:22

0 Answers0