String extensions

Rian Stockbower edited this page Dec 23, 2018 · 4 revisions

System.String extension methods.

Constant time string comparison

It's useful in many cryptographic scenarios to have a string comparison that doesn't leak information about the strings being compared. This is because reasons. The BCL doesn't include any constant time string comparison methods, so I've implemented one in Haystack.

Internally, the two strings are MD5 hashed, and then compared byte by byte, which is significantly slower than traditional string comparison methods which contain optimizations that bail out after the first character mismatch. In cryptography, slower is usually better, so being slower is a feature, not a bug.

const string here = "Here";
const string there = "There";

var areSame = here.ConstantTimeEquals(there);   // false

Trimming

  • Trim(subString)
  • TrimStart(subString)
  • TrimEnd(subString)

These remove the specified subString from the start and/or end of a string. There are optional overloads that take a StringComparison; otherwise the default is Ordinal.

Example:

const string trim = "Hello world";
const string hello = "Hello worldThis is a hello worldHello world";

var trimFront = hello.TrimStart(trim);   // This is a hello worldHello world
var trimEnd = hello.TrimEnd(trim);       // Hello worldThis is a hello world
var trimBoth = hello.Trim(trim);         // This is a hello world 

Shapes

IsBase64()

Perf testing indicates a modulo + regex approach is about 20x faster than using Convert.FromBase64 and catching the exception.

var validBase64 = "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHN0cmluZy4=".IsBase64();  // true
var inValidBase64 = "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHN0cmluZy4".IsBase64();  // false
Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.