|
| 1 | +package rs.wordpress.api.android |
| 2 | + |
| 3 | +import android.os.Build |
| 4 | +import android.security.keystore.KeyGenParameterSpec |
| 5 | +import android.security.keystore.KeyInfo |
| 6 | +import android.security.keystore.KeyProperties |
| 7 | +import android.security.keystore.StrongBoxUnavailableException |
| 8 | +import android.util.Base64 |
| 9 | +import uniffi.wp_mobile.PasswordTransformer |
| 10 | +import uniffi.wp_mobile.PasswordTransformerException |
| 11 | +import java.security.KeyStore |
| 12 | +import javax.crypto.Cipher |
| 13 | +import javax.crypto.KeyGenerator |
| 14 | +import javax.crypto.SecretKey |
| 15 | +import javax.crypto.SecretKeyFactory |
| 16 | +import javax.crypto.spec.GCMParameterSpec |
| 17 | + |
| 18 | +/** |
| 19 | + * A [PasswordTransformer] implementation that uses the Android Keystore for |
| 20 | + * hardware-backed encryption. |
| 21 | + * |
| 22 | + * The AES key is generated and stored inside the Android Keystore — it never |
| 23 | + * leaves the secure hardware (TEE or StrongBox). On devices that support |
| 24 | + * StrongBox (API 28+), the key is stored in the dedicated secure element for |
| 25 | + * stronger isolation. Check [isHardwareBacked] to confirm the key is |
| 26 | + * hardware-protected. |
| 27 | + * |
| 28 | + * Keys are addressed by application name. If a key with the given name already |
| 29 | + * exists in the Keystore it is loaded; otherwise a new one is created. |
| 30 | + * |
| 31 | + * ## Usage |
| 32 | + * |
| 33 | + * ```kotlin |
| 34 | + * val transformer = KeystorePasswordTransformer("my-app") |
| 35 | + * |
| 36 | + * // Encrypt a password |
| 37 | + * val encrypted: String = transformer.encrypt("hunter2") |
| 38 | + * |
| 39 | + * // Decrypt it back |
| 40 | + * val decrypted: String = transformer.decrypt(encrypted) |
| 41 | + * assert(decrypted == "hunter2") |
| 42 | + * |
| 43 | + * // Check hardware backing |
| 44 | + * if (transformer.isHardwareBacked) { |
| 45 | + * // Key is in TEE or StrongBox |
| 46 | + * } |
| 47 | + * ``` |
| 48 | + */ |
| 49 | +class KeystorePasswordTransformer(applicationName: String) : PasswordTransformer { |
| 50 | + |
| 51 | + private val key: SecretKey |
| 52 | + |
| 53 | + /** |
| 54 | + * Whether the encryption key is backed by secure hardware (TEE or StrongBox). |
| 55 | + * |
| 56 | + * Returns `false` on emulators or devices without a hardware-backed Keystore, |
| 57 | + * where the key is protected in software only. |
| 58 | + */ |
| 59 | + val isHardwareBacked: Boolean |
| 60 | + get() { |
| 61 | + val factory = SecretKeyFactory.getInstance(key.algorithm, KEYSTORE_PROVIDER) |
| 62 | + val keyInfo = factory.getKeySpec(key, KeyInfo::class.java) as KeyInfo |
| 63 | + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { |
| 64 | + keyInfo.securityLevel >= KeyProperties.SECURITY_LEVEL_TRUSTED_ENVIRONMENT |
| 65 | + } else { |
| 66 | + @Suppress("DEPRECATION") |
| 67 | + keyInfo.isInsideSecureHardware |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + init { |
| 72 | + val keyStore = KeyStore.getInstance(KEYSTORE_PROVIDER) |
| 73 | + keyStore.load(null) |
| 74 | + |
| 75 | + key = (keyStore.getKey(applicationName, null) as? SecretKey) |
| 76 | + ?: generateKey(applicationName) |
| 77 | + } |
| 78 | + |
| 79 | + // The Cipher and KeyStore APIs throw a wide variety of checked and unchecked |
| 80 | + // exceptions (InvalidKeyException, BadPaddingException, IllegalBlockSizeException, |
| 81 | + // etc.). We catch broadly and wrap them into a single PasswordTransformerException |
| 82 | + // so callers get a uniform error type that crosses the UniFFI boundary cleanly. |
| 83 | + @Suppress("TooGenericExceptionCaught", "SwallowedException") |
| 84 | + override fun encrypt(password: String): String { |
| 85 | + try { |
| 86 | + val cipher = Cipher.getInstance(TRANSFORMATION) |
| 87 | + cipher.init(Cipher.ENCRYPT_MODE, key) |
| 88 | + |
| 89 | + val iv = cipher.iv |
| 90 | + val ciphertext = cipher.doFinal(password.toByteArray(Charsets.UTF_8)) |
| 91 | + |
| 92 | + val combined = ByteArray(iv.size + ciphertext.size) |
| 93 | + System.arraycopy(iv, 0, combined, 0, iv.size) |
| 94 | + System.arraycopy(ciphertext, 0, combined, iv.size, ciphertext.size) |
| 95 | + |
| 96 | + return Base64.encodeToString(combined, Base64.NO_WRAP) |
| 97 | + } catch (e: Exception) { |
| 98 | + val reason = "${e.javaClass.simpleName}: " + |
| 99 | + (e.message ?: "Unknown encryption error") |
| 100 | + throw PasswordTransformerException.EncryptionFailed(reason) |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + @Suppress("TooGenericExceptionCaught", "SwallowedException") // See comment on encrypt() |
| 105 | + override fun decrypt(password: String): String { |
| 106 | + try { |
| 107 | + val combined = Base64.decode(password, Base64.NO_WRAP) |
| 108 | + |
| 109 | + require(combined.size >= GCM_IV_SIZE + GCM_TAG_SIZE) { "Ciphertext too short" } |
| 110 | + |
| 111 | + val iv = combined.copyOfRange(0, GCM_IV_SIZE) |
| 112 | + val ciphertext = combined.copyOfRange(GCM_IV_SIZE, combined.size) |
| 113 | + |
| 114 | + val cipher = Cipher.getInstance(TRANSFORMATION) |
| 115 | + cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(GCM_TAG_SIZE_BITS, iv)) |
| 116 | + |
| 117 | + val plaintext = cipher.doFinal(ciphertext) |
| 118 | + return String(plaintext, Charsets.UTF_8) |
| 119 | + } catch (e: PasswordTransformerException) { |
| 120 | + throw e |
| 121 | + } catch (e: Exception) { |
| 122 | + val reason = "${e.javaClass.simpleName}: " + |
| 123 | + (e.message ?: "Unknown decryption error") |
| 124 | + throw PasswordTransformerException.DecryptionFailed(reason) |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + companion object { |
| 129 | + private const val KEYSTORE_PROVIDER = "AndroidKeyStore" |
| 130 | + private const val TRANSFORMATION = "AES/GCM/NoPadding" |
| 131 | + private const val GCM_IV_SIZE = 12 |
| 132 | + private const val GCM_TAG_SIZE_BITS = 128 |
| 133 | + private const val GCM_TAG_SIZE = GCM_TAG_SIZE_BITS / 8 |
| 134 | + private const val AES_KEY_SIZE = 256 |
| 135 | + |
| 136 | + private fun generateKey(applicationName: String): SecretKey { |
| 137 | + val builder = KeyGenParameterSpec.Builder( |
| 138 | + applicationName, |
| 139 | + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT |
| 140 | + ) |
| 141 | + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) |
| 142 | + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) |
| 143 | + .setKeySize(AES_KEY_SIZE) |
| 144 | + |
| 145 | + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { |
| 146 | + builder.setIsStrongBoxBacked(true) |
| 147 | + } |
| 148 | + |
| 149 | + val keyGenerator = KeyGenerator.getInstance( |
| 150 | + KeyProperties.KEY_ALGORITHM_AES, |
| 151 | + KEYSTORE_PROVIDER |
| 152 | + ) |
| 153 | + |
| 154 | + try { |
| 155 | + keyGenerator.init(builder.build()) |
| 156 | + return keyGenerator.generateKey() |
| 157 | + } catch (_: StrongBoxUnavailableException) { |
| 158 | + // StrongBox not available on this device, fall back to TEE |
| 159 | + builder.setIsStrongBoxBacked(false) |
| 160 | + keyGenerator.init(builder.build()) |
| 161 | + return keyGenerator.generateKey() |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | +} |
0 commit comments