All Downloads are FREE. Search and download functionalities are using the official Maven repository.

keyvault.KeyVaultRepo.kt Maven / Gradle / Ivy

There is a newer version: 0.3.1
Show newest version
package se.wollan.crypto.keyvault

import se.wollan.datascope.SqliteDatabase

internal interface KeyVaultRepo {
    suspend fun hasKey(key: String): Boolean

    suspend fun getString(key: String): String?
    suspend fun getBytes(key: String): ByteArray?
    suspend fun getInt(key: String): Int?

    suspend fun putString(key: String, value: String?)
    suspend fun putBytes(key: String, value: ByteArray?)
    suspend fun putInt(key: String, value: Int?)
}

internal class SqliteKeyVaultRepo(private val db: SqliteDatabase) : KeyVaultRepo {

    override suspend fun hasKey(key: String): Boolean =
        db.execRead(
            "SELECT 1 FROM crypto_key_value WHERE key = @key and value is not null",
            listOf("@key" to key)
        ).isNotEmpty()

    override suspend fun getString(key: String): String? = get(key) as String?

    override suspend fun getBytes(key: String): ByteArray? = get(key) as ByteArray?

    override suspend fun getInt(key: String): Int? = (get(key) as Long?)?.toInt()

    override suspend fun putString(key: String, value: String?) = put(key, value)

    override suspend fun putBytes(key: String, value: ByteArray?) = put(key, value)

    override suspend fun putInt(key: String, value: Int?) = put(key, value)

    private suspend fun get(key: String): Any? =
        db.execRead("SELECT value FROM crypto_key_value WHERE key = @key", listOf("@key" to key))
            .singleOrNull()?.values?.singleOrNull()

    private suspend fun put(key: String, value: Any?): Unit = db.write {
        val params = listOf("@key" to key, "@value" to value)
        val affected =
            db.execWrite("UPDATE crypto_key_value SET value = @value WHERE key = @key", params)
        if (affected == 0)
            db.execWrite("INSERT INTO crypto_key_value (key, value) VALUES (@key, @value)", params)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy