Constant-time comparison of two byte arrays. - CSharp System

CSharp examples for System:Byte Array

Description

Constant-time comparison of two byte arrays.

Demo Code


using System.Linq;
using System;//from  w  w  w.j a  v  a  2 s  .c  o m

public class Main{
        /// <summary>
        ///     Constant-time comparison of two byte arrays.
        /// </summary>
        /// <param name="a">The first byte array.</param>
        /// <param name="b">The second byte array.</param>
        /// <returns><c>true</c> if valid; otherwise, <c>false</c>.</returns>
        /// <exception cref="OverflowException"></exception>
        public static bool ConstantTimeEquals(byte[] a, byte[] b)
        {
            var diff = (uint) a.Length ^ (uint) b.Length;
            for (var i = 0; i < a.Length && i < b.Length; i++)
                diff |= (uint) (a[i] ^ b[i]);
            return diff == 0;
        }
}

Related Tutorials