Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / SecretSealer.kt

SecretSealer.kt125 lines · 5.3 KiBRaw
1package com.vayunmathur.communicate.data
2
3import android.security.keystore.KeyGenParameterSpec
4import android.security.keystore.KeyProperties
5import android.util.Base64
6import com.vayunmathur.library.log.Log
7import java.security.KeyStore
8import javax.crypto.Cipher
9import javax.crypto.KeyGenerator
10import javax.crypto.SecretKey
11import javax.crypto.spec.GCMParameterSpec
12
13/**
14 * Seal/unseal for communicate's persisted secrets, mirroring everysync's
15 * `TokenStore`: AES-GCM with a non-exportable AndroidKeyStore key, ciphertext
16 * prefixed with its 12-byte GCM IV. The stored string form is
17 * `"v1:" + Base64(iv || ciphertext)` so a sealed value is unambiguously
18 * distinguishable from a legacy plaintext value (which never carries the
19 * prefix) — that distinction is what makes migration-on-first-read possible.
20 *
21 * Failure contract (all stores using this):
22 * - [seal] returns null on failure; callers must not fall back to plaintext.
23 * - [unseal] returns null on failure (bad prefix, bad Base64, GCM tag
24 * mismatch, missing key); callers return signed-out / not-registered and
25 * must leave the stored blob untouched for a later retry.
26 */
27interface SecretSealer {
28 /** Sealed form of [plain], or null if sealing failed. */
29 fun seal(plain: String): String?
30
31 /** Plaintext for a value produced by [seal], or null if it cannot be unsealed. */
32 fun unseal(sealed: String): String?
33
34 /** True if [value] carries the sealed prefix (regardless of whether it decrypts). */
35 fun isSealed(value: String): Boolean
36}
37
38/**
39 * AndroidKeyStore-backed [SecretSealer] (everysync `TokenStore` pattern, same
40 * alias style / transformation / IV-prefix layout, communicate-scoped alias).
41 */
42class KeystoreSecretSealer : SecretSealer {
43
44 /** Test seam: a software key replacing the AndroidKeyStore key (which Robolectric lacks). */
45 internal var secretKeyForTest: SecretKey? = null
46
47 // Ephemeral software key, used only when AndroidKeyStore is unavailable
48 // (JVM/Robolectric tests). On a real device the Keystore path always
49 // succeeds, so production secrets never touch this key; if it were ever
50 // used on-device, its loss on process death yields unseal-failure
51 // (signed-out, blob intact), never plaintext.
52 @Volatile
53 private var softwareFallbackKey: SecretKey? = null
54
55 private fun secretKey(): SecretKey {
56 secretKeyForTest?.let { return it }
57 try {
58 val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
59 (ks.getEntry(KEY_ALIAS, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }
60 val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
61 generator.init(
62 KeyGenParameterSpec.Builder(
63 KEY_ALIAS,
64 KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
65 )
66 .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
67 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
68 .build(),
69 )
70 return generator.generateKey()
71 } catch (expected: Exception) {
72 Log.error(TAG, "AndroidKeyStore unavailable, using ephemeral software key", expected)
73 return softwareFallbackKey ?: synchronized(this) {
74 softwareFallbackKey ?: KeyGenerator.getInstance("AES").apply { init(256) }
75 .generateKey().also { softwareFallbackKey = it }
76 }
77 }
78 }
79
80 override fun seal(plain: String): String? = try {
81 val cipher = Cipher.getInstance(TRANSFORMATION)
82 cipher.init(Cipher.ENCRYPT_MODE, secretKey())
83 val iv = cipher.iv
84 val ct = cipher.doFinal(plain.toByteArray(Charsets.UTF_8))
85 val blob = ByteArray(iv.size + ct.size).also {
86 iv.copyInto(it, 0)
87 ct.copyInto(it, iv.size)
88 }
89 SEALED_PREFIX + Base64.encodeToString(blob, Base64.NO_WRAP)
90 } catch (expected: Exception) {
91 Log.error(TAG, "Failed to seal secret", expected)
92 null
93 }
94
95 override fun unseal(sealed: String): String? {
96 if (!isSealed(sealed)) return null
97 return try {
98 val blob = Base64.decode(sealed.removePrefix(SEALED_PREFIX), Base64.NO_WRAP)
99 if (blob.size <= GCM_IV_LEN) return null
100 val iv = blob.copyOfRange(0, GCM_IV_LEN)
101 val ct = blob.copyOfRange(GCM_IV_LEN, blob.size)
102 val cipher = Cipher.getInstance(TRANSFORMATION)
103 cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))
104 String(cipher.doFinal(ct), Charsets.UTF_8)
105 } catch (expected: Exception) {
106 Log.error(TAG, "Failed to unseal secret", expected)
107 null
108 }
109 }
110
111 override fun isSealed(value: String): Boolean = value.startsWith(SEALED_PREFIX)
112
113 companion object {
114 private const val ANDROID_KEYSTORE = "AndroidKeyStore"
115 private const val KEY_ALIAS = "communicate_secret_key"
116 private const val TRANSFORMATION = "AES/GCM/NoPadding"
117 private const val GCM_IV_LEN = 12
118 private const val GCM_TAG_BITS = 128
119 private const val SEALED_PREFIX = "v1:"
120 private const val TAG = "SecretSealer"
121
122 /** Process-wide instance shared by all communicate secret stores. */
123 val shared: KeystoreSecretSealer = KeystoreSecretSealer()
124 }
125}