言わずと知れた facebook/concealを使う。
このリポジトリのサンプルは少しわかりにくいので、Context/StringのExtensionとして以下の様に実装するといいと思います。
設定
build.gradle
compile "com.facebook.conceal:conceal:1.1.3@aar"
これだけやるとproguard指定している場合はリリースビルドでクラッシュする。
公式に対応方法が書いてあるので参照されたし。proguard-ruleに追記すること
実装
ENCRYPT_KEYはよしなに変更してください。
private val Crypto.ENCRYPT_KEY: String
get() = "###########"
val Context.crypto: Crypto
get() {
val keyChain = SharedPrefsBackedKeyChain(this, CryptoConfig.KEY_256)
val crypto = AndroidConceal.get().createDefaultCrypto(keyChain)
if (!crypto.isAvailable) {
throw Exception("error")
}
return crypto
}
fun Crypto.encrypt(plainText: String): String {
return encrypt(plainText.toByteArray(Charsets.UTF_8), Entity.create(ENCRYPT_KEY)).let {
Base64.encodeToString(it, Base64.DEFAULT)
}
}
fun Crypto.decrypt(encrypted: String): String? {
return Base64.decode(encrypted, Base64.DEFAULT).let {
String(decrypt(it, Entity.create(ENCRYPT_KEY)))
}
}
fun String?.aesEncrypt(context:Context):String?{
if(this == null){ return null }
val res = context.crypto.encrypt(this)
return res
}
fun String?.aesDecrypt(context:Context):String?{
if(this == null){ return null }
try {
val res = context.crypto.decrypt(this)
return res
}catch (e:Exception){
return null
}
}
この部分はイケテナイ気もする
if(this == null){ return null }
val res = context.crypto.encrypt(this)