【问题标题】:Call c native function from C# project从 C# 项目调用 c 本机函数
【发布时间】:2013-03-27 16:58:40
【问题描述】:

我正在开发一个 C# 项目,我必须在文件中存储一些密码。我想用sha1加密那些。 我已经在 C 项目中加密/解密 sha1 prog。 我想从我的 C# 项目中调用“password_sha1_build”,它是加密密码 extern "C" __declspec(dllexport) char * Password_SHA1_Build(char *Password)) 的 C 函数。

我从包含“Password_SHA1_Build”函数的文件中构建了一个 dll,并尝试从我的 C# 项目中调用它,如下所示:

[DllImport("Pass.dll")]
public static extern string Password_SHA1_Build(string Password);

... 

string password = "iamlee";
string hashedpwd = "";
hashedpwd = Password_SHA1_Build(password);

我收到一个关于 Pinvoke 与签名不匹配的错误(法语)...不平衡。 我坚持认为这可能是因为我使用的是字符串/字符*,但如果是这样的话,我可以处理吗?..

如果需要,请询问更多信息 谢谢大家


大家好,感谢大家的回答。

我注意到我的主题不够清楚。 有一个用作“服务器”的 C 程序,它将读取名为 infos.cfg 的文件,其中存储了在 C# 程序中写入的加密密码。 C程序不是我自己开发的,但它包含一个名为“int Password_SHA1_Check(char *Password, char *Hash)”的函数,它能够读取由函数“char * Password_SHA1_Build(char *Password)”构建的sha1密码.

所以一开始我尝试在 c# 中使用 sha1 存储密码,如下所示:

System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1.Create();
System.Text.ASCIIEncoding encoder = newS ystem.Text.ASCIIEncoding();
byte[] combined = encoder.GetBytes(password);
hash.ComputeHash(combined);
//rethash = Convert.ToBase64String(hash.Hash);
System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] hash = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(password));
string delimitedHexHash = BitConverter.ToString(hash);
string hexHash = delimitedHexHash.Replace("-", "");
rethash = hexHash;

密码以这样的方式存储在文件中:“.”之前的“password:sha1:576295.49880ab837e9179dd68dfb142342f368e821de43”是盐,之后是哈希

但是当 C 程序执行他的 Password_SHA1_Check 时,他告诉我我输入的密码与存储的密码不同。 我在加密方面有点弱,并且忙于其他工作,所以我只是问自己“为什么不使用已经存在并且有效的“Password_SHA1_Build”函数”所以这就是为什么我试图从我的 C# 程序中调用这个函数。 我希望这很清楚,对不起,我的英语很糟糕。

致 Reed Copsey:谢谢我试过了,至少 Pinvoke 异常消失了,但现在我得到了“AccessViolationException”.. 所以任何更多的想法将再次受到欢迎!

【问题讨论】:

  • 为什么不使用 .net SHA1 实现?
  • 这可能是数据封送处理的问题。看到这个msdn.microsoft.com/en-us/magazine/cc164123.aspx
  • 您的“答案”确实是对问题的更新,因此我将其合并。请编辑您的问题以添加新信息。

标签: c# c wpf dll encryption


【解决方案1】:

这可能是由于调用约定不匹配造成的。 PInvoke 默认使用StdCall,但VC编译器默认使用CDecl

尝试更改为:

[DllImport("Pass.dll", CallingConvention=CallingConvention.Cdecl)]

其他潜在问题是字符串编组技术。您可能需要指定要使用的编码,和/或将StringBuilder 作为第二个参数传递并使用它来“填充”结果。

【讨论】:

    【解决方案2】:

    .Net 框架内置了很多加密算法,包括 SHA256。尝试使用SHA256Managed 类。如果你想最终解密你的密码,你需要对称加密功能,而SHA不是其中之一。

    看看这个帖子:Password retrieval and storage

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 2016-06-09
      相关资源
      最近更新 更多