LoginSignup
0

More than 5 years have passed since last update.

kotlinで文字列を暗号化したり複合する

Last updated at Posted at 2017-06-01

言わずと知れた 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)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0