以下是AES加解密Kotlin实现:
object AESCrypt {
/**
* AES加密
*/
fun enCrypt(str: String, pwd: String): String {
//创建cipher对象
val cipher = Cipher.getInstance("AES")
val secretKeySpec: SecretKeySpec? = SecretKeySpec(pwd.toByteArray(), "AES")
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec)
val enCryptRes = cipher.doFinal(str.toByteArray())
val result = Base64.encode(enCryptRes)
return result
}
/**
* 解密
*/
fun deCrypt(str: String, pwd: String): String {
//创建cipher对象
val cipher = Cipher.getInstance("AES")
val secretKeySpec: SecretKeySpec? = SecretKeySpec(pwd.toByteArray(), "AES")
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec)
val deCryptRes = cipher.doFinal(Base64.decode(str))
val result = String(deCryptRes)
return result
}
}
fun main(args: Array<String>) {
val str = "老婆我爱你"
val pwd = "1234567812345678"
val enCrypt = AESCrypt.enCrypt(str, pwd)
println("加密后的结果:$enCrypt")
val deCrypt = AESCrypt.deCrypt(enCrypt, pwd)
println("解密后的结果:$deCrypt")
}
Base64的工具请看上一篇DES博客
网友评论