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++;
}
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: