Android AES加密(Kotlin)

3414次阅读  |  发布于3年以前

最近工作上写的东西比较简单,感觉分享不出来,最近刚好看到数据加密这一块,感觉挺不错的,也挺好用的,所以下面分享给大家!

注意:解密时,要用加密时用的密钥K去解密,不然得不到正确的结果。

基本的加密过程就是这样的,下面先把AES工具类写出来:

class AESUtils {
  private val SHA1PRNG = "SHA1PRNG" // SHA1PRNG 强随机种子算法, 要区别4.2以上版本的调用方法
  private val IV = "qws871bz73msl9x8"
  private val AES = "AES" //AES 加密
  private val CIPHERMODE = "AES/CBC/PKCS5Padding" //algorithm/mode/padding

  /**
   * 加密
   */
  fun encrypt(key: String, cleartext: String): String? {
    if (TextUtils.isEmpty(cleartext)) {
      return cleartext
    }
    try {
      val result = encrypt(key, cleartext.toByteArray())
      return parseByte2HexStr(result)
    }
    catch (e: Exception) {
      e.printStackTrace()
    }
    return null
  }

  /**
   * 加密
   */
  @Throws(Exception::class)
  fun encrypt(key: String, clear: ByteArray?): ByteArray {
    val raw = getRawKey(key.toByteArray())
    val skeySpec = SecretKeySpec(raw, AES)
    val cipher: Cipher = Cipher.getInstance(CIPHERMODE)
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, IvParameterSpec(ByteArray(cipher.blockSize)))
    return cipher.doFinal(clear)
  }

  /**
   * 解密
   */
  fun decrypt(key: String, encrypted: String): String? {
    if (TextUtils.isEmpty(encrypted)) {
      return encrypted
    }
    try {
      val enc = parseHexStr2Byte(encrypted)
      val result = decrypt(key, enc)
      return String(result)
    }
    catch (e: Exception) {
      e.printStackTrace()
    }
    return null
  }

  /**
   * 解密
   */
  @Throws(Exception::class)
  fun decrypt(key: String, encrypted: ByteArray?): ByteArray {
    val raw = getRawKey(key.toByteArray())
    val skeySpec = SecretKeySpec(raw, AES)
    val cipher: Cipher = Cipher.getInstance(CIPHERMODE)
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, IvParameterSpec(ByteArray(cipher.blockSize)))
    return cipher.doFinal(encrypted)
  }

  /**
   * 生成随机数,可以当做动态的密钥
   * 加密和解密的密钥必须一致,不然将不能解密
   */
  fun generateKey(): String? {
    try {
      val secureRandom: SecureRandom = SecureRandom.getInstance(SHA1PRNG)
      val key = ByteArray(20)
      secureRandom.nextBytes(key)
      return toHex(key)
    }
    catch (e: NoSuchAlgorithmException) {
      e.printStackTrace()
    }
    return null
  }

  /**
   * 对密钥进行处理
   */
  @Throws(Exception::class)
  fun getRawKey(seed: ByteArray?): ByteArray {
    val kgen: KeyGenerator = KeyGenerator.getInstance(AES)
    //for android
    var sr: SecureRandom? = null
    // 在4.2以上版本中,SecureRandom获取方式发生了改变
    //crypto 加密
    sr = if (Build.VERSION.SDK_INT >= 17) {
      SecureRandom.getInstance(SHA1PRNG, CryptoProvider())
    }
    else {
      SecureRandom.getInstance(SHA1PRNG)
    }
    // for Java
    // secureRandom = SecureRandom.getInstance(SHA1PRNG);
    sr.setSeed(seed)
    kgen.init(128, sr) //256 bits or 128 bits,192bits
    //AES中128位密钥版本有10个加密循环,192比特密钥版本有12个加密循环,256比特密钥版本则有14个加密循环。
    val skey: SecretKey = kgen.generateKey()
    return skey.getEncoded()
  }

  /**
   * 二进制转字符
   */
  private fun toHex(buf: ByteArray?): String? {
    if (buf == null) return ""
    val result = StringBuffer(2 * buf.size)
    for (i in buf.indices) {
      appendHex(result, buf[i])
    }
    return result.toString()
  }

  private fun appendHex(sb: StringBuffer, b: Byte) {
    sb.append(IV[b.toInt() shr 4 and 0x0f]).append(IV[b.toInt() and 0x0f])
  }

  /**
   * 将二进制转换成16进制
   *
   * @param buf
   * @return
   */
  private fun parseByte2HexStr(buf: ByteArray): String? {
    val sb = StringBuilder()
    for (i in buf.indices) {
      var hex = Integer.toHexString(buf[i].toInt() and 0xFF)
      if (hex.length == 1) {
        hex = "0$hex"
      }
      sb.append(hex.toUpperCase(Locale.ROOT))
    }
    return sb.toString()
  }

  /**
   * 将16进制转换为二进制
   *
   * @param hexStr
   * @return
   */
  private fun parseHexStr2Byte(hexStr: String): ByteArray? {
    if (hexStr.isEmpty()) return null
    val result = ByteArray(hexStr.length / 2)
    for (i in 0 until hexStr.length / 2) {
      val high = hexStr.substring(i * 2, i * 2 + 1).toInt(16)
      val low = hexStr.substring(i * 2 + 1, i * 2 + 2).toInt(16)
      result[i] = (high * 16 + low).toByte()
    }
    return result
  }
}

