Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MessageDigest in Java to C#

I am trying to translate java code to c#. I’m kind of stuck on this exercise below:

      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));
      } 

This is what I have tried but I am not getting the desired result which would be the following string: "e81e26d88d62aba9ab55b632f25f117d"

My Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()); 

Does anyone know the answer?

>Solution :

Main issue is you are using SHA1 function instead of MD5. Also Im not sure why you are looping over the password length. Every MD5 hash will be the same length regardless of input size.

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 ;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading