@dynamic-labs/react-native-extension 4.69.0 → 4.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/android/AndroidManifest.xml +1 -0
  2. package/android/KeyStoreKeyManager.kt +148 -0
  3. package/android/KeychainModule.kt +71 -0
  4. package/android/build.gradle +38 -0
  5. package/android/dynamic/keychain/KeyStoreKeyManager.kt +148 -0
  6. package/android/dynamic/keychain/KeychainModule.kt +71 -0
  7. package/android/java/xyz/dynamic/keychain/KeyStoreKeyManager.kt +148 -0
  8. package/android/java/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  9. package/android/keychain/KeyStoreKeyManager.kt +148 -0
  10. package/android/keychain/KeychainModule.kt +71 -0
  11. package/android/main/AndroidManifest.xml +1 -0
  12. package/android/main/java/xyz/dynamic/keychain/KeyStoreKeyManager.kt +148 -0
  13. package/android/main/java/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  14. package/android/src/main/AndroidManifest.xml +1 -0
  15. package/android/src/main/java/xyz/dynamic/keychain/KeyStoreKeyManager.kt +148 -0
  16. package/android/src/main/java/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  17. package/android/xyz/dynamic/keychain/KeyStoreKeyManager.kt +148 -0
  18. package/android/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  19. package/expo-module.config.json +9 -0
  20. package/index.cjs +57 -1
  21. package/index.js +57 -1
  22. package/ios/Keychain.podspec +15 -0
  23. package/ios/KeychainModule.swift +39 -0
  24. package/ios/SecureEnclaveKeyManager.swift +185 -0
  25. package/package.json +8 -7
  26. package/src/ReactNativeExtension/setupKeychainHandler/index.d.ts +1 -0
  27. package/src/ReactNativeExtension/setupKeychainHandler/setupKeychainHandler.d.ts +2 -0
  28. package/src/nativeModules/Keychain.d.ts +16 -0
  29. package/src/nativeModules/index.d.ts +1 -0
