繁体   English   中英

如何在C#中使用带有RSAwithSHA256的公钥来验证响应的签名?

[英]How to verify the signature of a response using a public key with RSAwithSHA256 in C#?

我在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

看来我唯一的问题是数据编码错误。 我使用了Encoding.UTF8.GetBytes(message)而不是Encoding.Unicode.GetBytes(message),并且可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM