Recipe 17.19. Achieving Secure Unicode EncodingProblemYou want to make sure that your UnicodeEncoding or UTF8Encoding class detects any errors, such as an invalid sequence of bytes. SolutionUse the constructor for the UnicodeEncoding class that accepts three parameters: UnicodeEncoding encoding = new UnicodeEncoding(false, true, true); Or use the constructor for the UTF8Encoding class that accepts two parameters: UTF8Encoding encoding = new UTF8Encoding(true, true); DiscussionThe final argument to both these constructors should be TRue. This turns on error detection for this class. Error detection will help when an attacker somehow is able to access and modify a Unicode-or a UTF8-encoded stream of characters. If the attacker is not careful she can invalidate the encoded stream. If error detection is turned on, it will be a first defense in catching these invalid encoded streams. When error detection is turned on, errors such as the following are dealt with by throwing an ArgumentException:
If you use a constructor other than the one shown in this recipe or if you set the last parameter in this constructor to false, any errors in the encoding sequence are ignored and no exception is thrown. See AlsoSee the "UnicodeEncoding Class" and "UTF8Encoding Class" topic in the MSDN documentation. |