【问题标题】:MessageDigest in Java to C#Java 中的 MessageDigest 到 C#
【发布时间】:2022-11-06 12:21:48
【问题描述】:

我正在尝试将 java 代码翻译成 c#。我有点坚持下面的这个练习:

      MessageDigest md = MessageDigest.getInstance("MD5");
      md.reset();
      md.update(pass.getBytes());
      byte[] enc = md.digest();
      StringBuilder hex = new StringBuilder();
      for (int i = 0; i < enc.length; i++) {
        String h = Integer.toHexString(0xFF & enc[i]);
        hex.append((h.length() == 2) ? h : ("0" + h));
      } 

这是我尝试过的,但我没有得到想要的结果,即以下字符串:“e81e26d88d62aba9ab55b632f25f117d”

我的代码:

using System.Security.Cryptography;
using System.Text;

string user_password = "HELLOWORLD";
byte[] hashBytes = Encoding.UTF8.GetBytes(user_password);
SHA1 sha1 = SHA1Managed.Create();
byte[] cryptPassword = sha1.ComputeHash(hashBytes);
user_password = Encoding.Default.GetString(cryptPassword);

StringBuilder hex = new StringBuilder();
for (int i = 0; i < cryptPassword.Length; i++)
{

    // Store integer 182
    int intValue = cryptPassword[i];
    // Convert integer 182 as a hex in a string variable
    string hexValue = intValue.ToString("X");
    // Convert the hex string back to the number
    int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

    hex.Append((intAgain.ToString().Length == 2) ? intAgain : ("0" + intAgain.ToString()));
}

Console.WriteLine("pass: " + hex.ToString()); 

有人知道答案吗?

【问题讨论】:

  • 对于初学者,您的预期结果是 MD5 哈希,但您的代码正在获取 SHA1 哈希

标签: java c# security


【解决方案1】:

主要问题是您使用的是SHA1 函数而不是MD5。我也不确定你为什么要循环密码长度。无论输入大小如何,每个 MD5 哈希的长度都相同。

using System;
using System.Security.Cryptography;
using System.Text;

string user_password = "HELLOWORLD";
byte[] hashBytes = Encoding.UTF8.GetBytes(user_password);
var md5 = MD5.Create();
var hash = md5.ComputeHash(hashBytes);

StringBuilder hex = new StringBuilder();
foreach (byte b in hash)
    hex.AppendFormat("{0:x2}", b);
Console.WriteLine("pass: " + hex);
return ;

【讨论】:

  • 好的非常感谢。作品!! G
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-07
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多