I am trying to use a self signed certificate to sign a string and then verify that the string is signed correctly.
This is how I create my self signed certificate:
makecert -r -n "CN=AuthCert2" -ss my -a sha1 -pe
After this I export the certificate to a pfx file and try to run the following code:
using System;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Net;
using System.Net.Security;
[TestClass]
public class TestSign
{
[TestMethod]
public void TestSignAndVerify()
{
string toSignString = "This is my string to sign";
byte[] data = UnicodeEncoding.UTF8.GetBytes(toSignString);
SHA1Managed sha1 = new SHA1Managed();
byte[] hash = sha1.ComputeHash(data);
X509Certificate2 signCert = new X509Certificate2("authcert2.pfx", "authpass");
var csp = (RSACryptoServiceProvider)signCert.PrivateKey;
byte[] signedData = csp.SignData(hash, CryptoConfig.MapNameToOID("SHA1"));
RSACryptoServiceProvider csp2 = (RSACryptoServiceProvider)signCert.PublicKey.Key;
bool result = csp2.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signedData);
}
}
Yet I am always getting result as false. I am sure I am missing something very basic here. Any idea what is going on or how I can debug the problem?
thanks,
There are two things wrong within the code. First of all, the SignData
computation already includes calculating the hash (no need to do it yourself) and the second is that you are using VerifyHash
instead of VerifyData
.