【问题标题】:Convert SHA Hash Computation in Python to C#将 Python 中的 SHA 哈希计算转换为 C#
【发布时间】:2011-04-23 09:56:32
【问题描述】:

谁能帮我把下面两行python转换成C#。

hash = hmac.new(secret, data, digestmod = hashlib.sha1)
key = hash.hexdigest()[:8]

如果你有兴趣,其余的看起来像这样:

#!/usr/bin/env python

import hmac
import hashlib


secret = 'mySecret'     
data = 'myData'

hash = hmac.new(secret, data, digestmod = hashlib.sha1)
key = hash.hexdigest()[:8]

print key

谢谢

【问题讨论】:

    标签: c# python hash sha1


    【解决方案1】:

    您可以使用HMACSHA1 类来计算哈希:

    class Program
    {
        static void Main()
        {
            var secret = "secret";
            var data = "data";
            var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret));
            var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
            Console.WriteLine(BitConverter.ToString(hash));
        }
    }
    

    【讨论】:

    • 为了打印密钥,我添加了: string key = string.Empty; foreach(哈希中的字节 b){ key += b.ToString("X2"); } MessageBox.Show(key);
    • 或者你可以BitConverter.ToString(hash).Replace("-", string.Empty)
    • 您可以像这样将 using 语句添加到 HMACSHA1 实例以正确处理它:using var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret));(C# 8 或更高版本。在旧版本中使用 using 块)。这将确保在 HMACSHA1 实例上调用 dispose 方法。
    猜你喜欢
    • 1970-01-01
    • 2011-10-14
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 2020-12-09
    • 1970-01-01
    • 2010-11-25
    相关资源
    最近更新 更多