|
| 1 | +package com.iterable.iterableapi |
| 2 | + |
| 3 | +import android.util.Base64 |
| 4 | +import android.security.keystore.KeyGenParameterSpec |
| 5 | +import android.security.keystore.KeyProperties |
| 6 | +import java.security.KeyStore |
| 7 | +import javax.crypto.Cipher |
| 8 | +import javax.crypto.KeyGenerator |
| 9 | +import javax.crypto.SecretKey |
| 10 | +import javax.crypto.spec.GCMParameterSpec |
| 11 | +import android.os.Build |
| 12 | +import java.security.KeyStore.PasswordProtection |
| 13 | +import androidx.annotation.VisibleForTesting |
| 14 | + |
| 15 | +class IterableDataEncryptor { |
| 16 | + companion object { |
| 17 | + private const val TAG = "IterableDataEncryptor" |
| 18 | + private const val ANDROID_KEYSTORE = "AndroidKeyStore" |
| 19 | + private const val TRANSFORMATION = "AES/GCM/NoPadding" |
| 20 | + private const val ITERABLE_KEY_ALIAS = "iterable_encryption_key" |
| 21 | + private const val GCM_IV_LENGTH = 12 |
| 22 | + private const val GCM_TAG_LENGTH = 128 |
| 23 | + private val TEST_KEYSTORE_PASSWORD = "test_password".toCharArray() |
| 24 | + |
| 25 | + // Make keyStore static so it's shared across instances |
| 26 | + private val keyStore: KeyStore by lazy { |
| 27 | + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { |
| 28 | + try { |
| 29 | + KeyStore.getInstance(ANDROID_KEYSTORE).apply { |
| 30 | + load(null) |
| 31 | + } |
| 32 | + } catch (e: Exception) { |
| 33 | + IterableLogger.e(TAG, "Failed to initialize AndroidKeyStore", e) |
| 34 | + KeyStore.getInstance("PKCS12").apply { |
| 35 | + load(null, TEST_KEYSTORE_PASSWORD) |
| 36 | + } |
| 37 | + } |
| 38 | + } else { |
| 39 | + KeyStore.getInstance("PKCS12").apply { |
| 40 | + load(null, TEST_KEYSTORE_PASSWORD) |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + init { |
| 47 | + if (!keyStore.containsAlias(ITERABLE_KEY_ALIAS)) { |
| 48 | + generateKey() |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + private fun generateKey() { |
| 53 | + try { |
| 54 | + if (canUseAndroidKeyStore()) { |
| 55 | + generateAndroidKeyStoreKey()?.let { return } |
| 56 | + } |
| 57 | + generateFallbackKey() |
| 58 | + } catch (e: Exception) { |
| 59 | + IterableLogger.e(TAG, "Failed to generate key", e) |
| 60 | + throw e |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private fun canUseAndroidKeyStore(): Boolean { |
| 65 | + return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && |
| 66 | + keyStore.type == ANDROID_KEYSTORE |
| 67 | + } |
| 68 | + |
| 69 | + private fun generateAndroidKeyStoreKey(): Unit? { |
| 70 | + return try { |
| 71 | + val keyGenerator = KeyGenerator.getInstance( |
| 72 | + KeyProperties.KEY_ALGORITHM_AES, |
| 73 | + ANDROID_KEYSTORE |
| 74 | + ) |
| 75 | + |
| 76 | + val keySpec = KeyGenParameterSpec.Builder( |
| 77 | + ITERABLE_KEY_ALIAS, |
| 78 | + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT |
| 79 | + ) |
| 80 | + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) |
| 81 | + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) |
| 82 | + .build() |
| 83 | + |
| 84 | + keyGenerator.init(keySpec) |
| 85 | + keyGenerator.generateKey() |
| 86 | + Unit |
| 87 | + } catch (e: Exception) { |
| 88 | + IterableLogger.e(TAG, "Failed to generate key using AndroidKeyStore", e) |
| 89 | + null |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + private fun generateFallbackKey() { |
| 94 | + val keyGenerator = KeyGenerator.getInstance("AES") |
| 95 | + keyGenerator.init(256) // 256-bit AES key |
| 96 | + val secretKey = keyGenerator.generateKey() |
| 97 | + |
| 98 | + val keyEntry = KeyStore.SecretKeyEntry(secretKey) |
| 99 | + val protParam = if (keyStore.type == "PKCS12") { |
| 100 | + PasswordProtection(TEST_KEYSTORE_PASSWORD) |
| 101 | + } else { |
| 102 | + null |
| 103 | + } |
| 104 | + keyStore.setEntry(ITERABLE_KEY_ALIAS, keyEntry, protParam) |
| 105 | + } |
| 106 | + |
| 107 | + private fun getKey(): SecretKey { |
| 108 | + val protParam = if (keyStore.type == "PKCS12") { |
| 109 | + PasswordProtection(TEST_KEYSTORE_PASSWORD) |
| 110 | + } else { |
| 111 | + null |
| 112 | + } |
| 113 | + return (keyStore.getEntry(ITERABLE_KEY_ALIAS, protParam) as KeyStore.SecretKeyEntry).secretKey |
| 114 | + } |
| 115 | + |
| 116 | + class DecryptionException(message: String, cause: Throwable? = null) : Exception(message, cause) |
| 117 | + |
| 118 | + fun resetKeys() { |
| 119 | + try { |
| 120 | + keyStore.deleteEntry(ITERABLE_KEY_ALIAS) |
| 121 | + generateKey() |
| 122 | + } catch (e: Exception) { |
| 123 | + IterableLogger.e(TAG, "Failed to regenerate key", e) |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + fun encrypt(value: String?): String? { |
| 128 | + if (value == null) return null |
| 129 | + |
| 130 | + try { |
| 131 | + val cipher = Cipher.getInstance(TRANSFORMATION) |
| 132 | + cipher.init(Cipher.ENCRYPT_MODE, getKey()) |
| 133 | + |
| 134 | + val iv = cipher.iv |
| 135 | + val encrypted = cipher.doFinal(value.toByteArray(Charsets.UTF_8)) |
| 136 | + |
| 137 | + // Combine IV and encrypted data |
| 138 | + val combined = ByteArray(iv.size + encrypted.size) |
| 139 | + System.arraycopy(iv, 0, combined, 0, iv.size) |
| 140 | + System.arraycopy(encrypted, 0, combined, iv.size, encrypted.size) |
| 141 | + |
| 142 | + return Base64.encodeToString(combined, Base64.NO_WRAP) |
| 143 | + } catch (e: Exception) { |
| 144 | + IterableLogger.e(TAG, "Encryption failed", e) |
| 145 | + throw e |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + fun decrypt(value: String?): String? { |
| 150 | + if (value == null) return null |
| 151 | + |
| 152 | + try { |
| 153 | + val combined = Base64.decode(value, Base64.NO_WRAP) |
| 154 | + |
| 155 | + // Extract IV |
| 156 | + val iv = combined.copyOfRange(0, GCM_IV_LENGTH) |
| 157 | + val encrypted = combined.copyOfRange(GCM_IV_LENGTH, combined.size) |
| 158 | + |
| 159 | + val cipher = Cipher.getInstance(TRANSFORMATION) |
| 160 | + val spec = GCMParameterSpec(GCM_TAG_LENGTH, iv) |
| 161 | + cipher.init(Cipher.DECRYPT_MODE, getKey(), spec) |
| 162 | + |
| 163 | + return String(cipher.doFinal(encrypted), Charsets.UTF_8) |
| 164 | + } catch (e: Exception) { |
| 165 | + IterableLogger.e(TAG, "Decryption failed", e) |
| 166 | + throw DecryptionException("Failed to decrypt data", e) |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + // Add this method for testing purposes |
| 171 | + @VisibleForTesting |
| 172 | + fun getKeyStore(): KeyStore = keyStore |
| 173 | +} |
0 commit comments