-
Notifications
You must be signed in to change notification settings - Fork 0
feat: DataStore 모듈 설계 및 암호화 기능 구현 #17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
b8d9373
[BOOK-63] chore: core:datastore 모듈 추가
seoyoon513 18809aa
[BOOK-63] feat: DataStoreModule 구성
seoyoon513 50b112a
[BOOK-63] feat: KeyStore 기반 CryptoManager 구현
seoyoon513 d42a05d
[BOOK-63] feat: TokenPreferencesDataSource 구현
seoyoon513 dcf68db
[BOOK-63] test: TokenPreferencesDataSource 암호화/복호화 테스트 추가
seoyoon513 4c5a480
[BOOK-63] chore: settings.gradle include 블록 내 위치 수정
seoyoon513 17fa0c7
[BOOK-63] refactor: 토큰 복호화 공통 함수 분리 및 IOException 핸들링 유틸 추가
seoyoon513 d594c07
[BOOK-63] chore: code style check success
seoyoon513 23aab2a
[BOOK-63] chore: rename androidx-datastore to androidx-datastore-pref…
seoyoon513 525ac23
[BOOK-63] chore: rename TokenPreferencesDataSourceImpl to DefaultToke…
seoyoon513 006346d
[BOOK-63] refactor: AES 복호화 시 IV 크기를 고정값(16바이트)으로 수정
seoyoon513 1619f14
[BOOK-63] refactor: 불필요한 @Named("token") 제거
seoyoon513 376c45c
Merge branch 'develop' into BOOK-63-feature/#15
seoyoon513 22c4e8a
[BOOK-63] chore: code style check success
seoyoon513 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| /build |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| @file:Suppress("INLINE_FROM_HIGHER_PLATFORM") | ||
|
|
||
| plugins { | ||
| alias(libs.plugins.booket.android.library) | ||
| alias(libs.plugins.booket.android.hilt) | ||
| } | ||
|
|
||
| android { | ||
| namespace = "com.ninecraft.booket.core.datastore" | ||
|
|
||
| defaultConfig { | ||
| testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" | ||
| } | ||
| } | ||
|
|
||
| dependencies { | ||
| implementations( | ||
| libs.androidx.datastore.preferences, | ||
|
|
||
| libs.logger, | ||
| ) | ||
|
|
||
| androidTestImplementations( | ||
| libs.androidx.test.ext.junit, | ||
| libs.androidx.test.runner, | ||
| libs.kotlinx.coroutines.test, | ||
| ) | ||
| } |
80 changes: 80 additions & 0 deletions
80
...c/androidTest/kotlin/com/ninecraft/booket/core/datastore/TokenPreferenceDataSourceTest.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| package com.ninecraft.booket.core.datastore | ||
|
|
||
| import androidx.datastore.core.DataStore | ||
| import androidx.datastore.preferences.core.PreferenceDataStoreFactory | ||
| import androidx.datastore.preferences.core.Preferences | ||
| import androidx.datastore.preferences.core.stringPreferencesKey | ||
| import androidx.test.ext.junit.runners.AndroidJUnit4 | ||
| import com.ninecraft.booket.core.datastore.datasource.DefaultTokenPreferencesDataSource | ||
| import com.ninecraft.booket.core.datastore.security.CryptoManager | ||
| import kotlinx.coroutines.CoroutineScope | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.SupervisorJob | ||
| import kotlinx.coroutines.flow.first | ||
| import kotlinx.coroutines.test.runTest | ||
| import org.junit.After | ||
| import org.junit.Assert.assertEquals | ||
| import org.junit.Assert.assertNotEquals | ||
| import org.junit.Assert.assertNotNull | ||
| import org.junit.Assert.assertTrue | ||
| import org.junit.Before | ||
| import org.junit.Test | ||
| import org.junit.runner.RunWith | ||
| import java.io.File | ||
| import kotlin.io.path.createTempDirectory | ||
|
|
||
| @RunWith(AndroidJUnit4::class) | ||
| class TokenPreferenceDataSourceTest { | ||
| private lateinit var dataStore: DataStore<Preferences> | ||
| private lateinit var dataSource: DefaultTokenPreferencesDataSource | ||
| private lateinit var cryptoManager: CryptoManager | ||
| private lateinit var tempFile: File | ||
|
|
||
| @Before | ||
| fun setup() { | ||
| val tempFolder = createTempDirectory().toFile() | ||
| tempFile = File(tempFolder, "token_prefs.preferences_pb") | ||
|
|
||
| dataStore = PreferenceDataStoreFactory.create( | ||
| scope = CoroutineScope(Dispatchers.IO + SupervisorJob()), | ||
| produceFile = { tempFile } | ||
| ) | ||
|
|
||
| cryptoManager = CryptoManager() | ||
| dataSource = DefaultTokenPreferencesDataSource(dataStore, cryptoManager) | ||
| } | ||
|
|
||
| @After | ||
| fun tearDown() { | ||
| tempFile.delete() | ||
| } | ||
|
|
||
| @Test | ||
| fun tokenIsEncryptedWhenStored() = runTest { | ||
| // Given | ||
| val plainToken = "plain_access_token" | ||
| dataSource.setAccessToken(plainToken) | ||
|
|
||
| // When | ||
| val storedToken = dataStore.data.first()[stringPreferencesKey("ACCESS_TOKEN")] | ||
|
|
||
| // Then | ||
| assertNotNull(storedToken) | ||
| assertNotEquals(plainToken, storedToken) | ||
| assertTrue(storedToken!!.isNotEmpty()) | ||
| } | ||
|
|
||
|
|
||
| @Test | ||
| fun storedTokenIsDecryptedWhenRetrieved() = runTest { | ||
| // Given | ||
| val plainToken = "plain_access_token" | ||
| dataSource.setAccessToken(plainToken) | ||
|
|
||
| // When | ||
| val restoredToken = dataSource.accessToken.first() | ||
|
|
||
| // Then | ||
| assertEquals(plainToken, restoredToken) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| <?xml version="1.0" encoding="utf-8"?> | ||
| <manifest xmlns:android="http://schemas.android.com/apk/res/android"> | ||
|
|
||
| </manifest> |
60 changes: 60 additions & 0 deletions
60
...otlin/com/ninecraft/booket/core/datastore/datasource/DefaultTokenPreferencesDataSource.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| package com.ninecraft.booket.core.datastore.datasource | ||
|
|
||
| import androidx.datastore.core.DataStore | ||
| import androidx.datastore.preferences.core.Preferences | ||
| import androidx.datastore.preferences.core.edit | ||
| import androidx.datastore.preferences.core.stringPreferencesKey | ||
| import com.ninecraft.booket.core.datastore.security.CryptoManager | ||
| import com.ninecraft.booket.core.datastore.util.handleIOException | ||
| import com.orhanobut.logger.Logger | ||
| import kotlinx.coroutines.flow.Flow | ||
| import kotlinx.coroutines.flow.map | ||
| import java.security.GeneralSecurityException | ||
| import javax.inject.Inject | ||
|
|
||
| class DefaultTokenPreferencesDataSource @Inject constructor( | ||
| private val dataStore: DataStore<Preferences>, | ||
| private val cryptoManager: CryptoManager, | ||
| ) : TokenPreferencesDataSource { | ||
| override val accessToken: Flow<String> = decryptStringFlow(ACCESS_TOKEN) | ||
| override val refreshToken: Flow<String> = decryptStringFlow(REFRESH_TOKEN) | ||
|
|
||
| override suspend fun setAccessToken(accessToken: String) { | ||
| dataStore.edit { prefs -> | ||
| prefs[ACCESS_TOKEN] = cryptoManager.encrypt(accessToken) | ||
| } | ||
| } | ||
|
|
||
| override suspend fun setRefreshToken(refreshToken: String) { | ||
| dataStore.edit { prefs -> | ||
| prefs[REFRESH_TOKEN] = cryptoManager.encrypt(refreshToken) | ||
| } | ||
| } | ||
|
|
||
| override suspend fun clearTokens() { | ||
| dataStore.edit { prefs -> | ||
| prefs.remove(ACCESS_TOKEN) | ||
| prefs.remove(REFRESH_TOKEN) | ||
| } | ||
| } | ||
|
|
||
| private fun decryptStringFlow( | ||
| key: Preferences.Key<String>, | ||
| ): Flow<String> = dataStore.data | ||
| .handleIOException() | ||
| .map { prefs -> | ||
| prefs[key]?.let { | ||
| try { | ||
| cryptoManager.decrypt(it) | ||
| } catch (e: GeneralSecurityException) { | ||
| Logger.e(e, "Failed to decrypt token") | ||
| "" | ||
| } | ||
| }.orEmpty() | ||
| } | ||
|
|
||
| companion object { | ||
| private val ACCESS_TOKEN = stringPreferencesKey("ACCESS_TOKEN") | ||
| private val REFRESH_TOKEN = stringPreferencesKey("REFRESH_TOKEN") | ||
| } | ||
| } |
11 changes: 11 additions & 0 deletions
11
.../main/kotlin/com/ninecraft/booket/core/datastore/datasource/TokenPreferencesDataSource.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| package com.ninecraft.booket.core.datastore.datasource | ||
|
|
||
| import kotlinx.coroutines.flow.Flow | ||
|
|
||
| interface TokenPreferencesDataSource { | ||
| val accessToken: Flow<String> | ||
| val refreshToken: Flow<String> | ||
| suspend fun setAccessToken(accessToken: String) | ||
| suspend fun setRefreshToken(refreshToken: String) | ||
| suspend fun clearTokens() | ||
| } |
39 changes: 39 additions & 0 deletions
39
core/datastore/src/main/kotlin/com/ninecraft/booket/core/datastore/di/DataStoreModule.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| package com.ninecraft.booket.core.datastore.di | ||
|
|
||
| import android.content.Context | ||
| import androidx.datastore.core.DataStore | ||
| import androidx.datastore.preferences.core.Preferences | ||
| import androidx.datastore.preferences.preferencesDataStore | ||
| import com.ninecraft.booket.core.datastore.datasource.DefaultTokenPreferencesDataSource | ||
| import com.ninecraft.booket.core.datastore.datasource.TokenPreferencesDataSource | ||
| import dagger.Binds | ||
| import dagger.Module | ||
| import dagger.Provides | ||
| import dagger.hilt.InstallIn | ||
| import dagger.hilt.android.qualifiers.ApplicationContext | ||
| import dagger.hilt.components.SingletonComponent | ||
| import javax.inject.Singleton | ||
|
|
||
| @Module | ||
| @InstallIn(SingletonComponent::class) | ||
| object DataStoreModule { | ||
| private const val TOKEN_DATASTORE_NAME = "TOKENS_PREFERENCES" | ||
| private val Context.dataStore by preferencesDataStore(name = TOKEN_DATASTORE_NAME) | ||
|
|
||
| @Provides | ||
| @Singleton | ||
| fun provideTokenDataStore( | ||
| @ApplicationContext context: Context, | ||
| ): DataStore<Preferences> = context.dataStore | ||
| } | ||
|
|
||
| @Module | ||
| @InstallIn(SingletonComponent::class) | ||
| abstract class DataStoreBindModule { | ||
|
|
||
| @Binds | ||
| @Singleton | ||
| abstract fun bindTokenPreferencesDataSource( | ||
| tokenPreferencesDataSourceImpl: DefaultTokenPreferencesDataSource, | ||
| ): TokenPreferencesDataSource | ||
| } |
74 changes: 74 additions & 0 deletions
74
core/datastore/src/main/kotlin/com/ninecraft/booket/core/datastore/security/CryptoManager.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| package com.ninecraft.booket.core.datastore.security | ||
|
|
||
| import android.security.keystore.KeyGenParameterSpec | ||
| import android.security.keystore.KeyProperties | ||
| import android.util.Base64 | ||
| import java.security.KeyStore | ||
| import javax.crypto.Cipher | ||
| import javax.crypto.KeyGenerator | ||
| import javax.crypto.SecretKey | ||
| import javax.crypto.spec.IvParameterSpec | ||
| import javax.inject.Inject | ||
| import javax.inject.Singleton | ||
|
|
||
| @Singleton | ||
| class CryptoManager @Inject constructor() { | ||
| private val cipher = Cipher.getInstance(TRANSFORMATION) | ||
| private val keyStore = KeyStore | ||
| .getInstance("AndroidKeyStore") | ||
| .apply { | ||
| load(null) | ||
| } | ||
|
|
||
| private fun getKey(): SecretKey { | ||
| val existingKey = keyStore | ||
| .getEntry(KEY_ALIAS, null) as? KeyStore.SecretKeyEntry | ||
| return existingKey?.secretKey ?: createKey() | ||
| } | ||
|
|
||
| private fun createKey(): SecretKey { | ||
| return KeyGenerator | ||
| .getInstance(ALGORITHM) | ||
| .apply { | ||
| init( | ||
| KeyGenParameterSpec.Builder( | ||
| KEY_ALIAS, | ||
| KeyProperties.PURPOSE_ENCRYPT or | ||
| KeyProperties.PURPOSE_DECRYPT, | ||
| ) | ||
| .setBlockModes(BLOCK_MODE) | ||
| .setEncryptionPaddings(PADDING) | ||
| .setRandomizedEncryptionRequired(true) | ||
| .setUserAuthenticationRequired(false) | ||
| .build(), | ||
| ) | ||
| } | ||
| .generateKey() | ||
| } | ||
|
|
||
| fun encrypt(plainText: String): String { | ||
| cipher.init(Cipher.ENCRYPT_MODE, getKey()) | ||
| val iv = cipher.iv | ||
| val encryptedBytes = cipher.doFinal(plainText.toByteArray()) | ||
| val combined = iv + encryptedBytes | ||
| return Base64.encodeToString(combined, Base64.NO_WRAP) | ||
| } | ||
|
|
||
| fun decrypt(encodedText: String): String { | ||
| val combined = Base64.decode(encodedText, Base64.NO_WRAP) | ||
| val iv = combined.copyOfRange(0, IV_SIZE) | ||
| val encrypted = combined.copyOfRange(IV_SIZE, combined.size) | ||
| cipher.init(Cipher.DECRYPT_MODE, getKey(), IvParameterSpec(iv)) | ||
| val decryptedString = String(cipher.doFinal(encrypted)) | ||
| return decryptedString | ||
| } | ||
|
|
||
| companion object { | ||
| private const val KEY_ALIAS = "secret" | ||
| private const val ALGORITHM = KeyProperties.KEY_ALGORITHM_AES | ||
| private const val BLOCK_MODE = KeyProperties.BLOCK_MODE_CBC | ||
| private const val PADDING = KeyProperties.ENCRYPTION_PADDING_PKCS7 | ||
| private const val TRANSFORMATION = "$ALGORITHM/$BLOCK_MODE/$PADDING" | ||
| private const val IV_SIZE = 16 // AES IV는 항상 16바이트 | ||
| } | ||
| } |
16 changes: 16 additions & 0 deletions
16
core/datastore/src/main/kotlin/com/ninecraft/booket/core/datastore/util/DataStoreUtil.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| package com.ninecraft.booket.core.datastore.util | ||
|
|
||
| import androidx.datastore.preferences.core.Preferences | ||
| import androidx.datastore.preferences.core.emptyPreferences | ||
| import kotlinx.coroutines.flow.Flow | ||
| import kotlinx.coroutines.flow.catch | ||
| import java.io.IOException | ||
|
|
||
| fun Flow<Preferences>.handleIOException(): Flow<Preferences> = | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 👍 👍 |
||
| catch { exception -> | ||
| if (exception is IOException) { | ||
| emit(emptyPreferences()) | ||
| } else { | ||
| throw exception | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,6 +26,7 @@ include( | |
|
|
||
| ":core:designsystem", | ||
| ":core:network", | ||
| ":core:datastore", | ||
| ":core:ui", | ||
|
|
||
| ":feature:home", | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍 👍 👍