【问题标题】:Java MessageDigest class in C#C# 中的 Java MessageDigest 类
【发布时间】:2026-02-06 12:35:01
【问题描述】:

我需要将 Java 中完成的某些加密逻辑转换为 C#

MessageDigest updateDigestreset 函数的 C# 等效项是什么?

【问题讨论】:

    标签: c# encryption


    【解决方案1】:

    在 C# 中,类是 HashAlgorithm

    等效于更新的是TransformBlock(...)TransformFinalBlock(...),在调用最终块版本后(您也可以使用空输入)您可以调用Hash 属性,该属性将为您提供摘要值。

    HashAlgorithm 可能在调用最终块后可重用(这意味着它会在您下次调用 TransformBlock 时重置),您可以通过检查属性来仔细检查您的 HashAlgorithm 是否支持重用CanReuseTransform.

    相当于您的 reset()/digest() 组合是一行 byte[] ComputeHash(byte[])

    【讨论】:

    • 只是为了确保,messageDigest,update(inputBuffer, offset, length) 的等价物是 hash.TransfomBlock( inputBuffer, offset, length, inputBuffer, offset)?从docs.microsoft.com/en-us/dotnet/api/… 看来是这样
    【解决方案2】:
    try {
          MessageDigest md = MessageDigest.getInstance("SHA-1");
          md.update(password.getBytes());
          BigInteger hash = new BigInteger(1, md.digest());
          hashword = hash.toString(16);
    } catch (NoSuchAlgorithmException ex) {
          /* error handling */
    }
    return hashword;
    
    public static string HashPassword(string input)
    {
        var sha1 = SHA1Managed.Create();
        byte[] inputBytes = Encoding.ASCII.GetBytes(input);
        byte[] outputBytes = sha1.ComputeHash(inputBytes);
        return BitConverter.ToString(outputBytes).Replace("-", "").ToLower();
    }
    

    【讨论】:

    • 添加一点关于您的答案的 cmets。它帮助我在 C# 中生成摘要。
    【解决方案3】:

    对于 C# 中的摘要,类似于 Java,您可以使用类 Windows.Security.Cryptography.Core。例如,以下方法返回一个 SHA256 哈希,格式为 base64:

    public static string sha256Hash(string data)
    {
        // create buffer and specify encoding format (here utf8)
        IBuffer input = CryptographicBuffer.ConvertStringToBinary(data,
        BinaryStringEncoding.Utf8);
    
        // select algorithm
        var hasher = HashAlgorithmProvider.OpenAlgorithm("SHA256");
        IBuffer hashed = hasher.HashData(input);
    
        // return hash in base64 format
        return CryptographicBuffer.EncodeToBase64String(hashed);
    }
    

    见(mbrit):How to create SHA-256 hashes in WinRT?

    【讨论】: