This commit is contained in:
Alvin-Zilverstand committed 2026-11-19 11:23:59 +01:00
1 parent 8b54b0a2c4
commit 0d3e076115
21 files changed
+1313

No files matched your search

@@ -0,0 +1,46 @@
package dev.alvin.litellmdashboard
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
class ConnectionStore(context: Context) {
private val prefs = context.getSharedPreferences("connection", Context.MODE_PRIVATE)
private val alias = "litellm_dashboard_key"
private fun secretKey(): SecretKey {
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(store.getKey(alias, null) as? SecretKey)?.let { return it }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
init(KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.build())
}.generateKey()
}
fun save(connection: Connection) {
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, secretKey()) }
val encrypted = cipher.doFinal(connection.apiKey.toByteArray(Charsets.UTF_8))
prefs.edit().putString("url", connection.baseUrl)
.putString("key", Base64.encodeToString(encrypted, Base64.NO_WRAP))
.putString("iv", Base64.encodeToString(cipher.iv, Base64.NO_WRAP)).apply()
}
fun load(): Connection? = try {
val url = prefs.getString("url", null) ?: return null
val encrypted = Base64.decode(prefs.getString("key", null), Base64.NO_WRAP)
val iv = Base64.decode(prefs.getString("iv", null), Base64.NO_WRAP)
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(128, iv)) }
Connection(url, String(cipher.doFinal(encrypted), Charsets.UTF_8))
} catch (_: Exception) { null }
fun clear() { prefs.edit().clear().apply() }
}