when using System.Text.UnicodeEncoding.Unicode.GetString(byte[]) reverse encoding to byte array fails intermittently
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:
string salt = Convert.ToBase64String(saltBytes);
byte[] saltBytes2 = Convert.FromBase64String(salt);
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?
精彩评论