Skip to content

Instantly share code, notes, and snippets.

@eoinahern
Created March 13, 2020 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eoinahern/5a87e7d63e51bfd11f1f1a8302d7c264 to your computer and use it in GitHub Desktop.
Save eoinahern/5a87e7d63e51bfd11f1f1a8302d7c264 to your computer and use it in GitHub Desktop.
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