views:

25

answers:

2

Can someone tell me why the following code intermittently throws an exception ? I am running Vista Ultimate 32 bit and VS2010 .NET4

       byte[] saltBytes = new byte[32];

        RNGCryptoServiceProvider.Create().GetBytes(saltBytes);

        string salt = System.Text.UnicodeEncoding.Unicode.GetString(saltBytes);

        byte[] saltBytes2 = System.Text.UnicodeEncoding.Unicode.GetBytes(salt);

        int i = 0;
        foreach(byte b in saltBytes)
        {
            if (saltBytes[i] != saltBytes2[i])
            {
                throw new Exception();
            }

            i++;
        }
+2  A: 

You can't use random bytes to create a unicode string. Certain byte sequences are illegal in the encoding assumed by that method. Why are you trying to make random bytes into a string?

GregS
I was not aware that certain byte sequences are illegal. I was using the unicode encoding to convert the salt bytes to a string in my own password hashing component. I will use the base64 encoding instead.Thanks
Areg Sarkissian
+3  A: 

It's probably happening because an arbitrary sequence of random bytes isn't necessarily convertible to a legal unicode string.

When your random bytes are convertible to legal unicode then your encoding/decoding will work without error; when they're not convertible then you'll get problems.

If you need a string representation of a random sequence of bytes then you should probably use Base-64 encoding:

string salt = Convert.ToBase64String(saltBytes);

byte[] saltBytes2 = Convert.FromBase64String(salt);
LukeH