# Cryptographically proper way to compare Binary data

**URL:** https://talk.remobjects.com/t/cryptographically-proper-way-to-compare-binary-data/9676
**Category:** Snippets
**Tags:** net
**Created:** [June 11, 2016, 2:47pm UTC](https://talk.remobjects.com/t/cryptographically-proper-way-to-compare-binary-data/9676 "2016-06-11T14:47:54Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![antonk](https://talk.remobjects.com/letter_avatar_proxy/v4/letter/a/a5b964/32.png) [@antonk](https://talk.remobjects.com/u/antonk)
#### Post date: [June 11, 2016, 2:47pm UTC](https://talk.remobjects.com/t/cryptographically-proper-way-to-compare-binary-data/9676/1 "2016-06-11T14:47:55Z")

</div>

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;
}
```
