CryptEncodeObject

[DllImport("Crypt32.dll", SetLastError = true)]
public static extern bool CryptEncodeObject(
   uint dwCertEncodingType,
   uint lpszStructType,
   IntPtr pvStructInfo,
   byte[] pbEncoded,
   ref uint pcbEncoded
);

Microsoft documentation: Link

Last updated