美文网首页
AES加解密

AES加解密

作者: Q大疯zi | 来源:发表于2018-09-10 23:08 被阅读43次

    以下是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博客

    相关文章

      网友评论

          本文标题:AES加解密

          本文链接:https://www.haomeiwen.com/subject/kzaegftx.html