Last active
July 5, 2018 09:51
-
-
Save ishikota/17127c1d776b503a910cbd93419aa4ee to your computer and use it in GitHub Desktop.
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
companion object { | |
private const val ALGORITHM = "AES" | |
private const val MODE = "CBC" | |
private const val PADDING = "PKCS5Padding" | |
} | |
fun savePrivateString(key: String, value: String) { | |
prefs.edit().putString(key, encrypt(value)).apply() | |
} | |
fun getPrivateString(key: String): String { | |
val encrypted = prefs.getString(key, "") | |
return decrypt(encrypted) | |
} | |
private fun encrypt(plain: String): String { | |
val cipher = initializeCipher(Cipher.ENCRYPT_MODE) | |
val encrypted = cipher.doFinal(plain.toByteArray()) ?: byteArrayOf() // TODO catch exception | |
return Base64.encodeToString(encrypted, Base64.DEFAULT) | |
} | |
private fun decrypt(encrypted: String): String { | |
val cipher = initializeCipher(Cipher.DECRYPT_MODE) | |
val decrypted = cipher.doFinal(plain.toByteArray()) ?: byteArrayOf() // TODO catch exception | |
return String(decrypted) | |
} | |
private fun initializeCipher(mode: Int) = Cipher.getInstance("$ALGORITHM/$MODE/$PADDING").apply { | |
val key = BuildConfig.CIPHER_KEY // !!NOTICE!! Secret key is necessarry for encryption/decryption. | |
val iv = BuildConfig.CIPHER_IV // InitializationVector. 16bytes string. | |
val secretKeySpec = SecretKeySpec(key.toByteArray(), ALGORITHM) | |
val ivSpec = IvParameterSpec(iv.toByteArray()) | |
init(mode, secretKeySpec, ivSpec) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment