private unsafe static byte[] Encode(string distinguishedName, X500DistinguishedNameFlags flag) { if (distinguishedName == null) { throw new ArgumentNullException("distinguishedName"); } uint cbEncoded = 0; uint dwStrType = CAPI.CERT_X500_NAME_STR | MapNameToStrFlag(flag); if (!CAPI.CertStrToNameW(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, distinguishedName, dwStrType, IntPtr.Zero, IntPtr.Zero, ref cbEncoded, IntPtr.Zero)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } byte[] encodedName = new byte[cbEncoded]; fixed(byte *pbEncoded = encodedName) { if (!CAPI.CertStrToNameW(CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, distinguishedName, dwStrType, IntPtr.Zero, new IntPtr(pbEncoded), ref cbEncoded, IntPtr.Zero)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } return(encodedName); }