`CryptoJS.HmacSHA256` 的 C# 等价物是什么

时间:2021-07-01 14:48:20

标签: c# cryptojs

我有一些用 javascript 编写的代码如下,它们可以正常工作:

var generateSignature = function(apiKey, apiSecret, meetingNumber, role) {

    // Prevent time sync issue between client signature generation and zoom 
    var timestamp = new Date().getTime() - 30000;
    var msg = btoa(apiKey + meetingNumber + timestamp + role);
    var hash = window.CryptoJS.HmacSHA256(msg, apiSecret);
    var hashedBaseItems = CryptoJS.enc.Base64.stringify(hash);
    var encodableString = apiKey + "." + meetingNumber + "." + timestamp + "." + role + "." + hashedBaseItems;
    signature = btoa(encodableString);
    return signature;
}

我正在尝试将它们转换为 C# 等效项,但结果喜忧参半。这是我目前所拥有的:

    public string GenerateSignature(int role, long meetingNumber)
    {
        // Prevent time sync issue between client signature generation and zoom 
        long timeStamp = this.getLinuxEpochTimestamp() - 30000;

        string baseItems = _plusConfig.Value.ZoomApiKey + meetingNumber + timeStamp + role;
        string msg = this.jsbtoaEquivalentEncoding(baseItems);
        string hashedBaseItems = generateHash(msg, _plusConfig.Value.ZoomApiSecret);
        string dottedItems = _plusConfig.Value.ZoomApiKey + "." + meetingNumber + "." + timeStamp + "." + role + "." + hashedBaseItems;

        return this.jsbtoaEquivalentEncoding(dottedItems);
    }

    private long getLinuxEpochTimestamp()
    {
        return (long) DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
    }

    private string jsbtoaEquivalentEncoding(string toEncode)
    {
        byte[] bytes = Encoding.GetEncoding(28591).GetBytes(toEncode);
        string toReturn = System.Convert.ToBase64String(bytes);
        return toReturn;
    }

    private static string generateHash(string str, string cypherkey)
    {
        // based on CryptoJS.enc.Base64.parse
        byte[] keyBytes = Convert.FromBase64String(cypherkey);

        using (HMACSHA256 hmacsha256 = new HMACSHA256(keyBytes))
        {
            byte[] hashmessage = hmacsha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));
            return Convert.ToBase64String(hashmessage);
        }
    }

generateHash 函数返回的内容与 CryptoJS.HmacSHA256 函数完全不同的情况下,我做错了什么?

1 个答案:

答案 0 :(得分:0)

private static string generateHash(string str, string cypherkey)
{
    var encoding = new System.Text.ASCIIEncoding();

    var messageBytes = encoding.GetBytes(str);
    var keyBytes = encoding.GetBytes(cypherkey);

    using var hmacsha256 = new HMACSHA256(keyBytes);
    var hashmessage = hmacsha256.ComputeHash(messageBytes);
    return Convert.ToBase64String(hashmessage);
}

应该可以解决问题。

相关问题