using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
internal class Program
{
enum VKeyGenResultExOpt
{
KGREO_Ok = 0,
KGREO_BufferToSmall = 1,
KGREO_SecurityLevelInvalid = 2,
KGREO_VariantInvalid = 3,
KGREO_UnspecifiedError = 4
};
[DllImport("LHM_Vector.dll", EntryPoint = "GenerateKeyExOpt" ,CallingConvention = CallingConvention.Cdecl)]//导入安全算法dll
private static extern VKeyGenResultExOpt GenerateKeyExOpt( byte[] ipSeedArray, uint iSeedArraySize,
uint iSecurityLevel, ref string ipVariant, ref string ipOptions,
out IntPtr iopKeyArray, uint iMaxKeyArraySize,
ref uint oActualKeyArraySize);//引用算法中定义的函数
/// <summary>
/// IntPtr转byte[]数组
/// </summary>
/// <param name="obj">Inptr</param>
/// <returns></returns>
static byte[] Intptr2byte(object obj)
{
int size = Marshal.SizeOf(obj);
IntPtr intPtr = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(obj, intPtr, false);
byte[] by = new byte[size];
Marshal.Copy(intPtr, by, 0, by.Length);
return by;
}
catch (Exception ex)
{
Marshal.FreeHGlobal(intPtr);
}
return null;
}
static void Main(string[] args)
{
byte[] ipSeedArray=new byte[4] { 0X91,0X7C,0x39,0X1F}; //ECU处获取一个种子
uint iSeedArraySize=4;//设置种子长度
uint iSecurityLevel=7;//设置安全等级
string ipVariant = "";//默认为空
string ipOptions = "";//默认为空
IntPtr iopKeyArray; //经过安全认证返回的Key
uint oActualKeyArraySize = 0; ;//返回Key的长度
GenerateKeyExOpt(ipSeedArray, iSeedArraySize, iSecurityLevel, ref ipVariant, ref ipOptions, out iopKeyArray, 4, ref oActualKeyArraySize);//根据种子计算Key,安全等级
byte[] key= Intptr2byte(iopKeyArray);//得到的Key转成数组形式
}
}
}