Simple constant-time equality of two byte arrays. - Android Hardware

Android examples for Hardware:Sim Card

Description

Simple constant-time equality of two byte arrays.

Demo Code

/**//from ww  w.  ja  va 2 s .c o m
     * Fixes for the RNG as per
     * http://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html
     * <p/>
     * This software is provided 'as-is', without any express or implied
     * warranty. In no event will Google be held liable for any damages arising
     * from the use of this software.
     * <p/>
     * Permission is granted to anyone to use this software for any purpose,
     * including commercial applications, and to alter it and redistribute it
     * freely, as long as the origin is not misrepresented.
     * <p/>
     * Fixes for the output of the default PRNG having low entropy.
     * <p/>
     * The fixes need to be applied via {@link #apply()} before any use of Java
     * Cryptography Architecture primitives. A good place to invoke them is in
     * the application's {@code onCreate}.
     */
//package com.java2s;

public class Main {
    /**
     * Simple constant-time equality of two byte arrays. Used for security to avoid timing attacks.
     *
     * @param a
     * @param b
     * @return true iff the arrays are exactly equal.
     */
    public static boolean constantTimeEq(byte[] a, byte[] b) {
        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 Tutorials