Byte-To-Hex Conversion in C# – Gotcha

Software

I was working on some password hashing stuff and ran into a gotcha I thought I’d pass along.

When you have code like the following:

Byte[] data = Encoding.ASCII.GetBytes(pass);
SHA1Managed sham = new SHA1Managed();
Byte[] hash = sham.ComputeHash(data);
string result = "";
foreach (Byte b in hash)
{
result += b.ToString("X"); // convert byte to hex
}
return result;

You’ll get some odd errors. The reason is that statement with the ToString(”X”) call in it. I found out the hard way that this only returns a single character when the value should have a leading zero in it: “D” instead of “0D”.

Use ToString(”X2″) to get the properly-formatted value.

(h/t Anthony Ogden for the sample source code)

Blogged with Flock

Tags: , , ,

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Furl
  • Ma.gnolia
  • Reddit
  • TwitThis
2 Comments

2 Comments

  1. Srboslav  •  Dec 2, 2009 @7:35 am

    Short and clear!
    Thanks, man!

  2. dries hoebeke  •  May 12, 2010 @5:16 am

    nice, exactly what i was looking for!

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">