从python转换为C#的方法

问题描述 投票:0回答:1

我有一个方法,我需要在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;

            }
        }


    }
c# python hash
1个回答
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();

            }
        }


    }
© www.soinside.com 2019 - 2024. All rights reserved.