方法从python转换为C#

2024-10-03 04:36:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个方法需要在C语言中基于python代码重新生成。你知道吗

def _generateHash(self, password, time_stamp, nonce):
    import hashlib
    shaPw = hashlib.sha1()
    shaPw.update( password )
    m = hashlib.sha1()
    m.update(str(time_stamp))
    m.update(nonce)
    m.update(shaPw.hexdigest())
    m.update(self.api_key_secret)
    return m.hexdigest()

与python相比,C#中的哈希分配是不同的。而且我的散列经验也不是很好。有人能帮我吗?你知道吗

这就是我现在拥有的。你知道吗

    private string GenerateHash(string password, double timeStamp, string nonce)
    {
        using (SHA1Managed sha1 = new SHA1Managed())
        {
            var pwHash = sha1.ComputeHash(Encoding.UTF8.GetBytes(password));
            using (SHA1Managed sha1total = new SHA1Managed())
            {
                sha1total.ComputeHash(Encoding.UTF8.GetBytes(timeStamp.ToString()));
                sha1total.ComputeHash(Encoding.UTF8.GetBytes(nonce));

                string hexaHashPW = "";
                foreach (byte b in pwHash)
                {
                    hexaHashPW += String.Format("{0:x2}", b);
                }

                sha1total.ComputeHash(Encoding.UTF8.GetBytes(hexaHashPW));
                sha1total.ComputeHash(Encoding.UTF8.GetBytes(_SecretApiKey));

                var hmac = new HMACSHA1();

                //string hexaHashTotal = "";
                //foreach (byte b in sha1total.Hash)
                //{
                //    hexaHashTotal += String.Format("{0:x2}", b);
                //}
                hmac.ComputeHash(sha1total.Hash);
                var hexaHashTotal = hmac.Hash;
                var endhash = BitConverter.ToString(hexaHashTotal).Replace("-", "");
                return endhash;

            }
        }


    }

Tags: stringvarupdatepasswordutf8sha1encodingnonce
1条回答
网友
1楼 · 发布于 2024-10-03 04:36:04

在进行了更多的研究、跟踪和出错之后,我找到了产生与python代码相同的散列的方法。你知道吗

这是其他对此有问题的人的答案。你知道吗

    private string GenerateHash(string password, double timeStamp, string nonce)
    {
        using (SHA1Managed sha1 = new SHA1Managed())
        {
            var pwHash = sha1.ComputeHash(Encoding.UTF8.GetBytes(password));
            using (SHA1Managed sha1total = new SHA1Managed())
            {
                string hexaHashPW = "";
                foreach (byte b in pwHash)
                {
                    hexaHashPW += String.Format("{0:x2}", b);
                }

                var hmacPW = new HMACSHA1();
                hmacPW.ComputeHash(pwHash);

                sha1total.ComputeHash(Encoding.UTF8.GetBytes(timeStamp.ToString() + nonce + hexaHashPW + _SecretApiKey));
                var hmac = new HMACSHA1();

                string hexaHashTotal = "";
                foreach (byte b in sha1total.Hash)
                {
                    hexaHashTotal += String.Format("{0:x2}", b);
                }
                hmac.ComputeHash(sha1total.Hash);
                return hexaHashTotal.ToLower();

            }
        }


    }

相关问题 更多 >