Persist sequence counter in EncryptedSharedPreferences

This commit is contained in:
eddy 2026-07-26 22:33:43 +02:00
commit af3810554e
2 changed files with 9 additions and 4 deletions

View file

@ -166,14 +166,14 @@ class MainActivity : AppCompatActivity() {
bluetoothGatt = null bluetoothGatt = null
relayCharacteristic = null relayCharacteristic = null
seq = 1 seq = 1
loadHmacKey() loadState()
handler.postDelayed(scanRunnable, 500) handler.postDelayed(scanRunnable, 500)
} }
} }
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
loadHmacKey() loadState()
if (hmacKey == null) { if (hmacKey == null) {
statusText.text = "Geen HMAC sleutel - open Instellingen" statusText.text = "Geen HMAC sleutel - open Instellingen"
} else if (!isScanning && bluetoothGatt == null) { } else if (!isScanning && bluetoothGatt == null) {
@ -187,11 +187,12 @@ class MainActivity : AppCompatActivity() {
stopScan() stopScan()
} }
private fun loadHmacKey() { private fun loadState() {
val prefs = PrefsHelper.getPrefs(this) val prefs = PrefsHelper.getPrefs(this)
val hexKey = prefs.getString(PrefsHelper.PREF_KEY, null) val hexKey = prefs.getString(PrefsHelper.PREF_KEY, null)
hmacKey = hexKey?.let { hexStringToBytes(it) } hmacKey = hexKey?.let { hexStringToBytes(it) }
Log.d(TAG, "HMAC key loaded: ${if (hmacKey != null) "${hmacKey!!.size} bytes" else "none"}") seq = prefs.getInt(PrefsHelper.PREF_SEQ, 1).coerceAtMost(PrefsHelper.SEQ_MAX)
Log.d(TAG, "HMAC key loaded: ${if (hmacKey != null) "${hmacKey!!.size} bytes" else "none"}, seq=$seq")
} }
private fun hexStringToBytes(hex: String): ByteArray? { private fun hexStringToBytes(hex: String): ByteArray? {
@ -314,6 +315,8 @@ class MainActivity : AppCompatActivity() {
char.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE char.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
gatt.writeCharacteristic(char) gatt.writeCharacteristic(char)
seq++ seq++
if (seq > PrefsHelper.SEQ_MAX) seq = 1
PrefsHelper.getPrefs(this).edit().putInt(PrefsHelper.PREF_SEQ, seq).apply()
Log.d(TAG, "Sent relay ${if (on) "ON" else "OFF"} (seq=${seq - 1})") Log.d(TAG, "Sent relay ${if (on) "ON" else "OFF"} (seq=${seq - 1})")
} }

View file

@ -12,6 +12,8 @@ object PrefsHelper {
private const val TAG = "PrefsHelper" private const val TAG = "PrefsHelper"
const val PREFS_NAME = "relay_prefs" const val PREFS_NAME = "relay_prefs"
const val PREF_KEY = "hmac_key" const val PREF_KEY = "hmac_key"
const val PREF_SEQ = "seq_counter"
const val SEQ_MAX = 1_000_000
fun getPrefs(context: Context): SharedPreferences { fun getPrefs(context: Context): SharedPreferences {
return try { return try {