tags:

views:

1067

answers:

3

Hi, in languages like PHP or Python there are convenient functions to turn an input string into an output string that is the HEXed representation of it.

I find it a very common and useful task (password storing and checking, checksum of file content..), but in .NET, as far as I know, you can only work on byte streams.

A function to do the work is easy to put on (eg http://blog.stevex.net/index.php/c-code-snippet-creating-an-md5-hash-string/), but I'd like to know if I'm missing something, using the wrong pattern or there is simply no such thing in .NET.

Thanks

+4  A: 

Yes you can only work with bytes (as far as I know). But you can turn those bytes easily into their hex representation by looping through them and doing something like:

myByte.ToString("x2");

And you can get the bytes that make up the string using:

System.Text.Encoding.UTF8.GetBytes(myString);

So it could be done in a couple lines.

colithium
+4  A: 

The method you linked to seems right, a slightly different method is showed on the MSDN C# FAQ

A comment suggests you can use:

System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(string, "MD5");
Dykam
But please *don't* use the code shown in the FAQ, as is uses Encoding.ASCII and will therefore treat all non-ASCII characters as "?" - making it a pretty awful hash.
Jon Skeet
+3  A: 

One problem is with the very concept of "the HEXed representation of [a string]".

A string is a sequence of characters. How those characters are represented as individual bits depends on the encoding. The "native" encoding to .NET is UTF-16, but usually a more compact representation is achieved (while preserving the ability to encode any string) using UTF-8.

You can use Encoding.GetBytes to get the encoded version of a string once you've chosen an appropriate encoding - but the fact that there is that choice to make is the reason that there aren't many APIs which go straight from string to base64/hex or which perform encryption/hashing directly on strings. Any such APIs which do exist will almost certainly be doing the "encode to a byte array, perform appropriate binary operation, decode opaque binary data to hex/base64".

(That makes me wonder whether it wouldn't be worth writing a utility class which could take an encoding, a Func<byte[], byte[]> and an output format such as hex/base64 - that could represent an arbitrary binary operation applied to a string.)

Jon Skeet