Created
April 29, 2021 18:00
-
-
Save smokelaboratory/76eeb2c9e1c4939080ac8278fa2e9475 to your computer and use it in GitHub Desktop.
Security Utility class
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
| class SecurityUtil | |
| @Inject | |
| constructor() { | |
| private val provider = "AndroidKeyStore" | |
| private val cipher by lazy { | |
| Cipher.getInstance("AES/GCM/NoPadding") | |
| } | |
| private val charset by lazy { | |
| charset("UTF-8") | |
| } | |
| private val keyStore by lazy { | |
| KeyStore.getInstance(provider).apply { | |
| load(null) | |
| } | |
| } | |
| private val keyGenerator by lazy { | |
| KeyGenerator.getInstance(KEY_ALGORITHM_AES, provider) | |
| } | |
| fun encryptData(keyAlias: String, text: String): ByteArray { | |
| cipher.init(Cipher.ENCRYPT_MODE, generateSecretKey(keyAlias)) | |
| return cipher.doFinal(text.toByteArray(charset)) | |
| } | |
| fun decryptData(keyAlias: String, encryptedData: ByteArray): String { | |
| cipher.init(Cipher.DECRYPT_MODE, getSecretKey(keyAlias), GCMParameterSpec(128, cipher.iv)) | |
| return cipher.doFinal(encryptedData).toString(charset) | |
| } | |
| private fun generateSecretKey(keyAlias: String): SecretKey { | |
| return keyGenerator.apply { | |
| init( | |
| KeyGenParameterSpec | |
| .Builder(keyAlias, PURPOSE_ENCRYPT or PURPOSE_DECRYPT) | |
| .setBlockModes(BLOCK_MODE_GCM) | |
| .setEncryptionPaddings(ENCRYPTION_PADDING_NONE) | |
| .build() | |
| ) | |
| }.generateKey() | |
| } | |
| private fun getSecretKey(keyAlias: String) = | |
| (keyStore.getEntry(keyAlias, null) as KeyStore.SecretKeyEntry).secretKey | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment