Byte-To-Hex Conversion in C# – Gotcha

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: , , ,


0 Responses to “Byte-To-Hex Conversion in C# – Gotcha”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

TwitterCounter for @anthonyrstevens
Add to Technorati Favorites

RSS Feed

View Anthony Stevens's profile on LinkedIn

%d bloggers like this: