SoFunction
Updated on 2025-03-07

C# Method to create self-signed authentication files

This article describes the method of creating a self-signed authentication file in C#. Share it for your reference. The details are as follows:

using System;
using ;
using .X509Certificates;
using SecureString = ;
using RuntimeHelpers = ;
internal class Certificate
{
 public static byte[] CreateSelfSignCertificatePfx(
  string x500,
  DateTime startTime,
  DateTime endTime)
 {
  byte[] pfxData = CreateSelfSignCertificatePfx(
   x500,
   startTime,
   endTime,
   (SecureString)null);
  return pfxData;
 }
 public static byte[] CreateSelfSignCertificatePfx(
  string x500,
  DateTime startTime,
  DateTime endTime,
  string insecurePassword)
 {
  byte[] pfxData;
  SecureString password = null;
  try
  {
   if (!(insecurePassword))
   {
    password = new SecureString();
    foreach (char ch in insecurePassword)
    {
     (ch);
    }
    ();
   }
   pfxData = CreateSelfSignCertificatePfx(
    x500,
    startTime,
    endTime,
    password);
  }
  finally
  {
   if (password != null)
   {
    ();
   }
  }
  return pfxData;
 }
 public 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 = ().ToString();
  GCHandle dataHandle = new GCHandle();
  IntPtr providerContext = ;
  IntPtr cryptKey = ;
  IntPtr certContext = ;
  IntPtr certStore = ;
  IntPtr storeCertContext = ;
  IntPtr passwordPtr = ;
  ();
  try
  {
   Check((
    out providerContext,
    containerName,
    null,
    1, // PROV_RSA_FULL
    8)); // CRYPT_NEWKEYSET
   Check((
    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 = (x500, );
   if (!(
    0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
    (),
    3, // CERT_X500_NAME_STR = 3
    ,
    null,
    ref nameDataLength,
    out errorStringPtr))
   {
    string error = (errorStringPtr);
    throw new ArgumentException(error);
   }
   nameData = new byte[nameDataLength];
   if (!(
    0x00010001, // X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
    (),
    3, // CERT_X500_NAME_STR = 3
    ,
    nameData,
    ref nameDataLength,
    out errorStringPtr))
   {
    string error = (errorStringPtr);
    throw new ArgumentException(error);
   }
   ();
   dataHandle = (nameData, );
   CryptoApiBlob nameBlob = new CryptoApiBlob(
    ,
    ());
   CryptKeyProviderInformation kpi = new CryptKeyProviderInformation();
    = containerName;
    = 1; // PROV_RSA_FULL
    = 1; // AT_KEYEXCHANGE
   certContext = (
    providerContext,
    ref nameBlob,
    0,
    ref kpi,
    , // default = SHA1RSA
    ref startSystemTime,
    ref endSystemTime,
    );
   Check(certContext != );
   ();
   certStore = (
    "Memory", // sz_CERT_STORE_PROV_MEMORY
    0,
    ,
    0x2000, // CERT_STORE_CREATE_NEW_FLAG
    );
   Check(certStore != );
   Check((
    certStore,
    certContext,
    1, // CERT_STORE_ADD_NEW
    out storeCertContext));
   (
    storeCertContext,
    2, // CERT_KEY_PROV_INFO_PROP_ID
    0,
    ref kpi);
   if (password != null)
   {
    passwordPtr = (password);
   }
   CryptoApiBlob pfxBlob = new CryptoApiBlob();
   Check((
    certStore,
    ref pfxBlob,
    passwordPtr,
    ,
    7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY
   pfxData = new byte[];
   dataHandle = (pfxData, );
    = ();
   Check((
    certStore,
    ref pfxBlob,
    passwordPtr,
    ,
    7)); // EXPORT_PRIVATE_KEYS | REPORT_NO_PRIVATE_KEY | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY
   ();
  }
  finally
  {
   if (passwordPtr != )
   {
    (passwordPtr);
   }
   if ()
   {
    ();
   }
   if (certContext != )
   {
    (certContext);
   }
   if (storeCertContext != )
   {
    (storeCertContext);
   }
   if (certStore != )
   {
    (certStore, 0);
   }
   if (cryptKey != )
   {
    (cryptKey);
   }
   if (providerContext != )
   {
    (providerContext, 0);
    (
     out providerContext,
     containerName,
     null,
     1, // PROV_RSA_FULL
     0x10); // CRYPT_DELETEKEYSET
   }
  }
  return pfxData;
 }
 private static SystemTime ToSystemTime(DateTime dateTime)
 {
  long fileTime = ();
  SystemTime systemTime;
  Check((ref fileTime, out systemTime));
  return systemTime;
 }
 private static void Check(bool nativeCallSucceeded)
 {
  if (!nativeCallSucceeded)
  {
   int error = Marshal.GetHRForLastWin32Error();
   (error);
  }
 }
 [StructLayout()]
 private struct SystemTime
 {
  public short Year;
  public short Month;
  public short DayOfWeek;
  public short Day;
  public short Hour;
  public short Minute;
  public short Second;
  public short Milliseconds;
 }
 [StructLayout()]
 private struct CryptoApiBlob
 {
  public int DataLength;
  public IntPtr Data;
  public CryptoApiBlob(int dataLength, IntPtr data)
  {
    = dataLength;
    = data;
  }
 }
 [StructLayout()]
 private struct CryptKeyProviderInformation
 {
  [MarshalAs()] public string ContainerName;
  [MarshalAs()] public string ProviderName;
  public int ProviderType;
  public int Flags;
  public int ProviderParameterCount;
  public IntPtr ProviderParameters; // PCRYPT_KEY_PROV_PARAM
  public int KeySpec;
 }
 private static class NativeMethods
 {
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs()]
  public static extern bool FileTimeToSystemTime(
   [In] ref long fileTime,
   out SystemTime systemTime);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs()]
  public static extern bool CryptAcquireContextW(
   out IntPtr providerContext,
   [MarshalAs()] string container,
   [MarshalAs()] string provider,
   int providerType,
   int flags);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs()]
  public static extern bool CryptReleaseContext(
   IntPtr providerContext,
   int flags);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs()]
  public static extern bool CryptGenKey(
   IntPtr providerContext,
   int algorithmId,
   int flags,
   out IntPtr cryptKeyHandle);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs()]
  public static extern bool CryptDestroyKey(
   IntPtr cryptKeyHandle);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs()]
  public static extern bool CertStrToNameW(
   int certificateEncodingType,
   IntPtr x500,
   int strType,
   IntPtr reserved,
   [MarshalAs()] [Out] byte[] encoded,
   ref int encodedLength,
   out IntPtr errorString);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  public static extern IntPtr CertCreateSelfSignCertificate(
   IntPtr providerHandle,
   [In] ref CryptoApiBlob subjectIssuerBlob,
   int flags,
   [In] ref CryptKeyProviderInformation keyProviderInformation,
   IntPtr signatureAlgorithm,
   [In] ref SystemTime startTime,
   [In] ref SystemTime endTime,
   IntPtr extensions);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs()]
  public static extern bool CertFreeCertificateContext(
   IntPtr certificateContext);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  public static extern IntPtr CertOpenStore(
   [MarshalAs()] string storeProvider,
   int messageAndCertificateEncodingType,
   IntPtr cryptProvHandle,
   int flags,
   IntPtr parameters);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs()]
  public static extern bool CertCloseStore(
   IntPtr certificateStoreHandle,
   int flags);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs()]
  public static extern bool CertAddCertificateContextToStore(
   IntPtr certificateStoreHandle,
   IntPtr certificateContext,
   int addDisposition,
   out IntPtr storeContextPtr);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs()]
  public static extern bool CertSetCertificateContextProperty(
   IntPtr certificateContext,
   int propertyId,
   int flags,
   [In] ref CryptKeyProviderInformation data);
  [DllImport("", SetLastError = true, ExactSpelling = true)]
  [return: MarshalAs()]
  public static extern bool PFXExportCertStoreEx(
   IntPtr certificateStoreHandle,
   ref CryptoApiBlob pfxBlob,
   IntPtr password,
   IntPtr reserved,
   int flags);
 }
}

I hope this article will be helpful to everyone's C# programming.