17.16. Achieving Secure Unicode Encoding
Problem
You want to make sure that your UnicodeEncoding or UTF8Encoding class detects any errors, such as an invalid sequence of bytes.
Solution
Use 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);
Discussion
The 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:
Leftover bytes that do not make up a complete encoded character sequence exist.
An invalid encoded start character was detected. For example, a UTF8 character does not fit into one of the following classes: Single-Byte, Double-Byte, Three-Byte, Four-Byte, Five-Byte, or Six-Byte.
Extra bits are found after processing an extra byte in a multibyte sequence.
The leftover bytes in a sequence could not be used to create a complete character.
A high surrogate value is not followed by a low surrogate value.
In the case ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access