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 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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?

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.