c# - 从 C# 项目调用 c native 函数

标签 c# c wpf dll encryption

我正在开发一个 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”。 所以任何更多的想法都将受到欢迎,再次感谢!

最佳答案

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

尝试更改为:

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

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

关于c# - 从 C# 项目调用 c native 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15664792/

相关文章:

c# - CA2000:对象未沿所有异常路径处置

c - 如何使用字符串指针访问字符串的其余部分?

c# - “Long”延迟导致我的视​​图的按钮无法重新启用

c# - WPF 样式 setter 不工作

c# - 从不同的类访问控件

c# - 最小化 ASP.Net 中的 ViewState 大小,在构造函数中初始化控件值与 OnInit 之间有区别吗?

c# - 将大型 CLOB 对象转换为 .NET 字符串以放入 DataGridView 单元格

c# - 以编程方式检查 .NET 代码

c - 无符号值的不等式

c - Lint 警告 预期的正缩进