首页 > 解决方案 > Android-如何在本地存储和检索 SecretKey 对象并检索它

问题描述

我正在创建一个应该允许加密音频文件的应用程序。我正在创建一个 SecretKey 对象并使用它来加密和解密文件。一切正常,但现在我需要一种方法在本地存储 SecretKey 对象,以便在再次打开应用程序时,可以使用它来解密数据。

我尝试了几种方法,包括以下方法:

final byte[] filesBytes = encodeFile(mySecretKey, stringToSave);
SharedPreferences settings = context.getSharedPreferences(KEY_PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("cryptoKey", Arrays.toString(filesBytes));

为了检索数据,我正在尝试以下操作:

SharedPreferences settings = context.getSharedPreferences(KEY_PREFS, 0);
    String stringArray = settings.getString("cryptoKey", null);

    if (stringArray != null) {
        String[] split = stringArray.substring(1, stringArray.length() - 1).split(", ");
        byte[] array = new byte[split.length];
        for (int i = 0; i < split.length; i++) {
            array[i] = Byte.parseByte(split[i]);
        }
        localSecretKey = new SecretKeySpec(array, "AES");
    }

我还看过以下帖子:如何在 KeyStore 中存储 secretKey 并检索它,但没有帮助。

我需要知道的是,如何在本地存储 SecretKey 对象,以便稍后在重新打开应用程序时检索它?

标签: androidencryptioncryptographysecret-key

解决方案


推荐阅读