Java Array Compare areEqual(final byte[] a, final byte[] b)

Here you can find the source of areEqual(final byte[] a, final byte[] b)

Description

Checks the specified arrays for equality in constant time.

License

Apache License

Parameter

Parameter Description
a The first array. Must not be null .
b The second array. Must not be null .

Return

true if the two arrays are equal, else false .

Declaration

public static boolean areEqual(final byte[] a, final byte[] b) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*from   www.  j a  v a2  s  . co  m*/
     * Checks the specified arrays for equality in constant time. Intended
     * to mitigate timing attacks.
     *
     * @param a The first array. Must not be {@code null}.
     * @param b The second array. Must not be {@code null}.
     *
     * @return {@code true} if the two arrays are equal, else
     *         {@code false}.
     */
    public static boolean areEqual(final byte[] a, final byte[] b) {

        // From http://codahale.com/a-lesson-in-timing-attacks/

        if (a.length != b.length) {
            return false;
        }

        int result = 0;
        for (int i = 0; i < a.length; i++) {
            result |= a[i] ^ b[i];
        }

        return result == 0;
    }
}

Related

  1. areEqual(byte[] a, byte[] b)
  2. areEqual(byte[] a, byte[] b)
  3. areEqual(byte[] a, byte[] b)
  4. areEqual(byte[] array1, byte[] array2)
  5. AreEqual(double[] vector1, double[] vector2)
  6. areEqualBytes(byte[] b1, byte[] b2)
  7. areEqualPropPaths(String[] pp1, String[] pp2)
  8. areEquals(byte[] g1, byte[] g2)
  9. arrayCompare(byte src[], short srcOff, byte dest[], short destOff, short length)