EncryptedKVStorage: can destroy exisint creating one with a new key
This commit is contained in:
1 parent
875c0f7a50
commit
fbbe4d3a34
2 files changed
+42
-7
No files matched your search
@@ -15,11 +15,19 @@ import kotlin.random.nextUBytes
|
||||
*
|
||||
* Keys are stored encrypted and used hashed so it is not possible to
|
||||
* retrieve them without knowing the encryption key.
|
||||
*
|
||||
* @param plainStore where to store encrypted data
|
||||
* @param encryptionKey key to decrypt existing/encrypt new data. Can cause [DecryptionFailedException]
|
||||
* if the key is wrong and the storage is already initialized with a new key and same [prefix]
|
||||
* @param prefix prefix for keys to distinguish from other data in [plainStore]
|
||||
* @param removeExisting if true, removes all existing data in [plainStore] if the [encryptionKey] can't
|
||||
* decrypt existing encrypted data
|
||||
*/
|
||||
class EncryptedKVStorage(
|
||||
private val plainStore: KVStorage,
|
||||
private var encryptionKey: SymmetricKey,
|
||||
private val prefix: String = "EKVS_"
|
||||
private val prefix: String = "EKVS_",
|
||||
removeExisting: Boolean
|
||||
) : KVStorage {
|
||||
private val op = ProtectedOp()
|
||||
|
||||
@@ -29,10 +37,21 @@ class EncryptedKVStorage(
|
||||
|
||||
init {
|
||||
var encryptedSeed by plainStore.optStored<UByteArray>("$prefix#seed")
|
||||
seed = encryptedSeed?.let { encryptionKey.decrypt(it) }
|
||||
?: Random.nextUBytes(32).also {
|
||||
encryptedSeed = encryptionKey.encrypt(it)
|
||||
}
|
||||
seed = try {
|
||||
encryptedSeed?.let { encryptionKey.decrypt(it) }
|
||||
?: Random.nextUBytes(32).also {
|
||||
encryptedSeed = encryptionKey.encrypt(it)
|
||||
}
|
||||
} catch (x: DecryptionFailedException) {
|
||||
if (removeExisting) {
|
||||
plainStore.keys.filter { it.startsWith(prefix) }.forEach {
|
||||
plainStore.delete(it)
|
||||
}
|
||||
Random.nextUBytes(32).also {
|
||||
encryptedSeed = encryptionKey.encrypt(it)
|
||||
}
|
||||
} else throw x
|
||||
}
|
||||
}
|
||||
|
||||
private fun mkkey(key: String): String =
|
||||
|
||||
Reference in new issue
Block a user