Java Array Compare arrayCompare(byte[] b1, byte[] b2)

Here you can find the source of arrayCompare(byte[] b1, byte[] b2)

Description

A "safe" array comparison that is not vulnerable to side-channel "timing attacks".

License

BSD License

Parameter

Parameter Description
b1 A byte array to compare.
b2 A second byte array to compare.

Return

true if both byte arrays are null or if both byte arrays are identical or have the same value; otherwise false is returned.

Declaration

public static boolean arrayCompare(byte[] b1, byte[] b2) 

Method Source Code

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

public class Main {
    /**/*  www  .  j av a 2 s.c o  m*/
     * A "safe" array comparison that is not vulnerable to side-channel
     * "timing attacks". All comparisons of non-null, equal length bytes should
     * take same amount of time. We use this for cryptographic comparisons.
     * 
     * @param b1   A byte array to compare.
     * @param b2   A second byte array to compare.
     * @return     {@code true} if both byte arrays are null or if both byte
     *             arrays are identical or have the same value; otherwise
     *             {@code false} is returned.
     */
    public static boolean arrayCompare(byte[] b1, byte[] b2) {
        if (b1 == b2) {
            return true;
        }
        if (b1 == null || b2 == null) {
            return (b1 == b2);
        }
        if (b1.length != b2.length) {
            return false;
        }

        int result = 0;
        // Make sure to go through ALL the bytes. We use the fact that if
        // you XOR any bit stream with itself the result will be all 0 bits,
        // which in turn yields 0 for the result.
        for (int i = 0; i < b1.length; i++) {
            // XOR the 2 current bytes and then OR with the outstanding result.
            result |= (b1[i] ^ b2[i]);
        }
        return (result == 0) ? true : false;
    }
}

Related

  1. areEqualPropPaths(String[] pp1, String[] pp2)
  2. areEquals(byte[] g1, byte[] g2)
  3. arrayCompare(byte src[], short srcOff, byte dest[], short destOff, short length)
  4. arrayCompare(byte[] a, byte[] a2)
  5. arrayCompare(byte[] a1, byte[] a2)
  6. arrayCompare(final T[] a, final T[] b)
  7. arrayCompare(int[] arr1, int[] arr2)
  8. arrayCompareLex(byte[] a, byte[] b)
  9. arrayContentsEq(Object[] a1, Object[] a2)