首页 > 解决方案 > 我无法从 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#delphi

解决方案


推荐阅读