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

一笑奈何 提交于 2021-02-18 17:04:51

问题


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 = "test@gmail.com";
        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


回答1:


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.




回答2:


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

https://github.com/Mauin/RxFingerprint



来源:https://stackoverflow.com/questions/37522370/android-use-fingerprint-scanner-and-cipher-to-encrypt-and-decrypt-multiple-str

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!