【发布时间】:2022-01-06 22:51:23
【问题描述】:
我正在尝试使用公钥验证一些数据,我使用私钥签名的方法 ecdsa.VerifyData() 得到了错误的返回,我不知道为什么。
这些是签署和验证数据的方法:
public byte[] SignData(byte[] dataValue)
{
X509Certificate2 privateKey = new X509Certificate2(privateKeyPfxFile);
//Encryting/Signing a hash
using (ECDsa ecdsa = privateKey.GetECDsaPrivateKey())
{
if (ecdsa == null) throw new Exception("Not an ECDSA cert, or has no private key");
return ecdsa.SignData(dataValue, HashAlgorithmName.SHA256);
}
}
public bool VerifyData(byte[] dataValue, byte[] dataSigned)
{
byte[] mycertCer = Properties.Resources.mycertCer;
X509Certificate2 publicKey = new X509Certificate2(mycertCer);
//Checking the hash and signature
using (ECDsa ecdsa = publicKey.GetECDsaPublicKey())
{
if (ecdsa == null) throw new Exception("Not an ECDSA cert, or has no private key");
return ecdsa.VerifyData(dataValue, dataSigned, HashAlgorithmName.SHA256);
}
}
这就是我创建密钥的方式:
public void CreateAsymmetricKeysPair(string path, string keyName)
{
var ecdsa = ECDsa.Create(); // generate asymmetric key pair
var req = new CertificateRequest("cn=localhost", ecdsa, HashAlgorithmName.SHA256);
var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));
// Create PFX (PKCS #12) with private key
File.WriteAllBytes(Path.Join(path, keyName + ".pfx"), cert.Export(X509ContentType.Pfx));
// Create Base 64 encoded CER (public key only)
File.WriteAllText(Path.Join(path,keyName + ".cer"),
"-----BEGIN CERTIFICATE-----\r\n"
+ Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
+ "\r\n-----END CERTIFICATE-----");
}
这是我得到错误回报的单元测试:
private const string rawText = "test";
[Fact]
public void OnSignData_DoReturnSignature_WhenValidStream()
{
//Arrange
var rawBytes = Encoding.UTF8.GetBytes(rawText);
//Act
var signature = licenseService.SignData(rawBytes);
var isValid = licenseService.VerifyData(rawBytes, signature);
//Assert
Assert.True(isValid);
}
我错过了什么吗?
【问题讨论】:
-
我无法在我的计算机上重现该问题。我已经从文件系统加载了 .pfx 和 .cer 文件。检查您的环境中的两个文件是否属于一起以及其余数据的一致性。
-
@Topaco,所以你的意思是这段代码在你的环境中运行良好,是吗?
-
@HenryMigo,我正在读这篇文章,看看我能不能从这里得到什么,tks。
-
是的,Topaco 似乎在说它对他有用。
标签: c# xunit private-key public-key ecdsa