Reputation: 4638
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 get the 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?
Upvotes: 2
Views: 10624
Reputation: 169
using some performance-focused features (e.g. span and stackalloc) to allocate less memory during hashing!
usage:
var number = 42;
var hash = number.ToString().ToMD5();
code:
using System;
using System.Security.Cryptography;
using System.Text;
public static class MD5Extensions
{
public static string ToMd5(this string input)
{
var inputBytes = Encoding.ASCII.GetBytes(input);
return inputBytes.ToMd5(0, inputBytes.Length);
}
public static string ToMd5(this byte[] inputBytes, int offset, int count)
{
Span<char> chars = stackalloc char[32];
inputBytes.ToMd5(offset, count, chars);
return chars.ToString();
}
public static void ToMd5(this byte[] input, int offset, int count, Span<char> destination)
{
using var md5 = MD5.Create();
var hashBytes = md5.ComputeHash(input, offset, count);
var charsWritten = 0;
const string format = "X2";
foreach (var hashByte in hashBytes)
{
if (hashByte.TryFormat(destination, out charsWritten, format))
{
destination = destination.Slice(charsWritten);
}
else
{
throw new InvalidOperationException(
$"byte '{hashByte}' could not be parsed using format '{format}' and avaible space of {destination.Length}");
}
}
}
}
Upvotes: 0
Reputation: 4638
Thank you All.After referring all the answers, here i am posting my answer which is containg Generic methods for Generating "MD5 Hash(32/64 Characters) from an integer/string/byte array". Might be helpful for others.
using System;
using System.Security.Cryptography;
using System.Text;
using System.Linq;
namespace ConvertIntToHashCodeConsoleApp
{
class Program
{
static void Main(string[] args)
{
int number = 100;
Console.WriteLine(GetHashMD5(number.ToString()));
Console.WriteLine(GetHashStringFromInteger(number));
Console.Read();
}
/// <summary>
/// Get the Hash Value for MD5 Hash(32 Characters) from an integer
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public static string GetHashStringFromInteger(int number)
{
string hash;
using (var md5 = System.Security.Cryptography.MD5.Create())
{
hash = String.Concat(md5.ComputeHash(BitConverter
.GetBytes(number))
.Select(x => x.ToString("x2")));
}
return hash;
}
/// <summary>
/// Get the Hash Value for sha256 Hash(64 Characters)
/// </summary>
/// <param name="data">The Input Data</param>
/// <returns></returns>
public static string GetHash256(string data)
{
string hashResult = string.Empty;
if (data != null)
{
using (SHA256 sha256 = SHA256Managed.Create())
{
byte[] dataBuffer = Encoding.UTF8.GetBytes(data);
byte[] dataBufferHashed = sha256.ComputeHash(dataBuffer);
hashResult = GetHashString(dataBufferHashed);
}
}
return hashResult;
}
/// <summary>
/// Get the Hash Value for MD5 Hash(32 Characters)
/// </summary>
/// <param name="data">The Input Data</param>
/// <returns></returns>
public static string GetHashMD5(string data)
{
string hashResult = string.Empty;
if (data != null)
{
using (MD5 md5 = MD5.Create())
{
byte[] dataBuffer = Encoding.UTF8.GetBytes(data);
byte[] dataBufferHashed = md5.ComputeHash(dataBuffer);
hashResult = GetHashString(dataBufferHashed);
}
}
return hashResult;
}
/// <summary>
/// Get the Encrypted Hash Data
/// </summary>
/// <param name="dataBufferHashed">Buffered Hash Data</param>
/// <returns> Encrypted hash String </returns>
private static string GetHashString(byte[] dataBufferHashed)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in dataBufferHashed)
{
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
}
}
Modify / any better solution for this code is always welcome.
Upvotes: 1
Reputation: 186688
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);
Upvotes: 4
Reputation: 37808
First you need to convert your integer into a byte array then you can do this:
byte[] hashValue;
using (var md5 = MD5.Create())
{
hashValue = md5.ComputeHash(BitConverter.GetBytes(5));
}
Upvotes: 1
Reputation: 20038
If you want to know what is the md5 hash of "meaning of life" you can
int meaningOfLife = 42;
var result = CalculateMD5Hash(""+meaningOfLife);
This assumes you can
public string CalculateMD5Hash(string input)
{
// step 1, calculate MD5 hash from input
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
Upvotes: 2
Reputation: 3379
You can try this,
int intValue = ; // your value
byte[] intBytes = BitConverter.GetBytes(intValue);
Array.Reverse(intBytes);
byte[] result = intBytes; // you are most probably working on a little-endian machine
byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(result);
// string representation (similar to UNIX format)
string encoded = BitConverter.ToString(hash)
// without dashes
.Replace("-", string.Empty)
// make lowercase
.ToLower();
Upvotes: 0