Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.Sign up
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
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
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
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