我在使用C#中的RSAwithSHA256过程验证签名时遇到问题。问题是VerifyHash函数将始终返回false,但我相信我使用了正确的过程。我知道RSACryptoServiceProvider默认使用SHA1进行签名,但在这里我只想验证签名。什么可能出错?
#region // public //
public bool Verify(SMBillsAuthResponse response) {
RSACryptoServiceProvider csp = retrieveCryptoServiceProvider();
string verificationMessage = getVerificationMessage(response);
byte[] hash = getSha256Hash(verificationMessage);
byte[] signature = HexStringToByteArray(response.auth.signature);
return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA256"), signature);
}
#endregion
#region // auxiliary //
private RSACryptoServiceProvider retrieveCryptoServiceProvider() {
X509Certificate2 cert = new X509Certificate2(this.publicKeyFile);
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
return csp;
}
private string getVerificationMessage(SMBillsAuthResponse response) {
return this.apiKey + response.auth.nonce + response.auth.timestamp + response.transactionId;
}
private byte[] getSha256Hash(string message) {
SHA256Managed sha256 = new SHA256Managed();
byte[] data = Encoding.Unicode.GetBytes(message);
byte[] hash = sha256.ComputeHash(data);
return hash;
}
#endregion
答案 0 :(得分:1)
似乎我遇到的唯一问题是数据编码错误。而不是Encoding.Unicode.GetBytes(消息)我使用Encoding.UTF8.GetBytes(消息),它工作。