gpt4 book ai didi

c# - RSA_sign 和 RSACryptoProvider.VerifySignature

转载 作者:太空宇宙 更新时间:2023-11-03 14:30:17 25 4
gpt4 key购买 nike

我正在尝试快速了解如何获取一些使用 OpenSSL 进行加密的代码,以便与我使用 .NET 中提供的 Microsoft 加密提供程序使用 C# 编写的另一个程序配合使用。

更重要的是,我试图让 C# 程序验证由 OpenSSL 代码生成的 RSA 消息签名。生成签名的代码如下所示:

// Code in C, using the OpenSSL RSA implementation

char msgToSign[] = "Hello World"; // the message to be signed
char signature[RSA_size(rsa)]; // buffer that will hold signature
int slen = 0; // will contain signature size

// rsa is an OpenSSL RSA context, that's loaded with the public/private key pair

memset(signature, 0, sizeof(signature));

RSA_sign(NID_sha1
, (unsigned char*)msgToSign
, strlen(msgToSign)
, signature
, &slen
, rsa);

// now signature contains the message signature
// and can be verified using the RSA_verify counterpart
// .. I would like to verify the signature in C#

在 C# 中,我会执行以下操作:

  • 将对方的公钥导入RSACryptoServiceProvider对象
  • 接收消息及其签名
  • 尝试验证签名

我的前两部分工作正常(我已经验证公钥加载正确,因为我设法将 RSA 加密文本从 C# 代码发送到 C 中的 OpenSSL 代码并成功解密)

为了在 C# 中验证签名,我尝试使用 RSACryptoServiceProvider 的 VerifySignature 方法,但没有成功。在互联网上搜索后,我只能找到一些模糊的信息,指出 .NET 使用与 OpenSSL 不同的方法来生成签名。那么,有人知道如何实现吗?

编辑

因为有一个请求,这里是 C# 方面的事情..

byte[] receivedSignature;
// ....
// receivedSignature is set to the byte array generated by the OpenSSL side
// I've verified this much is working correctly

// I use my utility to parse a PEM file and extract the other side's public key
// also, verified to be working correctly - the public key is good.
RSACryptoServiceProvider rsa = MyPEMLoader.LoadFromFile("publicKey.pem");

string msgToVerify = "Hello World";
byte[] msgBytes = Encoding.ASCII.GetBytes(msg); // other side uses ASCII, so do the same
bool verified = rsa.VerifyHash(msgBytes, "SHA1", receivedSignature);

// verfied is false.. verfification failed!

最佳答案

如果您展示了您的 C# 代码,它可能会有所帮助。我认为它应该是这样的:

<罢工>

<罢工>
    string msg = ...;
byte[] localData = Encoding.UTF8.GetBytes(msg);
bool ok = rsa.VerifyHash(localData, "SHA1", receivedhash);

当然,我只是在猜测 UTF-8 部分。也可能是 ASCII。

<罢工>

编辑:这里是 MSDN page .该示例似乎有所不同,首先对 localData 进行哈希处理。

hashedData = hash.ComputeHash(signedData);
return rsaCSP.VerifyHash(hashedData, CryptoConfig.MapNameToOID("SHA1"), signature);

关于c# - RSA_sign 和 RSACryptoProvider.VerifySignature,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2812003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com