-
Notifications
You must be signed in to change notification settings - Fork 239
/
EncryptedKeyValueRepository.kt
78 lines (66 loc) · 2.38 KB
/
EncryptedKeyValueRepository.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.amplify.amplify_secure_storage
import android.content.Context
import android.content.SharedPreferences
import androidx.annotation.VisibleForTesting
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV
import androidx.security.crypto.EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
import androidx.security.crypto.MasterKeys
import java.io.File
open class EncryptedKeyValueRepository(
private val context: Context,
private val sharedPreferencesName: String,
) : KeyValueRepository {
private val sharedPreferences: SharedPreferences by lazy {
val isInitialized = initializationFlagFile.exists()
if (!isInitialized) {
// Attempt to remove previous SharedPreferences file if not initialized.
removeSharedPreferencesFile()
initializationFlagFile.createNewFile()
}
val sharedPreferences = EncryptedSharedPreferences.create(
sharedPreferencesName,
MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
context,
AES256_SIV,
AES256_GCM
)
sharedPreferences
}
private val editor: SharedPreferences.Editor by lazy {
sharedPreferences.edit()
}
override fun put(dataKey: String, value: String?) {
with(editor) {
putString(dataKey, value)
apply()
}
}
override fun get(dataKey: String): String? = sharedPreferences.getString(dataKey, null)
override fun remove(dataKey: String) {
with(editor) {
remove(dataKey)
apply()
}
}
override fun removeAll() {
with(editor) {
clear()
apply()
}
}
@VisibleForTesting
open fun removeSharedPreferencesFile() {
File("${context.filesDir.parent}/shared_prefs/$sharedPreferencesName.xml").delete()
}
/**
* A file used as a flag to indicate if the SharedPreferences file has been created since the
* most recent app install.
*/
@VisibleForTesting
val initializationFlagFile: File by lazy {
File(context.noBackupFilesDir, "amplify_EncryptedSharedPreferences_$sharedPreferencesName")
}
}