您好,我一直在寻找互联网,我无法找到解决我的签名和验证问题的方法。首先,我想确保我在理解发生的事情时走上正轨,请纠正我。签名的第一件事是服务器首先创建两个密钥,一个是公共密钥,一个是私有密钥。然后,服务器放入数据文本,公钥,然后在文件上进行散列和加密(使用它的私钥)数据文本。服务器将文件发送到客户端,客户端开始通过获取文件中的公钥来验证数据,并使用它来解密加密数据。最后,客户端使用散列算法(与服务器相同)对文本数据进行比较,并将其与解密后的数据进行比较。
如果这样可以,那么我不明白为什么我的代码无效:
服务器:
string name = textBox1.Text;
string GUID = textBox2.Text;
string startDate = textBox3.Text;
string EndDate = textBox4.Text;
string macAddress = GetMacAddress();
FileStream fs = File.Create(@"cert.txt");
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
UnicodeEncoding ByteConverter = new UnicodeEncoding();
StreamWriter write = new StreamWriter(fs);
write.Write(name + "\r\n");
write.Write(GUID + "\r\n");
write.Write(startDate + "\r\n");
write.Write(EndDate + "\r\n");
write.Write(macAddress + "\r\n");
string pkey = RSA.ToXmlString(false);
write.Write(pkey + "\r\n");
SHA1Managed Sha = new SHA1Managed();
string info = name + GUID + startDate + EndDate + macAddress;
byte [] hashed = Sha.ComputeHash(Encoding.UTF8.GetBytes(info));
byte []signature = RSA.SignData(hashed,CryptoConfig.MapNameToOID("SHA1"));
write.Write(Convert.ToBase64String(signature));
textBox5.Text = Convert.ToBase64String(hashed);
write.Close();
fs.Close();
客户端:
FileStream fsSource = new FileStream(@"cert.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fsSource);
string name = reader.ReadLine();
string GUID = reader.ReadLine();
string startDate = reader.ReadLine();
string EndDate = reader.ReadLine();
string macAddress = reader.ReadLine();
string pkey = reader.ReadLine();
string signed = reader.ReadLine();
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString(pkey);
string info = name + GUID + startDate + EndDate + macAddress;
SHA1Managed Sha = new SHA1Managed();
byte[] checkinghash = Sha.ComputeHash(Encoding.UTF8.GetBytes(info));
if (RSA.VerifyHash(checkinghash, CryptoConfig.MapNameToOID("SHA1"), Encoding.UTF8.GetBytes(signed)))
{
Console.WriteLine("verfied");
}
else
{
Console.WriteLine("denied");
}
Console.WriteLine();
//Console.WriteLine(signed);
Console.ReadKey();
这总是产生拒绝,因为我不确定我是否错过了公钥,或者这是否是错误的方法。
答案 0 :(得分:2)
你的问题是 您在服务器端使用SignData
byte []signature = RSA.SignData(hashed,CryptoConfig.MapNameToOID("SHA1"));
但在您的客户端上使用VerifyHash
if (RSA.VerifyHash(checkinghash, CryptoConfig.MapNameToOID("SHA1"), Encoding.UTF8.GetBytes(signed)))
服务器上的您必须使用SignHash
byte []signature = RSA.SignHash(hashed,CryptoConfig.MapNameToOID("SHA1"));
并且您还必须更改下面的if
if (RSA.VerifyHash(checkinghash, CryptoConfig.MapNameToOID("SHA1"),Convert.FromBase64String(signed)))