Android Byte Array Compare compareSecure(byte[] test, byte[] good)

Here you can find the source of compareSecure(byte[] test, byte[] good)

Description

Compare two byte arrays.

License

Open Source License

Parameter

Parameter Description
test the first array
good the second array

Return

true if both byte arrays contain the same bytes

Declaration

public static boolean compareSecure(byte[] test, byte[] good) 

Method Source Code

//package com.java2s;
/*// ww w. j  a va2s  .  co m
 * Copyright 2004-2008 H2 Group. Multiple-Licensed under the H2 License, Version 1.0, and under the Eclipse Public License, Version 1.0 (http://h2database.com/html/license.html). Initial Developer: H2 Group
 */

public class Main {
    /**
     * Compare two byte arrays. This method will always loop over all bytes and doesn't use conditional operations in the loop to make sure an attacker can not use a timing attack when trying out passwords.
     * 
     * @param test
     *          the first array
     * @param good
     *          the second array
     * @return true if both byte arrays contain the same bytes
     */
    public static boolean compareSecure(byte[] test, byte[] good) {
        if ((test == null) || (good == null)) {
            return (test == null) && (good == null);
        }
        if (test.length != good.length) {
            return false;
        }
        if (test.length == 0) {
            return true;
        }
        // don't use conditional operations inside the loop
        int bits = 0;
        for (int i = 0; i < good.length; i++) {
            // this will never reset any bits
            bits |= test[i] ^ good[i];
        }
        return bits == 0;
    }
}

Related

  1. compare(byte[] as, byte[] bs)
  2. compareByteArray(byte[] src, byte[] dst)
  3. compareByteArray(byte[] src, int srcOffset, byte[] dst, int dstOffset, int length)
  4. compareByteArray(byte[] src, int srcOffset, int srcLen, byte[] dst, int dstOffset, int dstLen)
  5. compareNotNull(byte[] data1, byte[] data2)
  6. compareTo(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, int length2)
  7. compareTo(final byte[] left, final byte[] right)
  8. areEqual(byte[] a, byte[] b)
  9. compare(byte[] arr1, byte[] arr2)