簡體   English   中英

在 C# 中生成 HMAC-SHA1

[英]generate HMAC-SHA1 in C#

我正在嘗試使用 C# 來使用 REST API。

API 創建者提供了以下用於創建 hmac 的偽代碼。

var key1 = sha1(body);
var key2 = key1 . SECRET_KEY;
var key3 = sha1(key2);
var signature = base64_encode(key3);

上述偽代碼中,body為html請求正文字符串,SECRET_KEY為REST API提供者提供的秘鑰。

據我所知,我需要使用 System.Security.Cryptography.HMACSHA1 類來實現這一點。

但是我無法在 C# 中完全實現上述邏輯。

有什么建議 ?

將上述代碼直接映射到 C# 將類似於:

static string ComputeSignature(byte[] body, byte[] secret) {
    using (var sha1 = SHA1.Create())
    {
        var key1 = sha1.ComputeHash(body);
        var key2 = key1.Concat(secret).ToArray();
        var key3 = sha1.ComputeHash(key2);
        return Convert.ToBase64String(key3);
    }
}

如果您將請求正文作為字符串,請使用適當的編碼將其轉換為字節數組,例如:

var body = Encoding.UTF8.GetBytes(bodyAsString);

如果您將秘密作為字符串 - 這取決於 api 開發人員希望將其轉換為字節數組的方式。 很可能它已經是十六進制或 base64 編碼的字符串。

使其在 c# 中工作的問題是您需要考慮十六進制格式,然后在某些情況下使其工作最終結果應該是小寫的(例如,如果您將其用於 quickblox api 或其他東西)

    private string GetHashedMessage(String _secret)
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        byte[] keyByte = encoding.GetBytes(_secret);
        String _message= "Your message that needs to be hashed";
        HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);

        byte[] messageBytes = encoding.GetBytes(_message);
        byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
        return ByteToString(hashmessage).ToLower();
    }

    public string ByteToString(byte[] buff)
    {
        string sbinary = "";

        for (int i = 0; i < buff.Length; i++)
        {
            sbinary += buff[i].ToString("X2"); // hex format
        }
        return (sbinary);
    }

參考: http : //billatnapier.com/security01.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM