|
| 1 | +package com.plugin.flutter.cryptography.key_store |
| 2 | + |
| 3 | +import android.annotation.TargetApi |
| 4 | +import android.content.Context |
| 5 | +import android.os.Build |
| 6 | +import android.security.KeyPairGeneratorSpec |
| 7 | +import android.security.keystore.KeyGenParameterSpec |
| 8 | +import android.security.keystore.KeyProperties |
| 9 | +import android.security.keystore.StrongBoxUnavailableException |
| 10 | +import java.math.BigInteger |
| 11 | +import java.security.* |
| 12 | +import java.security.spec.AlgorithmParameterSpec |
| 13 | +import java.util.* |
| 14 | +import javax.crypto.Cipher |
| 15 | +import javax.security.auth.x500.X500Principal |
| 16 | + |
| 17 | +class KeyStoreImplementation(context: Context) { |
| 18 | + private val KEY_ALIAS: String |
| 19 | + private val KEYSTORE_PROVIDER_ANDROID = "AndroidKeyStore" |
| 20 | + private val TYPE_RSA = "RSA" |
| 21 | + private val start = Calendar.getInstance() |
| 22 | + private val end = Calendar.getInstance() |
| 23 | + |
| 24 | + init { |
| 25 | + end.add(Calendar.MONTH, 3) // TODO decide on validity |
| 26 | + KEY_ALIAS = "get_package" + "com.plugin.flutter.cryptography.key_store" |
| 27 | + createKeysIfNotExists(context) |
| 28 | + } |
| 29 | + |
| 30 | + private fun createKeysIfNotExists(context: Context) { |
| 31 | + val keyStore: KeyStore = KeyStore.getInstance(KEYSTORE_PROVIDER_ANDROID) |
| 32 | + keyStore.load(null) |
| 33 | + val privateKey = keyStore.getKey(KEY_ALIAS, null) |
| 34 | + // if the keys are not present in keystore then create a new pair |
| 35 | + if (privateKey == null) |
| 36 | + createKeys(context) |
| 37 | + } |
| 38 | + |
| 39 | + private fun createKeys(context: Context) { |
| 40 | + val keyPairGenerator = KeyPairGenerator.getInstance(TYPE_RSA, KEYSTORE_PROVIDER_ANDROID) |
| 41 | + val algorithmParameterSpec: AlgorithmParameterSpec = getAlgorithmSpec(context) |
| 42 | + |
| 43 | + try { |
| 44 | + initializeKeyPair(keyPairGenerator, algorithmParameterSpec) |
| 45 | + } catch (exception: Exception) { |
| 46 | + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && exception is StrongBoxUnavailableException) |
| 47 | + generateKeysForAndroidPWithoutStrongBox(keyPairGenerator) |
| 48 | + else |
| 49 | + throw Exception(ExceptionMessage.CANNOT_CREATE_KEY) |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + @TargetApi(Build.VERSION_CODES.P) |
| 54 | + private fun generateKeysForAndroidPWithoutStrongBox(keyPairGenerator: KeyPairGenerator) { |
| 55 | + try { |
| 56 | + val algorithmParameterSpecWithoutStrongBox = keyPairBuilder().build() |
| 57 | + initializeKeyPair(keyPairGenerator, algorithmParameterSpecWithoutStrongBox) |
| 58 | + } catch (exception: Exception) { |
| 59 | + throw Exception(ExceptionMessage.CANNOT_CREATE_KEY_WITH_STRONGBOX) |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + private fun initializeKeyPair(keyPairGenerator: KeyPairGenerator, algorithmParameterSpec: AlgorithmParameterSpec) { |
| 64 | + keyPairGenerator.initialize(algorithmParameterSpec) |
| 65 | + keyPairGenerator.generateKeyPair() |
| 66 | + } |
| 67 | + |
| 68 | + @TargetApi(Build.VERSION_CODES.P) |
| 69 | + private fun keyPairBuilder(): KeyGenParameterSpec.Builder { |
| 70 | + |
| 71 | + return KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_DECRYPT or KeyProperties.PURPOSE_ENCRYPT) |
| 72 | + .setCertificateSubject(X500Principal("CN=$KEY_ALIAS")) |
| 73 | + .setDigests(KeyProperties.DIGEST_SHA256) |
| 74 | + .setBlockModes(KeyProperties.BLOCK_MODE_ECB) |
| 75 | + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1) |
| 76 | + .setCertificateSerialNumber(BigInteger.valueOf(1)) |
| 77 | + .setCertificateNotBefore(start.time) |
| 78 | + .setCertificateNotAfter(end.time) |
| 79 | + } |
| 80 | + |
| 81 | + @TargetApi(Build.VERSION_CODES.M) |
| 82 | + private fun keyPairBuilderDeprecated(context: Context): KeyPairGeneratorSpec.Builder { |
| 83 | + return KeyPairGeneratorSpec.Builder(context) |
| 84 | + .setAlias(KEY_ALIAS) |
| 85 | + .setSubject(X500Principal("CN=$KEY_ALIAS")) |
| 86 | + .setSerialNumber(BigInteger.valueOf(1)) |
| 87 | + .setStartDate(start.time) |
| 88 | + .setEndDate(end.time) |
| 89 | + } |
| 90 | + |
| 91 | + private fun getAlgorithmSpec(context: Context): AlgorithmParameterSpec { |
| 92 | + val algorithmParameterSpec: AlgorithmParameterSpec |
| 93 | + if (isAndroidBelowM()) { |
| 94 | + algorithmParameterSpec = keyPairBuilderDeprecated(context).build() |
| 95 | + } else { |
| 96 | + val keyPairSpecBuilder = keyPairBuilder() |
| 97 | + setStrongBox(keyPairSpecBuilder) |
| 98 | + algorithmParameterSpec = keyPairSpecBuilder.build() |
| 99 | + } |
| 100 | + |
| 101 | + return algorithmParameterSpec |
| 102 | + } |
| 103 | + private fun setStrongBox(keyPairSpecBuilder: KeyGenParameterSpec.Builder) { |
| 104 | + if (isAndroidIsGreaterThanEqualP()) { |
| 105 | + keyPairSpecBuilder.setIsStrongBoxBacked(true) |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + private fun isAndroidBelowM(): Boolean { |
| 110 | + return Build.VERSION.SDK_INT < Build.VERSION_CODES.M |
| 111 | + } |
| 112 | + |
| 113 | + private fun isAndroidIsGreaterThanEqualP(): Boolean { |
| 114 | + return Build.VERSION.SDK_INT >= Build.VERSION_CODES.P |
| 115 | + } |
| 116 | + |
| 117 | + private fun getPrivateKey(): PrivateKey { |
| 118 | + val keyStore = KeyStore.getInstance(KEYSTORE_PROVIDER_ANDROID) |
| 119 | + keyStore.load(null) |
| 120 | + val key: Key = keyStore.getKey(KEY_ALIAS, null) ?: throw Exception(ExceptionMessage.KEY_NOT_FOUND) |
| 121 | + if (key !is PrivateKey) { |
| 122 | + throw Exception(ExceptionMessage.NOT_PRIVATE_KEY) |
| 123 | + } |
| 124 | + return key |
| 125 | + } |
| 126 | + |
| 127 | + fun getPublicKey(): PublicKey { |
| 128 | + val keyStore = KeyStore.getInstance(KEYSTORE_PROVIDER_ANDROID) |
| 129 | + keyStore.load(null) |
| 130 | + |
| 131 | + val certificate = keyStore.getCertificate(KEY_ALIAS) ?: throw Exception(ExceptionMessage.CERTIFICATE_NOT_FOUND) |
| 132 | + val publicKey: PublicKey |
| 133 | + publicKey = certificate.getPublicKey() |
| 134 | + return publicKey |
| 135 | + } |
| 136 | + |
| 137 | + fun wrap(key: Key): ByteArray { |
| 138 | + val publicKey: PublicKey = getPublicKey() |
| 139 | + val cipher = getRSACipher() |
| 140 | + cipher.init(Cipher.WRAP_MODE, publicKey) |
| 141 | + return cipher.wrap(key) |
| 142 | + } |
| 143 | + |
| 144 | + fun unwrap(wrappedKey: ByteArray, algorithm: String): Key { |
| 145 | + val privateKey = getPrivateKey() |
| 146 | + val cipher = getRSACipher() |
| 147 | + cipher.init(Cipher.UNWRAP_MODE, privateKey) |
| 148 | + return cipher.unwrap(wrappedKey, algorithm, Cipher.SECRET_KEY) |
| 149 | + } |
| 150 | + // todo with app pin creation |
| 151 | + fun encrypt(input: String): ByteArray { |
| 152 | + val byteArrayInput = input.toByteArray() |
| 153 | + val publicKey = getPublicKey() |
| 154 | + val cipher = getRSACipher() |
| 155 | + cipher.init(Cipher.ENCRYPT_MODE, publicKey) |
| 156 | + return cipher.doFinal(byteArrayInput) |
| 157 | + } |
| 158 | + |
| 159 | + @Throws(Exception::class) |
| 160 | + private fun getRSACipher(): Cipher { |
| 161 | + return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { |
| 162 | + // error in android 6: InvalidKeyException: Need RSA private or public key |
| 163 | + Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL") |
| 164 | + } else { |
| 165 | + // error in android 5: NoSuchProviderException: Provider not available: AndroidKeyStoreBCWorkaround |
| 166 | + Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidKeyStoreBCWorkaround") |
| 167 | + } |
| 168 | + } |
| 169 | +} |
0 commit comments