코딩하는 일용직 노동자

AES256 암호화/복호화 본문

안드로이드

AES256 암호화/복호화

bacass 2020. 6. 8. 12:05
import android.util.Base64
import java.io.UnsupportedEncodingException
import java.security.InvalidAlgorithmParameterException
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import java.security.spec.AlgorithmParameterSpec
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.crypto.IllegalBlockSizeException
import javax.crypto.NoSuchPaddingException
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec


object AES256Chiper {
    var ivBytes = byteArrayOf(
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    )
    var secretKey = "abcd1234efgh5678" // 16글자여야 한다.

    //AES256 암호화
    @Throws(
        UnsupportedEncodingException::class,
        NoSuchAlgorithmException::class,
        NoSuchPaddingException::class,
        InvalidKeyException::class,
        InvalidAlgorithmParameterException::class,
        IllegalBlockSizeException::class,
        BadPaddingException::class
    )
    fun encode(str: String): String {
        val textBytes = str.toByteArray(charset("UTF-8"))
        val ivSpec: AlgorithmParameterSpec =
            IvParameterSpec(ivBytes)
        val newKey = SecretKeySpec(
            secretKey.toByteArray(charset("UTF-8")),
            "AES"
        )
        var cipher: Cipher? = null
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
        cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec)
        return Base64.encodeToString(cipher.doFinal(textBytes), 0)
    }

    //AES256 복호화
    @Throws(
        UnsupportedEncodingException::class,
        NoSuchAlgorithmException::class,
        NoSuchPaddingException::class,
        InvalidKeyException::class,
        InvalidAlgorithmParameterException::class,
        IllegalBlockSizeException::class,
        BadPaddingException::class
    )
    fun decode(str: String?): String {
        val textBytes = Base64.decode(str, 0)
        //byte[] textBytes = str.getBytes("UTF-8");
        val ivSpec: AlgorithmParameterSpec =
            IvParameterSpec(ivBytes)
        val newKey = SecretKeySpec(
            secretKey.toByteArray(charset("UTF-8")),
            "AES"
        )
        val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec)
        return String(cipher.doFinal(textBytes), charset("UTF-8"))
    }
}
private fun testEncryp() {
    val test = "테스트할 문자열 입니다."
    val encode = AES256Chiper.encode(test)
    val decode = AES256Chiper.decode(encode)
    Log.d("TEST" , "encode: $encode")
    Log.d("TEST" , "decode: $decode")
}

문자열을 암호화/복호화 한 결과