很多人看到一整块看不懂的代码都不想看,我给大家分开解释下

/**
   * 加密
   */
  fun encrypt(key: String, cleartext: String): String? {
    if (TextUtils.isEmpty(cleartext)) {
      return cleartext
    }
    try {
      val result = encrypt(key, cleartext.toByteArray())
      return parseByte2HexStr(result)
    }
    catch (e: Exception) {
      e.printStackTrace()
    }
    return null
  }

  /**
   * 加密
   */
  @Throws(Exception::class)
  fun encrypt(key: String, clear: ByteArray?): ByteArray {
    val raw = getRawKey(key.toByteArray())
    val skeySpec = SecretKeySpec(raw, AES)
    val cipher: Cipher = Cipher.getInstance(CIPHERMODE)
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, IvParameterSpec(ByteArray(cipher.blockSize)))
    return cipher.doFinal(clear)
  }
private fun appendHex(sb: StringBuffer, b: Byte) {
    sb.append(IV[b.toInt() shr 4 and 0x0f]).append(IV[b.toInt() and 0x0f])
  }
  /**
   * 将二进制转换成16进制
   *
   * @param buf
   * @return
   */
  private fun parseByte2HexStr(buf: ByteArray): String? {
    val sb = StringBuilder()
    for (i in buf.indices) {
      var hex = Integer.toHexString(buf[i].toInt() and 0xFF)
      if (hex.length == 1) {
        hex = "0$hex"
      }
      sb.append(hex.toUpperCase(Locale.ROOT))
    }
    return sb.toString()
  }
/**
   * 解密
   */
  fun decrypt(key: String, encrypted: String): String? {
    if (TextUtils.isEmpty(encrypted)) {
      return encrypted
    }
    try {
      val enc = parseHexStr2Byte(encrypted)
      val result = decrypt(key, enc)
      return String(result)
    }
    catch (e: Exception) {
      e.printStackTrace()
    }
    return null
  }

  /**
   * 解密
   */
  @Throws(Exception::class)
  fun decrypt(key: String, encrypted: ByteArray?): ByteArray {
    val raw = getRawKey(key.toByteArray())
    val skeySpec = SecretKeySpec(raw, AES)
    val cipher: Cipher = Cipher.getInstance(CIPHERMODE)
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, IvParameterSpec(ByteArray(cipher.blockSize)))
    return cipher.doFinal(encrypted)
  }