@@ -0,0 +1 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,148 @@
1
+ package xyz.dynamic.keychain
2
+
3
+ import android.content.Context
4
+ import android.content.pm.PackageManager
5
+ import android.os.Build
6
+ import android.security.keystore.KeyGenParameterSpec
7
+ import android.security.keystore.KeyProperties
8
+ import android.security.keystore.StrongBoxUnavailableException
9
+ import java.security.KeyPairGenerator
10
+ import java.security.KeyStore
11
+ import java.security.Signature
12
+ import java.security.spec.ECGenParameterSpec
13
+
14
+ /// Platform-agnostic Android KeyStore key manager.
15
+ /// Provides P-256 key generation, signing, and management backed by hardware TEE/StrongBox.
16
+ /// All public keys are returned in uncompressed SEC1 format (65 bytes: 04 || x || y).
17
+ /// All binary data uses base64url encoding (RFC 4648 §5, no padding).
18
+ class KeyStoreKeyManager {
19
+
20
+ fun isAvailable(context: Context?): Boolean {
21
+ return try {
22
+ val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
23
+ keyStore.load(null)
24
+ val hasStrongBox = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && context != null) {
25
+ context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
26
+ } else {
27
+ false
28
+ }
29
+ // Even without StrongBox, Android KeyStore provides TEE-backed keys on most devices
30
+ hasStrongBox || Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
31
+ } catch (e: Exception) {
32
+ false
33
+ }
34
+ }
35
+
36
+ fun hasKey(alias: String): Boolean {
37
+ val keyStore = loadKeyStore()
38
+ return keyStore.containsAlias(alias)
39
+ }
40
+
41
+ fun generateKeyPair(alias: String): String {
42
+ require(!hasKey(alias)) { "Key already exists for alias: $alias" }
43
+
44
+ val specBuilder = KeyGenParameterSpec.Builder(
45
+ alias,
46
+ KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY
47
+ )
48
+ .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
49
+ .setDigests(KeyProperties.DIGEST_SHA256)
50
+
51
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
52
+ specBuilder.setIsStrongBoxBacked(true)
53
+ }
54
+
55
+ val keyPair = try {
56
+ val kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, ANDROID_KEYSTORE)
57
+ kpg.initialize(specBuilder.build())
58
+ kpg.generateKeyPair()
59
+ } catch (e: Exception) {
60
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && e is StrongBoxUnavailableException) {
61
+ // Retry without StrongBox
62
+ specBuilder.setIsStrongBoxBacked(false)
63
+ val kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, ANDROID_KEYSTORE)
64
+ kpg.initialize(specBuilder.build())
65
+ kpg.generateKeyPair()
66
+ } else {
67
+ throw e
68
+ }
69
+ }
70
+
71
+ val publicKeyBytes = extractUncompressedPublicKey(keyPair.public.encoded)
72
+ return base64urlEncode(publicKeyBytes)
73
+ }
74
+
75
+ fun getPublicKey(alias: String): String? {
76
+ val keyStore = loadKeyStore()
77
+ val entry = keyStore.getEntry(alias, null)
78
+
79
+ if (entry == null || entry !is KeyStore.PrivateKeyEntry) {
80
+ return null
81
+ }
82
+
83
+ val publicKeyBytes = extractUncompressedPublicKey(entry.certificate.publicKey.encoded)
84
+ return base64urlEncode(publicKeyBytes)
85
+ }
86
+
87
+ fun sign(alias: String, payload: ByteArray): String {
88
+ val keyStore = loadKeyStore()
89
+ val entry = keyStore.getEntry(alias, null)
90
+
91
+ require(entry != null && entry is KeyStore.PrivateKeyEntry) { "Key not found: $alias" }
92
+
93
+ val signature = Signature.getInstance("SHA256withECDSA")
94
+ signature.initSign(entry.privateKey)
95
+ signature.update(payload)
96
+ val signatureBytes = signature.sign()
97
+
98
+ return base64urlEncode(signatureBytes)
99
+ }
100
+
101
+ fun deleteKey(alias: String) {
102
+ val keyStore = loadKeyStore()
103
+ keyStore.deleteEntry(alias)
104
+ }
105
+
106
+ // region Private helpers
107
+
108
+ private fun loadKeyStore(): KeyStore {
109
+ val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
110
+ keyStore.load(null)
111
+ return keyStore
112
+ }
113
+
114
+ /**
115
+ * Extract uncompressed SEC1 public key (65 bytes: 04 || x || y)
116
+ * from X.509 SubjectPublicKeyInfo DER encoding.
117
+ *
118
+ * For a P-256 key, the SubjectPublicKeyInfo contains the uncompressed
119
+ * point at the end of the DER structure. The point is always 65 bytes.
120
+ */
121
+ private fun extractUncompressedPublicKey(x509Encoded: ByteArray): ByteArray {
122
+ val uncompressedPointLength = 65
123
+ return x509Encoded.copyOfRange(
124
+ x509Encoded.size - uncompressedPointLength,
125
+ x509Encoded.size
126
+ )
127
+ }
128
+
129
+ private fun base64urlEncode(data: ByteArray): String {
130
+ return android.util.Base64.encodeToString(
131
+ data,
132
+ android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING
133
+ )
134
+ }
135
+
136
+ companion object {
137
+ private const val ANDROID_KEYSTORE = "AndroidKeyStore"
138
+
139
+ fun base64urlDecode(input: String): ByteArray {
140
+ return android.util.Base64.decode(
141
+ input,
142
+ android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING
143
+ )
144
+ }
145
+ }
146
+
147
+ // endregion
148
+ }
@@ -0,0 +1,71 @@
1
+ package xyz.dynamic.keychain
2
+
3
+ import expo.modules.kotlin.modules.Module
4
+ import expo.modules.kotlin.modules.ModuleDefinition
5
+ import expo.modules.kotlin.Promise
6
+
7
+ class KeychainModule : Module() {
8
+ private val keyManager = KeyStoreKeyManager()
9
+
10
+ override fun definition() = ModuleDefinition { // NOSONAR (cognitive complexity — inherent to Expo module DSL pattern)
11
+ Name("Keychain")
12
+
13
+ AsyncFunction("isAvailable") { promise: Promise ->
14
+ try {
15
+ val context = appContext.reactContext
16
+ promise.resolve(keyManager.isAvailable(context))
17
+ } catch (e: Exception) {
18
+ promise.resolve(false)
19
+ }
20
+ }
21
+
22
+ AsyncFunction("hasKey") { key: String, promise: Promise ->
23
+ try {
24
+ promise.resolve(keyManager.hasKey(key))
25
+ } catch (e: Exception) {
26
+ promise.reject("ERR_KEYCHAIN", "Failed to check key: ${e.message}", e)
27
+ }
28
+ }
29
+
30
+ AsyncFunction("generateKeyPair") { key: String, promise: Promise ->
31
+ try {
32
+ val publicKey = keyManager.generateKeyPair(key)
33
+ promise.resolve(mapOf("publicKey" to publicKey))
34
+ } catch (e: Exception) {
35
+ promise.reject("ERR_KEYCHAIN", "Failed to generate key pair: ${e.message}", e)
36
+ }
37
+ }
38
+
39
+ AsyncFunction("getPublicKey") { key: String, promise: Promise ->
40
+ try {
41
+ val publicKey = keyManager.getPublicKey(key)
42
+ if (publicKey == null) {
43
+ promise.resolve(null)
44
+ } else {
45
+ promise.resolve(mapOf("publicKey" to publicKey))
46
+ }
47
+ } catch (e: Exception) {
48
+ promise.reject("ERR_KEYCHAIN", "Failed to get public key: ${e.message}", e)
49
+ }
50
+ }
51
+
52
+ AsyncFunction("sign") { key: String, payload: String, promise: Promise ->
53
+ try {
54
+ val payloadData = KeyStoreKeyManager.base64urlDecode(payload)
55
+ val signature = keyManager.sign(key, payloadData)
56
+ promise.resolve(mapOf("signature" to signature))
57
+ } catch (e: Exception) {
58
+ promise.reject("ERR_KEYCHAIN", "Failed to sign: ${e.message}", e)
59
+ }
60
+ }
61
+
62
+ AsyncFunction("deleteKey") { key: String, promise: Promise ->
63
+ try {
64
+ keyManager.deleteKey(key)
65
+ promise.resolve(null)
66
+ } catch (e: Exception) {
67
+ promise.reject("ERR_KEYCHAIN", "Failed to delete key: ${e.message}", e)
68
+ }
69
+ }
70
+ }
71
+ }
@@ -0,0 +1,38 @@
1
+ apply plugin: 'com.android.library'
2
+ apply plugin: 'kotlin-android'
3
+ apply plugin: 'expo-module-gradle-plugin'
4
+
5
+ def packageJsonFile = file('../package.json')
6
+ def packageJson = new groovy.json.JsonSlurper().parseText(packageJsonFile.text)
7
+
8
+ group = 'xyz.dynamic.keychain'
9
+ version = packageJson.version
10
+
11
+ android {
12
+ namespace 'xyz.dynamic.keychain'
13
+ compileSdkVersion safeExtGet("compileSdkVersion", 34)
14
+
15
+ defaultConfig {
16
+ minSdkVersion safeExtGet("minSdkVersion", 23)
17
+ targetSdkVersion safeExtGet("targetSdkVersion", 34)
18
+ versionCode 1
19
+ versionName packageJson.version
20
+ }
21
+
22
+ compileOptions {
23
+ sourceCompatibility JavaVersion.VERSION_17
24
+ targetCompatibility JavaVersion.VERSION_17
25
+ }
26
+
27
+ kotlinOptions {
28
+ jvmTarget = '17'
29
+ }
30
+ }
31
+
32
+ dependencies {
33
+ implementation project(':expo-modules-core')
34
+ }
35
+
36
+ def safeExtGet(prop, fallback) {
37
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
38
+ }
@@ -0,0 +1,148 @@
1
+ package xyz.dynamic.keychain
2
+
3
+ import android.content.Context
4
+ import android.content.pm.PackageManager
5
+ import android.os.Build
6
+ import android.security.keystore.KeyGenParameterSpec
7
+ import android.security.keystore.KeyProperties
8
+ import android.security.keystore.StrongBoxUnavailableException
9
+ import java.security.KeyPairGenerator
10
+ import java.security.KeyStore
11
+ import java.security.Signature
12
+ import java.security.spec.ECGenParameterSpec
13
+
14
+ /// Platform-agnostic Android KeyStore key manager.
15
+ /// Provides P-256 key generation, signing, and management backed by hardware TEE/StrongBox.
16
+ /// All public keys are returned in uncompressed SEC1 format (65 bytes: 04 || x || y).
17
+ /// All binary data uses base64url encoding (RFC 4648 §5, no padding).
18
+ class KeyStoreKeyManager {
19
+
20
+ fun isAvailable(context: Context?): Boolean {
21
+ return try {
22
+ val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
23
+ keyStore.load(null)
24
+ val hasStrongBox = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && context != null) {
25
+ context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
26
+ } else {
27
+ false
28
+ }
29
+ // Even without StrongBox, Android KeyStore provides TEE-backed keys on most devices
30
+ hasStrongBox || Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
31
+ } catch (e: Exception) {
32
+ false
33
+ }
34
+ }
35
+
36
+ fun hasKey(alias: String): Boolean {
37
+ val keyStore = loadKeyStore()
38
+ return keyStore.containsAlias(alias)
39
+ }
40
+
41
+ fun generateKeyPair(alias: String): String {
42
+ require(!hasKey(alias)) { "Key already exists for alias: $alias" }
43
+
44
+ val specBuilder = KeyGenParameterSpec.Builder(
45
+ alias,
46
+ KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY
47
+ )
48
+ .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
49
+ .setDigests(KeyProperties.DIGEST_SHA256)
50
+
51
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
52
+ specBuilder.setIsStrongBoxBacked(true)
53
+ }
54
+
55
+ val keyPair = try {
56
+ val kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, ANDROID_KEYSTORE)
57
+ kpg.initialize(specBuilder.build())
58
+ kpg.generateKeyPair()
59
+ } catch (e: Exception) {
60
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && e is StrongBoxUnavailableException) {
61
+ // Retry without StrongBox
62
+ specBuilder.setIsStrongBoxBacked(false)
63
+ val kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, ANDROID_KEYSTORE)
64
+ kpg.initialize(specBuilder.build())
65
+ kpg.generateKeyPair()
66
+ } else {
67
+ throw e
68
+ }
69
+ }
70
+
71
+ val publicKeyBytes = extractUncompressedPublicKey(keyPair.public.encoded)
72
+ return base64urlEncode(publicKeyBytes)
73
+ }
74
+
75
+ fun getPublicKey(alias: String): String? {
76
+ val keyStore = loadKeyStore()
77
+ val entry = keyStore.getEntry(alias, null)
78
+
79
+ if (entry == null || entry !is KeyStore.PrivateKeyEntry) {
80
+ return null
81
+ }
82
+
83
+ val publicKeyBytes = extractUncompressedPublicKey(entry.certificate.publicKey.encoded)
84
+ return base64urlEncode(publicKeyBytes)
85
+ }
86
+
87
+ fun sign(alias: String, payload: ByteArray): String {
88
+ val keyStore = loadKeyStore()
89
+ val entry = keyStore.getEntry(alias, null)
90
+
91
+ require(entry != null && entry is KeyStore.PrivateKeyEntry) { "Key not found: $alias" }
92
+
93
+ val signature = Signature.getInstance("SHA256withECDSA")
94
+ signature.initSign(entry.privateKey)
95
+ signature.update(payload)
96
+ val signatureBytes = signature.sign()
97
+
98
+ return base64urlEncode(signatureBytes)
99
+ }
100
+
101
+ fun deleteKey(alias: String) {
102
+ val keyStore = loadKeyStore()
103
+ keyStore.deleteEntry(alias)
104
+ }
105
+
106
+ // region Private helpers
107
+
108
+ private fun loadKeyStore(): KeyStore {
109
+ val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
110
+ keyStore.load(null)
111
+ return keyStore
112
+ }
113
+
114
+ /**
115
+ * Extract uncompressed SEC1 public key (65 bytes: 04 || x || y)
116
+ * from X.509 SubjectPublicKeyInfo DER encoding.
117
+ *
118
+ * For a P-256 key, the SubjectPublicKeyInfo contains the uncompressed
119
+ * point at the end of the DER structure. The point is always 65 bytes.
120
+ */
121
+ private fun extractUncompressedPublicKey(x509Encoded: ByteArray): ByteArray {
122
+ val uncompressedPointLength = 65
123
+ return x509Encoded.copyOfRange(
124
+ x509Encoded.size - uncompressedPointLength,
125
+ x509Encoded.size
126
+ )
127
+ }
128
+
129
+ private fun base64urlEncode(data: ByteArray): String {
130
+ return android.util.Base64.encodeToString(
131
+ data,
132
+ android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING
133
+ )
134
+ }
135
+
136
+ companion object {
137
+ private const val ANDROID_KEYSTORE = "AndroidKeyStore"
138
+
139
+ fun base64urlDecode(input: String): ByteArray {
140
+ return android.util.Base64.decode(
141
+ input,
142
+ android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING
143
+ )
144
+ }
145
+ }
146
+
147
+ // endregion
148
+ }
@@ -0,0 +1,71 @@
1
+ package xyz.dynamic.keychain
2
+
3
+ import expo.modules.kotlin.modules.Module
4
+ import expo.modules.kotlin.modules.ModuleDefinition
5
+ import expo.modules.kotlin.Promise
6
+
7
+ class KeychainModule : Module() {
8
+ private val keyManager = KeyStoreKeyManager()
9
+
10
+ override fun definition() = ModuleDefinition { // NOSONAR (cognitive complexity — inherent to Expo module DSL pattern)
11
+ Name("Keychain")
12
+
13
+ AsyncFunction("isAvailable") { promise: Promise ->
14
+ try {
15
+ val context = appContext.reactContext
16
+ promise.resolve(keyManager.isAvailable(context))
17
+ } catch (e: Exception) {
18
+ promise.resolve(false)
19
+ }
20
+ }
21
+
22
+ AsyncFunction("hasKey") { key: String, promise: Promise ->
23
+ try {
24
+ promise.resolve(keyManager.hasKey(key))
25
+ } catch (e: Exception) {
26
+ promise.reject("ERR_KEYCHAIN", "Failed to check key: ${e.message}", e)
27
+ }
28
+ }
29
+
30
+ AsyncFunction("generateKeyPair") { key: String, promise: Promise ->
31
+ try {
32
+ val publicKey = keyManager.generateKeyPair(key)
33
+ promise.resolve(mapOf("publicKey" to publicKey))
34
+ } catch (e: Exception) {
35
+ promise.reject("ERR_KEYCHAIN", "Failed to generate key pair: ${e.message}", e)
36
+ }
37
+ }
38
+
39
+ AsyncFunction("getPublicKey") { key: String, promise: Promise ->
40
+ try {
41
+ val publicKey = keyManager.getPublicKey(key)
42
+ if (publicKey == null) {
43
+ promise.resolve(null)
44
+ } else {
45
+ promise.resolve(mapOf("publicKey" to publicKey))
46
+ }
47
+ } catch (e: Exception) {
48
+ promise.reject("ERR_KEYCHAIN", "Failed to get public key: ${e.message}", e)
49
+ }
50
+ }
51
+
52
+ AsyncFunction("sign") { key: String, payload: String, promise: Promise ->
53
+ try {
54
+ val payloadData = KeyStoreKeyManager.base64urlDecode(payload)
55
+ val signature = keyManager.sign(key, payloadData)
56
+ promise.resolve(mapOf("signature" to signature))
57
+ } catch (e: Exception) {
58
+ promise.reject("ERR_KEYCHAIN", "Failed to sign: ${e.message}", e)
59
+ }
60
+ }
61
+
62
+ AsyncFunction("deleteKey") { key: String, promise: Promise ->
63
+ try {
64
+ keyManager.deleteKey(key)
65
+ promise.resolve(null)
66
+ } catch (e: Exception) {
67
+ promise.reject("ERR_KEYCHAIN", "Failed to delete key: ${e.message}", e)
68
+ }
69
+ }
70
+ }
71
+ }
@@ -0,0 +1,148 @@
1
+ package xyz.dynamic.keychain
2
+
3
+ import android.content.Context
4
+ import android.content.pm.PackageManager
5
+ import android.os.Build
6
+ import android.security.keystore.KeyGenParameterSpec
7
+ import android.security.keystore.KeyProperties
8
+ import android.security.keystore.StrongBoxUnavailableException
9
+ import java.security.KeyPairGenerator
10
+ import java.security.KeyStore
11
+ import java.security.Signature
12
+ import java.security.spec.ECGenParameterSpec
13
+
14
+ /// Platform-agnostic Android KeyStore key manager.
15
+ /// Provides P-256 key generation, signing, and management backed by hardware TEE/StrongBox.
16
+ /// All public keys are returned in uncompressed SEC1 format (65 bytes: 04 || x || y).
17
+ /// All binary data uses base64url encoding (RFC 4648 §5, no padding).
18
+ class KeyStoreKeyManager {
19
+
20
+ fun isAvailable(context: Context?): Boolean {
21
+ return try {
22
+ val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
23
+ keyStore.load(null)
24
+ val hasStrongBox = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && context != null) {
25
+ context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
26
+ } else {
27
+ false
28
+ }
29
+ // Even without StrongBox, Android KeyStore provides TEE-backed keys on most devices
30
+ hasStrongBox || Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
31
+ } catch (e: Exception) {
32
+ false
33
+ }
34
+ }
35
+
36
+ fun hasKey(alias: String): Boolean {
37
+ val keyStore = loadKeyStore()
38
+ return keyStore.containsAlias(alias)
39
+ }
40
+
41
+ fun generateKeyPair(alias: String): String {
42
+ require(!hasKey(alias)) { "Key already exists for alias: $alias" }
43
+
44
+ val specBuilder = KeyGenParameterSpec.Builder(
45
+ alias,
46
+ KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY
47
+ )
48
+ .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
49
+ .setDigests(KeyProperties.DIGEST_SHA256)
50
+
51
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
52
+ specBuilder.setIsStrongBoxBacked(true)
53
+ }
54
+
55
+ val keyPair = try {
56
+ val kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, ANDROID_KEYSTORE)
57
+ kpg.initialize(specBuilder.build())
58
+ kpg.generateKeyPair()
59
+ } catch (e: Exception) {
60
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && e is StrongBoxUnavailableException) {
61
+ // Retry without StrongBox
62
+ specBuilder.setIsStrongBoxBacked(false)
63
+ val kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, ANDROID_KEYSTORE)
64
+ kpg.initialize(specBuilder.build())
65
+ kpg.generateKeyPair()
66
+ } else {
67
+ throw e
68
+ }
69
+ }
70
+
71
+ val publicKeyBytes = extractUncompressedPublicKey(keyPair.public.encoded)
72
+ return base64urlEncode(publicKeyBytes)
73
+ }
74
+
75
+ fun getPublicKey(alias: String): String? {
76
+ val keyStore = loadKeyStore()
77
+ val entry = keyStore.getEntry(alias, null)
78
+
79
+ if (entry == null || entry !is KeyStore.PrivateKeyEntry) {
80
+ return null
81
+ }
82
+
83
+ val publicKeyBytes = extractUncompressedPublicKey(entry.certificate.publicKey.encoded)
84
+ return base64urlEncode(publicKeyBytes)
85
+ }
86
+
87
+ fun sign(alias: String, payload: ByteArray): String {
88
+ val keyStore = loadKeyStore()
89
+ val entry = keyStore.getEntry(alias, null)
90
+
91
+ require(entry != null && entry is KeyStore.PrivateKeyEntry) { "Key not found: $alias" }
92
+
93
+ val signature = Signature.getInstance("SHA256withECDSA")
94
+ signature.initSign(entry.privateKey)
95
+ signature.update(payload)
96
+ val signatureBytes = signature.sign()
97
+
98
+ return base64urlEncode(signatureBytes)
99
+ }
100
+
101
+ fun deleteKey(alias: String) {
102
+ val keyStore = loadKeyStore()
103
+ keyStore.deleteEntry(alias)
104
+ }
105
+
106
+ // region Private helpers
107
+
108
+ private fun loadKeyStore(): KeyStore {
109
+ val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE)
110
+ keyStore.load(null)
111
+ return keyStore
112
+ }
113
+
114
+ /**
115
+ * Extract uncompressed SEC1 public key (65 bytes: 04 || x || y)
116
+ * from X.509 SubjectPublicKeyInfo DER encoding.
117
+ *
118
+ * For a P-256 key, the SubjectPublicKeyInfo contains the uncompressed
119
+ * point at the end of the DER structure. The point is always 65 bytes.
120
+ */
121
+ private fun extractUncompressedPublicKey(x509Encoded: ByteArray): ByteArray {
122
+ val uncompressedPointLength = 65
123
+ return x509Encoded.copyOfRange(
124
+ x509Encoded.size - uncompressedPointLength,
125
+ x509Encoded.size
126
+ )
127
+ }
128
+
129
+ private fun base64urlEncode(data: ByteArray): String {
130
+ return android.util.Base64.encodeToString(
131
+ data,
132
+ android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING
133
+ )
134
+ }
135
+
136
+ companion object {
137
+ private const val ANDROID_KEYSTORE = "AndroidKeyStore"
138
+
139
+ fun base64urlDecode(input: String): ByteArray {
140
+ return android.util.Base64.decode(
141
+ input,
142
+ android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING
143
+ )
144
+ }
145
+ }
146
+
147
+ // endregion
148
+ }
@@ -0,0 +1,71 @@
1
+ package xyz.dynamic.keychain
2
+
3
+ import expo.modules.kotlin.modules.Module
4
+ import expo.modules.kotlin.modules.ModuleDefinition
5
+ import expo.modules.kotlin.Promise
6
+
7
+ class KeychainModule : Module() {
8
+ private val keyManager = KeyStoreKeyManager()
9
+
10
+ override fun definition() = ModuleDefinition { // NOSONAR (cognitive complexity — inherent to Expo module DSL pattern)
11
+ Name("Keychain")
12
+
13
+ AsyncFunction("isAvailable") { promise: Promise ->
14
+ try {
15
+ val context = appContext.reactContext
16
+ promise.resolve(keyManager.isAvailable(context))
17
+ } catch (e: Exception) {
18
+ promise.resolve(false)
19
+ }
20
+ }
21
+
22
+ AsyncFunction("hasKey") { key: String, promise: Promise ->
23
+ try {
24
+ promise.resolve(keyManager.hasKey(key))
25
+ } catch (e: Exception) {
26
+ promise.reject("ERR_KEYCHAIN", "Failed to check key: ${e.message}", e)
27
+ }
28
+ }
29
+
30
+ AsyncFunction("generateKeyPair") { key: String, promise: Promise ->
31
+ try {
32
+ val publicKey = keyManager.generateKeyPair(key)
33
+ promise.resolve(mapOf("publicKey" to publicKey))
34
+ } catch (e: Exception) {
35
+ promise.reject("ERR_KEYCHAIN", "Failed to generate key pair: ${e.message}", e)
36
+ }
37
+ }
38
+
39
+ AsyncFunction("getPublicKey") { key: String, promise: Promise ->
40
+ try {
41
+ val publicKey = keyManager.getPublicKey(key)
42
+ if (publicKey == null) {
43
+ promise.resolve(null)
44
+ } else {
45
+ promise.resolve(mapOf("publicKey" to publicKey))
46
+ }
47
+ } catch (e: Exception) {
48
+ promise.reject("ERR_KEYCHAIN", "Failed to get public key: ${e.message}", e)
49
+ }
50
+ }
51
+
52
+ AsyncFunction("sign") { key: String, payload: String, promise: Promise ->
53
+ try {
54
+ val payloadData = KeyStoreKeyManager.base64urlDecode(payload)
55
+ val signature = keyManager.sign(key, payloadData)
56
+ promise.resolve(mapOf("signature" to signature))
57
+ } catch (e: Exception) {
58
+ promise.reject("ERR_KEYCHAIN", "Failed to sign: ${e.message}", e)
59
+ }
60
+ }
61
+
62
+ AsyncFunction("deleteKey") { key: String, promise: Promise ->
63
+ try {
64
+ keyManager.deleteKey(key)
65
+ promise.resolve(null)
66
+ } catch (e: Exception) {
67
+ promise.reject("ERR_KEYCHAIN", "Failed to delete key: ${e.message}", e)
68
+ }
69
+ }
70
+ }
71
+ }