Я сделал это!!!!! :d/
Может быть кому-нибудь пригодится...
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CryptAcquireContext(
ref IntPtr hProv,
String pszContainer,
String pszProvider,
Int32 dwProvType,
Int32 dwFlags
);
[DllImport("crypt32.dll")]
public static extern bool CryptExportPublicKeyInfo(
IntPtr hProv,
uint KeySpec,
uint CertEncodingType,
IntPtr pvStructInfo,
ref uint cbStructInfo
);
[StructLayout(LayoutKind.Sequential)]
public struct CERT_PUBLIC_KEY_INFO
{
public IntPtr SubjPKIAlgpszObjId;
public int SubjPKIAlgParameterscbData;
public IntPtr SubjPKIAlgParameterspbData;
public int PublicKeycbData;
public IntPtr PublicKeypbData;
public int PublicKeycUnusedBits;
}
const uint X509_ASN_ENCODING = 0x00000001;
const uint PKCS_7_ASN_ENCODING = 0x00010000;
static uint ENCODING_TYPE = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING;
public string DecodeSubjectPublicKeyInfo(string name_con, string name_prov, int type_prov)
{
try
{
IntPtr hProv = IntPtr.Zero;
if (CryptAcquireContext(ref hProv, name_con, name_prov, type_prov, 0))
{
uint cbytes = 0;
if (CryptExportPublicKeyInfo(hProv, 1, ENCODING_TYPE, IntPtr.Zero, ref cbytes))
{
IntPtr key_info = Marshal.AllocHGlobal((int)cbytes);
if (CryptExportPublicKeyInfo(hProv, 1, ENCODING_TYPE, key_info, ref cbytes))
{
CERT_PUBLIC_KEY_INFO pkinfo = (CERT_PUBLIC_KEY_INFO)Marshal.PtrToStructure(key_info, typeof(CERT_PUBLIC_KEY_INFO));
IntPtr pencodeddata = pkinfo.PublicKeypbData;
int cblob = pkinfo.PublicKeycbData;
byte[] encodeddata = new byte[cblob];
Marshal.Copy(pencodeddata, encodeddata, 0, cblob); //copy bytes from IntPtr to byte[]
Marshal.FreeHGlobal(key_info);
CAPICOM.Utilities cap = new CAPICOM.Utilities();
return cap.BinaryToHex(cap.ByteArrayToBinaryString(encodeddata));
}
}
}
MessageBox.Show("Не удалось получить открытый ключ", "Ошибка");
l.Write_Log("1", "Create_Request:DecodeSubjectPublicKeyInfo", "Не удалось получить открытый ключ");
return "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка");
l.Write_Log("1", "Create_Request:DecodeSubjectPublicKeyInfo", ex.Message);
return "";
}
}