public PublicKeyInfo ToPublicKey() { uint infoSize = 0; var publicKeyObjId = AlgorithmGroup == AlgorithmGroup.RSA ? OIDs.RSA_PUBLIC_KEY : OIDs.ECC_PUBLIC_KEY; if (Crypt32.CryptExportPublicKeyInfoEx(_handle, _keySpec, EncodingType.X509_ASN_ENCODING | EncodingType.PKCS_7_ASN_ENCODING, publicKeyObjId, 0, IntPtr.Zero, IntPtr.Zero, ref infoSize)) { var buffer = Marshal.AllocHGlobal((int)infoSize); if (Crypt32.CryptExportPublicKeyInfoEx(_handle, _keySpec, EncodingType.X509_ASN_ENCODING | EncodingType.PKCS_7_ASN_ENCODING, publicKeyObjId, 0, IntPtr.Zero, buffer, ref infoSize)) { return(new PublicKeyInfo(buffer)); } throw new Win32Exception(Marshal.GetLastWin32Error()); } throw new Win32Exception(Marshal.GetLastWin32Error()); }