title: Android - Encrypt and decrypt data using fingerprint authentication
body: <p>I'm facing problem from 3 days. I need to save a text from EditText into SharedPreferences. This text should be saved encrypted in SharedPreference after user authenticated with fingerprint scanner. Then I need to decrypt, later, this data so I need a permanent storage mechanism for the SecretKey generated.</p>
  
  <pre><code>private SecretKey createKey(String keyName) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
      KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);
      keyGenerator.init(new KeyGenParameterSpec.Builder(keyName,
              KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
              .setKeySize(DEFAULT_KEY_SIZE)
              .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
              .setUserAuthenticationRequired(true)
              .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
              .build());
      return keyGenerator.generateKey();
  }
  </code></pre>
  
  <p>Problem is happen when I try to load <code>KeyStore</code> from file using <code>FileInputStream</code>:</p>
  
  <pre><code>public static SecretKey getKeyFromKeystore(Context context) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
  
      FileInputStream fis = null;
      try {
          fis = context.openFileInput(KEYSTORE_FILENAME);
      } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
      // FileInputStream fis = context.openFileInput(KEYSTORE_FILENAME);
      keyStore.load(fis, null);
      SecretKey keyStoreKey = null;
  
      try {
          keyStoreKey = (SecretKey) keyStore.getKey(CONFIDENTIALITY_KEY, null);
      } catch (KeyStoreException e) {
          e.printStackTrace();
          return null;
      } catch (NoSuchAlgorithmException e) {
          e.printStackTrace();
          return null;
      } catch (UnrecoverableKeyException e) {
          e.printStackTrace();
          return null;
      }
  
      return  keyStoreKey;
  
  }
  </code></pre>
  
  <p>I'm getting error:</p>
  
  <blockquote>
    <p>java.lang.IllegalArgumentException: InputStream not supported<br>
    at
    android.security.keystore.AndroidKeyStoreSpi.engineLoad(AndroidKeyStoreSpi.java:930)</p>
  </blockquote>
  
  <p>Without <code>.setUserAuthenticationRequired(true)</code> I don't have this problem but I don't think this is the right way to use fingerprint's security.</p>