从python转换为C#的方法

时间:2019-02-18 09:09:55

标签: c# python hash

我有一种方法需要基于此python代码在C#中进行重制。

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;

            }
        }


    }

1 个答案:

答案 0 :(得分:0)

经过更多的研究和反复试验,我发现了产生与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();

            }
        }


    }