Created
March 13, 2020 12:52
-
-
Save eoinahern/5a87e7d63e51bfd11f1f1a8302d7c264 to your computer and use it in GitHub Desktop.
This file contains 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
private const val IV_KEY = "iv" | |
class EncryptionUtil @Inject constructor( | |
private val keyGenerator: KeyGenerator, | |
private val keyGenParameterSpec: KeyGenParameterSpec, | |
private val keyStore: KeyStore, | |
private val prefs: SharedPreferences, | |
private val editPrefs: SharedPreferences.Editor | |
) { | |
init { | |
keyGenerator.init(keyGenParameterSpec) | |
keyGenerator.generateKey() | |
keyStore.load(null) | |
} | |
@Synchronized | |
fun encrypt(data: ByteArray): ByteArray { | |
val cipher = Cipher.getInstance(TRANSFORMATION_AES) | |
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey()) | |
val ivBytes = cipher.iv | |
val encryptedIV = android.util.Base64.encodeToString( | |
ivBytes, | |
android.util.Base64.NO_WRAP | |
) | |
editPrefs.putString(IV_KEY, encryptedIV).commit() | |
return cipher.doFinal(data) | |
} | |
@Synchronized | |
fun decrypt(data: ByteArray): ByteArray { | |
val cipher = Cipher.getInstance(TRANSFORMATION_AES) | |
val encryptedIV = prefs.getString(IV_KEY, "") | |
val iv = android.util.Base64.decode(encryptedIV, android.util.Base64.NO_WRAP) | |
val spec = GCMParameterSpec(128, iv) | |
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), spec) | |
return cipher.doFinal(data) | |
} | |
private fun getSecretKey(): SecretKey { | |
val secretKeyEntry = keyStore.getEntry(KEYSTORE_ALIAS, null) as KeyStore.SecretKeyEntry | |
return secretKeyEntry.secretKey | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment