[Android/Kotlin] AES-256 암호화/복호화

SoyoungLee·2022년 11월 3일
0

안드로이드/코틀린

목록 보기
50/70
post-thumbnail

💌 [Android/Kotlin] AES-256 암호화/복호화

많은 암호화 방식이 있지만 AES-256 CBC 암호화를 구현해보려 한다.

📌 AES-128, AES-192, AES-256

  • 키의 길이에 따라 나뉨.
    AES-128 : 16byte
    AES-192 : 24byte
    AES-256 : 32byte
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingHorizontal="25dp">

        <TextView
            android:id="@+id/tv_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/login"
            android:textSize="@dimen/text_18"
            android:textStyle="bold" />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/id_TIL"
            style="@style/TextInputTheme"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_20"
            android:isScrollContainer="false"
            app:errorEnabled="true"
            app:expandedHintEnabled="false">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/id_et"
                style="@style/EditTextStyle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:hint="@string/id"
                android:paddingVertical="@dimen/padding_14"
                android:singleLine="true"
                android:textSize="@dimen/text_14"
                tools:ignore="SpeakableTextPresentCheck" />
        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/pwd_edit_textInputLayout"
            style="@style/TextInputTheme"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_6"
            android:theme="@style/EditTextThemeOverlay"
            app:errorEnabled="true"
            app:expandedHintEnabled="false"
            app:passwordToggleEnabled="true">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/pwd_edit_text"
                style="@style/EditTextStyle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/passWord"
                android:inputType="textPassword"
                android:paddingVertical="@dimen/padding_14"
                android:textSize="@dimen/text_14"
                tools:ignore="SpeakableTextPresentCheck" />
        </com.google.android.material.textfield.TextInputLayout>


        <Button
            android:id="@+id/btn_login"
            style="@style/btnStyle"
            android:layout_width="match_parent"
            android:layout_height="@dimen/size_60"
            android:text="@string/login" />

    </LinearLayout>

💜 입력한 아이디와 비밀번호 JSON 객체를 암호화/복호화.

class LoginActivity : AppCompatActivity() {

    companion object {
        const val SECRET_KEY = "ABCDEFGH12345678"
    }
    
    private val SECRET_IV = byteArrayOf(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
    private lateinit var binding: ActivityLoginBinding
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityLoginBinding.inflate(layoutInflater).also {
            setContentView(it.root)
        }
        
        with(binding) {

            btnLogin.setOnClickListener {
                val json = JsonObject()
                json.addProperty("id", binding.idEt.text.toString())
                json.addProperty("pw", binding.pwdEditText.text.toString())
                Log.d(TAG,"userInfo => ${Gson().toJson(json)}")

                val encrypted = encryptCBC(json)
                Log.d(TAG,"암호화 => $encrypted")
                val decrypted = decryptCBC(encrypted)
                Log.d(TAG,"복호화 => $decrypted")
                ...
}
   

💜 AES 256 CBC 암호화

// AES 256 CBC 암호화
private fun encryptCBC(jsonObj: JsonObject): String {
        val params = JSONObject()
        try {
            val strJson = Gson().toJson(jsonObj)
            val iv = IvParameterSpec(SECRET_IV)
            val key = SecretKeySpec(SECRET_KEY.toByteArray(), "AES")

            val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
            cipher.init(Cipher.ENCRYPT_MODE, key,iv)

            val crypted = cipher.doFinal(strJson.toByteArray())
            val encodedByte = Base64.encode(crypted, Base64.DEFAULT)
           
            return String(encodedByte)
            
        } catch (e: Exception) {
            Log.e("Exception", "Exception : ${e.message}")
        }
        return ""
}

💜 AES 256 CBC 복호화

// AES 256 CBC 복호화
private fun decryptCBC(str: String): String {

        val iv = IvParameterSpec(SECRET_IV)
        val key = SecretKeySpec(SECRET_KEY.toByteArray(), "AES")

        val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
        cipher.init(Cipher.DECRYPT_MODE, key, iv)

        val decodedByte = Base64.decode(str, Base64.DEFAULT)
        val byteResult = cipher.doFinal(decodedByte)

        return String(byteResult)
}

🤍 결과

참고 : https://developer.android.com/reference/kotlin/javax/crypto/Cipher
https://perfectacle.github.io/2019/11/24/aes/
https://developer.android.com/guide/topics/security/cryptography?hl=ko

profile
Android Developer..+ iOS 슬쩍 🌱 ✏️끄적끄적,,개인 기록용 👩🏻‍💻

0개의 댓글