c# - 我无法从 C# 调用用 Delphi 编写的 Lockbox 3 AES Encryption
问题描述
我在 Delphi 10 中编写了一个加密字符串的函数。一切正常,我在 Winform 中具有相同的函数,结果显示在备注字段中,但是,当我从 C# 调用该函数时,出现错误我从 C# 运行这个调用加密函数我得到“找不到参数”,这是来自 Delphi 中的异常。
有人可以帮忙吗?
function Encrypt(str: PWideChar; len: Integer): Boolean; stdcall;
begin
try
eString := AES128_Encrypt('Test','TestPassword');
PwValue := PWideChar(eString);
StrLCopy(str, PwValue, len);
Result := true;
except
On E: Exception do
begin
PwValue := PWideChar(E.Message);
StrLCopy(str, PwValue, len);
end;
end;
end;
function AES128_Encrypt(Value, Password: string): string; stdcall;
var
hCProv: HCRYPTPROV;
hKey: HCRYPTKEY;
lul_datalen: Integer;
lul_buflen: Integer;
Buffer: TBytes;
begin
Assert(Password <> '');
if (Value = '') then
Result := ''
else begin
hCProv := __CryptAcquireContext(PROV_RSA_AES);
try
hKey := __AES128_DeriveKeyFromPassword(hCProv, Password);
try
// allocate buffer space
lul_datalen := Length(Value) * SizeOf(Char);
Buffer := TEncoding.Unicode.GetBytes(Value + ' ');
lul_buflen := Length(Buffer);
// encrypt to buffer
Win32Check(CryptEncrypt(hKey, 0, True, 0, @Buffer[0], lul_datalen, lul_buflen));
SetLength(Buffer, lul_datalen);
// base 64 result
Result := Base64_Encode(Buffer);
finally
CryptDestroyKey(hKey);
end;
finally
CryptReleaseContext(hCProv, 0);
end;
end;
end;
像这样称呼它
eString := AES128_Encrypt('ii', 'o3ew232we22o');
C# 代码
[DllImport(@"<Path of dll>", EntryPoint = "Enrypt", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern bool Enrypt(StringBuilder sb, int len);
public static string Encrypt()
{
try
{
StringBuilder str = new StringBuilder(256);
System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.STA);
bool result = Encrypt(str, str.Capacity);
if (result)
{
return str.ToString();
}
}
catch (Exception ex1)
{
MessageBox.Show(ex1.ToString());
}
return "";
}
解决方案
推荐阅读
- c# - 具有泛型属性的类必须是泛型的?
- r - 如何将动态列名传递给 h2o 排列函数
- python - VSCode 集成终端未加载 Django
- google-cloud-platform - 通过 GCP 部署管理器使用 GKE 测试版功能
- c# - 将 DataTable 写入 csv 代码 break for loop
- razor - Net core 2.0 - Razor Pages 部分视图与业务本身(不是 MVC)
- c# - System.ComponentModel.DataAnnotations 在属性和封装字段上的有效放置
- sql-server - 排除具有相同绝对值的负值
- json - 访问 Json 对象数组中的子项
- generics - 通用类类型 IDE 警告的未经检查的强制转换