Cryptographically proper way to compare Binary data

The classic way of comparing two Byte arrays in .NET is

private static bool Equals(byte[] value1, byte[] value2)
{
	if (value1.Length != value2.Length)
	{
		return false;
	}

	for (int i = 0; i < value1.Length; i++)
	{
		if (value1[i] != value2[i])
		{
			return false;
		}
	}

	return true;
}

This code has a major flaw that makes it insecure to use in cryptography stuff. Its execution time heavily depends on the data provided. The recommended way to compare with constant execution time (and to ensure that JIT won’t optimize it making it vulnerable again) is some bit magic:

private static bool Equals(byte[] value1, byte[] value2)
{
	uint diff = (uint)value1.Length ^ (uint)value2.Length;

	for (int i = 0; i < value1.Length && i < value2.Length; i++)
	{
		diff |= (uint)(value1[i] ^ value2[i]);
	}

	return diff == 0;
}
1 Like