【发布时间】: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哈希