簡體   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