/**
   * 将16进制转换为二进制
   *
   * @param hexStr
   * @return
   */
  private fun parseHexStr2Byte(hexStr: String): ByteArray? {
    if (hexStr.isEmpty()) return null
    val result = ByteArray(hexStr.length / 2)
    for (i in 0 until hexStr.length / 2) {
      val high = hexStr.substring(i * 2, i * 2 + 1).toInt(16)
      val low = hexStr.substring(i * 2 + 1, i * 2 + 2).toInt(16)
      result[i] = (high * 16 + low).toByte()
    }
    return result
  }

如何调用呢?

  private var aes = AESUtils()
  private var PASSWORD_STRING = aes.generateKey()?:"qws871bz73msl9x8"

    override fun initView() {
    encrypt.setOnClickListener(this)
    decrypt.setOnClickListener(this)
  }
  //加密
  private fun encrypt(){
    var inputString:String? = ase_input.text.toString().trim()
    if (inputString?.length == 0){
      Toast.makeText(this,"请输入加密的内容",Toast.LENGTH_LONG).show()
      return
    }
    var encryStr = aes.encrypt(PASSWORD_STRING,inputString?:"")
    show_ase_encrypt.text = encryStr
  }

  //解密
  private fun decrypt(){
    var inputString:String? = show_ase_encrypt.text.toString().trim()
    if (inputString?.length == 0){
      Toast.makeText(this,"请输入加密的内容",Toast.LENGTH_LONG).show()
      return
    }
    var decryStr = aes.decrypt(PASSWORD_STRING,inputString?:"")
    show_oringe_encrypt.text = decryStr
  }

  override fun onClick(v: View?) {
    when(v?.id){
      R.id.encrypt -> encrypt()
      R.id.decrypt -> decrypt()
    }
  }

layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:id="@+id/activity_main"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

 <EditText
  android:id="@+id/ase_input"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:hint="输入要加密的内容"
  app:layout_constraintTop_toTopOf="parent"/>

 <Button
  android:id="@+id/encrypt"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="点击进行ASE加密" 
  app:layout_constraintTop_toBottomOf="@id/ase_input"
  app:layout_constraintLeft_toLeftOf="parent"/>

 <TextView
  android:id="@+id/show_ase_encrypt"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="10dp"
  android:text="显示加密后的内容" 
  app:layout_constraintTop_toBottomOf="@id/encrypt"/>

 <Button
  android:id="@+id/decrypt"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="点击进行ASE解密" 
  app:layout_constraintTop_toBottomOf="@id/show_ase_encrypt"
  app:layout_constraintLeft_toLeftOf="parent"/>

 <TextView
  android:id="@+id/show_oringe_encrypt"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="10dp"
  android:text="显示加密后的内容" 
  app:layout_constraintTop_toBottomOf="@id/decrypt"/>

</androidx.constraintlayout.widget.ConstraintLayout>

  @Throws(Exception::class)
  fun getRawKey(seed: ByteArray?): ByteArray {
    val kgen: KeyGenerator = KeyGenerator.getInstance(AES)
    //for android
    var sr: SecureRandom? = null
    // 在4.2以上版本中,SecureRandom获取方式发生了改变
    //crypto 加密
    sr = if (Build.VERSION.SDK_INT >= 17) {
      SecureRandom.getInstance(SHA1PRNG, CryptoProvider())
    }
    else {
      SecureRandom.getInstance(SHA1PRNG)
    }
    // for Java
    // secureRandom = SecureRandom.getInstance(SHA1PRNG);
    sr.setSeed(seed)
    kgen.init(128, sr) //256 bits or 128 bits,192bits
    //AES中128位密钥版本有10个加密循环,192比特密钥版本有12个加密循环,256比特密钥版本则有14个加密循环。
    val skey: SecretKey = kgen.generateKey()
    return skey.getEncoded()
  }
class CryptoProvider : Provider("Crypto",1.0,"HARMONY (SHA1 digest; SecureRandom; SHA1withDSA signature)") {
  init {
    put("SecureRandom.SHA1PRNG", "org.apache.harmony.security.provider.crypto.SHA1PRNG_SecureRandomImpl")
    put("SecureRandom.SHA1PRNG ImplementedIn", "Software")
  }
}

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8