Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Use Fingerprint scanner and Cipher to encrypt and decrypt multiple strings

Tags:

android

I need an end to encrypt different strings and related decryptions after user authenticate using fingerprint scanner.

Following this project (https://github.com/StylingAndroid/UserIdentity/tree/Part1) and changed "tryEncrypt" method like below:

  private boolean tryEncrypt(Cipher cipher) {
    try {
        cipher.doFinal(SECRET_BYTES);
        String one = "augusto";
        String two = "[email protected]";
        String three = "3333333331";
        byte[] oneEnc = cipher.doFinal(one.getBytes());
        byte[] twoEnc = cipher.doFinal(one.getBytes());
        byte[] threeEnc = cipher.doFinal(one.getBytes());
        Log.d("test", "oneEnc: " + Base64.encodeToString(oneEnc,0));
        Log.d("test", "twoEnc: " + Base64.encodeToString(twoEnc,0));
        Log.d("test", "threeEnc: " + Base64.encodeToString(threeEnc,0));

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

I'm getting this error:

java.lang.IllegalStateException: IV has already been used. Reusing IV in encryption mode violates security best practices.

What is the correct way on how to do it?

Thanks

*******************UPDATE:*****************************

To help others to get solve this problem I used this library and worked like charm:

https://github.com/Mauin/RxFingerprint

like image 414
Augusto Picciani Avatar asked Oct 18 '25 14:10

Augusto Picciani


1 Answers

You have a problem because your are using a single instance of the Cipher for multiple encryptions (dofinal). You are using a single vector initialization (IV).

Take a look on an option of how to initialize a cipher.

SecureRandom r = new SecureRandom();
byte[] ivBytes = new byte[16];
r.nextBytes(ivBytes);

cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(ivBytes));

As you can see, you need to specify the initialization vector. The initialization vector can not be repeated to guarantee that the encryption works.

In your scenario, you probably gonna need to perform a new initialization.

*Ps: It's also possible to use the Cipher initialization without the IvParameterSpec. In this scenario, the class will generate one for you. However, I believe that you need to perform a initialization per DoFinal to guarantee some randomness.

like image 164
Oximer Avatar answered Oct 21 '25 04:10

Oximer