Wednesday, July 20, 2022

[FIXED] How to generate MD5 Hash(32/64 Characters) from an integer

Issue

I have Googled and checked

How to generate MD5 Hash(32/64 Characters) from an integer?

What I got is there are examples for generating an MD5 hash string from a string or from a byte array. But in my case, I need to getthe MD5 hash of an integer.

I know that the GetHashCode() method is there to get the hash code for an integer. But this method is not applicable in my case.

Do I need to convert the integer to a string or byte array to get the expected MD5 hash string?


Solution

Something like this:

  int source = 123;
  String hash;

  // Do not omit "using" - should be disposed
  using (var md5 = System.Security.Cryptography.MD5.Create()) 
  {
    hash = String.Concat(md5.ComputeHash(BitConverter
      .GetBytes(source))
      .Select(x => x.ToString("x2")));
  }

  // Test
  // d119fabe038bc5d0496051658fd205e6
  Console.Write(hash);


Answered By - Dmitry Bychenko
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.