AES256 암복호화

AES256 암복호화 구현

import java.util.*
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

object Aes256Encryptor {

    private const val KEY = "5s2I7j2JdJgaPfDJUqyW66344eTnIWni"
    private val secretKeySpec = SecretKeySpec(KEY.toByteArray(), "AES")
    private const val IV = "f0f23707804963be"
    private val ivParameterSpec = IvParameterSpec(IV.toByteArray())

    fun encrypt(payload: String): String {
        val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec)
        val encrypted = cipher.doFinal(payload.toByteArray())

        return String(Base64.getEncoder().encode(encrypted))
    }

    fun decrypt(payload: String): String {
        val bytesOfPayload = Base64.getDecoder().decode(payload)
        val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)

        return String(cipher.doFinal(bytesOfPayload))
    }
}

테스트

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.util.*

internal class Aes256EncryptorTest {

    @Test
    fun `Aes256Encryptor encrypt and decrypt correctly`() {
        // Arrange
        val payload = UUID.randomUUID().toString()

        // Act
        val sut = Aes256Encryptor
        val actual = sut.encrypt(payload)

        // Assert
        assertThat(sut.decrypt(actual)).isEqualTo(payload)
    }
}