Etc

AES(암호화, 복원화)

smomo 2022. 10. 24. 14:45
//key값의 길이에 따라 AES128, AES192, AES256 으로 구분
//AES128 : 키값 16bytes, AES192 : 키값 24bytes, AES256 : 키값 32bytes
object AESUtil {
    private const val secretKey = "your_secretKey"
    private const val ecbTransformation = "AES/ECB/PKCS5Padding"
    private const val cbcTransformation = "AES/CBC/PKCS5Padding"
    private val ivBytes = secretKey.toByteArray()

    //AES 암호화(ECB)
    fun aesEncodeECB(str: String): String {
        try {
            val textBytes = str.toByteArray(charset("UTF-8"))
            val newKey = SecretKeySpec(secretKey.toByteArray(),"AES")
            var cipher: Cipher? = null
            cipher = Cipher.getInstance(ecbTransformation)
            cipher.init(Cipher.ENCRYPT_MODE, newKey)
            return Base64.encodeToString(cipher.doFinal(textBytes), Base64.NO_WRAP)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return str
    }

    //AES 복원화(ECB)
    fun aesDecodeECB(str: String): String {
        try {
            val textBytes: ByteArray = Base64.decode(str, Base64.DEFAULT)
            val newKey = SecretKeySpec(secretKey.toByteArray(), "AES")
            val cipher: Cipher = Cipher.getInstance(ecbTransformation)
            cipher.init(Cipher.DECRYPT_MODE, newKey)
            return String(cipher.doFinal(textBytes))
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return str
    }

    //AES 암호화(CBC)
    fun aesEncodeCBC(str: String): String {
        try {
            val textBytes = str.toByteArray(charset("UTF-8"))
            val ivSpec: AlgorithmParameterSpec = IvParameterSpec(ivBytes)
            val newKey = SecretKeySpec(secretKey.toByteArray(),"AES")
            var cipher: Cipher? = null
            cipher = Cipher.getInstance(cbcTransformation)
            cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec)
            return Base64.encodeToString(cipher.doFinal(textBytes), Base64.NO_WRAP)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return str
    }

    //AES 복원화(CBC)
    fun aesDecodeCBC(str: String): String {
        try {
            val textBytes: ByteArray = Base64.decode(str, Base64.DEFAULT)
            val ivSpec: AlgorithmParameterSpec = IvParameterSpec(ivBytes)
            val newKey = SecretKeySpec(secretKey.toByteArray(), "AES")
            val cipher: Cipher = Cipher.getInstance(cbcTransformation)
            cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec)
            return String(cipher.doFinal(textBytes))
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return str
    }
}