我需要在SharedPreferences中保存并加载字符串savedText,所以我需要对字符串进行加密和解密。我将字符串保存在saveText()并加载到loadText(String UNIC)。UNIC是保存我的字符串的ID。我有此代码,它可以工作,但不能加密。
private void saveText() throws GeneralSecurityException, IOException {
for (int i = 0; i < myArr.size(); i++) { //here i create my string
SAVEDITEMS = SAVEDITEMS + myArr.get(i).replace("✔", "") + "&";
}
KeyGenParameterSpec keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC;
String masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec);
String fileToWrite = SAVEDITEMS;
//getFilesDir() is ok? is was variable directory at documentation
try {
EncryptedFile encryptedFile = new EncryptedFile.Builder(
new File(getApplicationContext().getFilesDir(), fileToWrite),
getApplicationContext(),
masterKeyAlias,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
encryptedFile.openFileOutput()));
writer.write("MY SUPER-SECRET INFORMATION");
} catch (GeneralSecurityException gse) {
// Error occurred getting or creating keyset.
} catch (IOException ex) {
// Error occurred opening file for writing.
}
sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(UNIC, SAVEDITEMS);
ed.commit();
}
private void loadText(String UNIC) throws GeneralSecurityException, IOException {
KeyGenParameterSpec keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC;
String masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec);
String fileToRead = SAVEDITEMS;
EncryptedFile encryptedFile = new EncryptedFile.Builder(
new File(getApplicationContext().getFilesDir(), fileToRead),
getApplicationContext(),
masterKeyAlias,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build();
StringBuffer stringBuffer = new StringBuffer();
try (BufferedReader reader =
new BufferedReader(new FileReader(String.valueOf(encryptedFile)))) {
String line = reader.readLine();
while (line != null) {
stringBuffer.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred opening raw file for reading.
} finally {
String contents = stringBuffer.toString();
}
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(UNIC, SAVEDITEMS);
//here i toast my string
Toast toast = Toast.makeText(getApplicationContext(),
savedText, Toast.LENGTH_SHORT);
toast.show();
}
}
请帮帮我,是getFilesDir()还是其他地方的问题?谢谢你的帮助。对我来说真的很重要。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句