password: add totp codes to main page
- Commit
d4a46944e19558c88ee27783baba3deb743e2bc4- Author
- Vayun <[email protected]>
- When
- 2026-01-16 03:18 UTC (10 months ago)
- Parents
74b3ecf
Diff
library/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/src/main/java/com/vayunmathur/library/ui/Icons.ktindex bda533b901..fe7f0f9dbb 100644--- a/library/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -29,7 +29,7 @@ fun IconDelete() { @Composable fun IconNavigation(navBack: () -> Unit) { IconButton({- navBack+ navBack() }) { Icon(painterResource(R.drawable.arrow_back_24px), "Navigation") }
passwords/src/main/java/com/vayunmathur/passwords/TOTP.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/TOTP.kt b/passwords/src/main/java/com/vayunmathur/passwords/TOTP.ktnew file mode 100644index 0000000000..6b20005014--- /dev/null+++ b/passwords/src/main/java/com/vayunmathur/passwords/TOTP.kt@@ -0,0 +1,52 @@+package com.vayunmathur.passwords++import javax.crypto.Mac+import javax.crypto.spec.SecretKeySpec++object TOTP {+ private fun base32Decode(data: String): ByteArray {+ val base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"+ val clean = data.trim().replace("=", "").replace(" ", "").uppercase()+ val output = mutableListOf<Byte>()+ var buffer = 0+ var bitsLeft = 0+ for (c in clean) {+ val valC = base32Chars.indexOf(c)+ if (valC == -1) continue+ buffer = (buffer shl 5) or valC+ bitsLeft += 5+ if (bitsLeft >= 8) {+ bitsLeft -= 8+ output.add(((buffer shr bitsLeft) and 0xFF).toByte())+ }+ }+ return output.toByteArray()+ }++ private fun hotp(key: ByteArray, counter: Long, digits: Int = 6): String {+ val counterBytes = ByteArray(8)+ var c = counter+ for (i in 7 downTo 0) {+ counterBytes[i] = (c and 0xFF).toByte()+ c = c ushr 8+ }+ val mac = Mac.getInstance("HmacSHA1")+ val keySpec = SecretKeySpec(key, "RAW")+ mac.init(keySpec)+ val hash = mac.doFinal(counterBytes)+ val offset = (hash[hash.size - 1].toInt() and 0x0f)+ val binary = ((hash[offset].toInt() and 0x7f) shl 24) or+ ((hash[offset + 1].toInt() and 0xff) shl 16) or+ ((hash[offset + 2].toInt() and 0xff) shl 8) or+ (hash[offset + 3].toInt() and 0xff)+ val otp = binary % Math.pow(10.0, digits.toDouble()).toInt()+ return otp.toString().padStart(digits, '0')+ }++ fun generate(secret: String, epochSecond: Long): String {+ val key = base32Decode(secret)+ val timeStep = 30L+ val counter = epochSecond / timeStep+ return hotp(key, counter, 6)+ }+}\ No newline at end of file
passwords/src/main/java/com/vayunmathur/passwords/ui/MenuPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/MenuPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/MenuPage.ktindex 81f2d615cd..d84259576d 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/MenuPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/MenuPage.kt@@ -1,13 +1,18 @@ package com.vayunmathur.passwords.ui +import android.content.ClipData+import android.content.ClipboardManager+import android.content.Context import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.*-import androidx.compose.runtime.Composable+import androidx.compose.runtime.* import androidx.compose.runtime.collectAsState+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.navigation3.runtime.NavBackStack@@ -16,6 +21,8 @@ import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.passwords.Route import com.vayunmathur.passwords.Password import com.vayunmathur.passwords.R+import com.vayunmathur.passwords.TOTP+import kotlinx.coroutines.delay @Composable fun MenuPage(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel) {@@ -40,12 +47,71 @@ fun MenuPage(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel) { @Composable private fun PasswordListItem(pass: Password, onClick: () -> Unit) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()++ if (pass.totpSecret.isNullOrBlank()) {+ // No TOTP: simple list item+ ListItem(+ modifier = Modifier+ .fillMaxWidth()+ .clickable { onClick() }+ .padding(horizontal = 8.dp),+ headlineContent = { Text(pass.name.ifBlank { "(no name)" }) },+ supportingContent = { Text(pass.userId) }+ )+ return+ }++ // TOTP present: use identical logic to PasswordPage for smooth timer and code generation+ var currentCode by remember { mutableStateOf("") }+ var progress by remember { mutableFloatStateOf(1f) }++ LaunchedEffect(Unit) {+ while (true) {+ val nowMs = System.currentTimeMillis()+ val nowSeconds = nowMs / 1000++ // 1. Calculate the current 30s bucket (Time Step)+ val timeStep = nowSeconds / 30++ // 2. Generate code based on this bucket+ currentCode = try {+ TOTP.generate(pass.totpSecret, timeStep * 30)+ } catch (_: Exception) {+ "----"+ }++ // 3. Calculate remaining time in this specific bucket+ val millisIntoStep = nowMs % 30000+ val millisRemaining = 30000 - millisIntoStep++ progress = millisRemaining / 30000f++ // Tick frequently for a smooth progress bar+ delay(50)+ }+ }+ ListItem( modifier = Modifier .fillMaxWidth() .clickable { onClick() } .padding(horizontal = 8.dp), headlineContent = { Text(pass.name.ifBlank { "(no name)" }) },- supportingContent = { Text(pass.userId) }+ supportingContent = { Text(pass.userId) },+ trailingContent = {+ Row(Modifier.clickable {+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+ clipboard.setPrimaryClip(ClipData.newPlainText("totp", currentCode))+ }.wrapContentHeight(), verticalAlignment = Alignment.CenterVertically) {+ Text(currentCode, style = MaterialTheme.typography.bodyLarge)+ Spacer(Modifier.width(8.dp))+ Box(contentAlignment = Alignment.Center) {+ CircularProgressIndicator({progress}, Modifier.size(40.dp))+ Icon(painterResource(R.drawable.content_copy_24px), contentDescription = "Copy TOTP", Modifier.size(16.dp))+ }+ }+ } )-}+}\ No newline at end of file
passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordPage.ktindex da0e8f0db1..c00146e6c3 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasswordPage.kt@@ -27,11 +27,9 @@ import com.vayunmathur.passwords.Route import com.vayunmathur.passwords.R import androidx.core.net.toUri import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.passwords.TOTP import kotlinx.coroutines.delay import kotlinx.coroutines.launch-import javax.crypto.Mac-import javax.crypto.spec.SecretKeySpec-import kotlin.math.roundToLong @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -42,7 +40,6 @@ fun PasswordPage(backStack: NavBackStack<Route>, id: Long, viewModel: DatabaseVi val snackbarHostState = remember { SnackbarHostState() } val scope = rememberCoroutineScope() - Scaffold( topBar = { TopAppBar(@@ -146,7 +143,7 @@ fun PasswordPage(backStack: NavBackStack<Route>, id: Long, viewModel: DatabaseVi val timeStep = nowSeconds / 30 // 2. Generate code based on this bucket- currentCode = generateTotp(password.totpSecret!!, timeStep*30)+ currentCode = TOTP.generate(password.totpSecret!!, timeStep*30) // 3. Calculate remaining time in this specific bucket val millisIntoStep = nowMs % 30000@@ -209,51 +206,4 @@ fun PasswordPage(backStack: NavBackStack<Route>, id: Long, viewModel: DatabaseVi } } }-}--// TOTP implementation (RFC 6238) using HMAC-SHA1 and 6 digits-private fun base32Decode(data: String): ByteArray {- val base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"- val clean = data.trim().replace("=", "").replace(" ", "").uppercase()- val output = mutableListOf<Byte>()- var buffer = 0- var bitsLeft = 0- for (c in clean) {- val valC = base32Chars.indexOf(c)- if (valC == -1) continue- buffer = (buffer shl 5) or valC- bitsLeft += 5- if (bitsLeft >= 8) {- bitsLeft -= 8- output.add(((buffer shr bitsLeft) and 0xFF).toByte())- }- }- return output.toByteArray()-}--private fun hotp(key: ByteArray, counter: Long, digits: Int = 6): String {- val counterBytes = ByteArray(8)- var c = counter- for (i in 7 downTo 0) {- counterBytes[i] = (c and 0xFF).toByte()- c = c ushr 8- }- val mac = Mac.getInstance("HmacSHA1")- val keySpec = SecretKeySpec(key, "RAW")- mac.init(keySpec)- val hash = mac.doFinal(counterBytes)- val offset = (hash[hash.size - 1].toInt() and 0x0f)- val binary = ((hash[offset].toInt() and 0x7f) shl 24) or- ((hash[offset + 1].toInt() and 0xff) shl 16) or- ((hash[offset + 2].toInt() and 0xff) shl 8) or- (hash[offset + 3].toInt() and 0xff)- val otp = binary % Math.pow(10.0, digits.toDouble()).toInt()- return otp.toString().padStart(digits, '0')-}--private fun generateTotp(secret: String, epochSecond: Long): String {- val key = base32Decode(secret)- val timeStep = 30L- val counter = epochSecond / timeStep- return hotp(key, counter, 6)-}+}\ No newline at end of file