Android - 使用指纹认证加密和解密数据

Aug*_*ani 3 android

我从 3 天开始就面临问题。我需要将 EditText 中的文本保存到 SharedPreferences 中。用户使用指纹扫描仪进行身份验证后,应将此文本加密保存在 SharedPreference 中。然后我需要解密这些数据,所以我需要一个永久存储机制来生成 SecretKey。

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();
}
Run Code Online (Sandbox Code Playgroud)

当我尝试KeyStore使用FileInputStream以下方法从文件加载时发生问题:

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;

}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

java.lang.IllegalArgumentException:
android.security.keystore.AndroidKeyStoreSpi.engineLoad(AndroidKeyStoreSpi.java:930)不支持 InputStream

没有.setUserAuthenticationRequired(true)我就没有这个问题,但我认为这不是使用指纹安全性的正确方法。

Ale*_*bin 5

Android Keystore 的存储位于您的应用进程之外。因此,您无需将其存储到文件中或从文件中加载它。你需要做的就是调用keyStore.load(null),你应该很高兴。