package com.base.scanqr.helper

import android.util.Base64
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec

object AESHelper {

    private const val aesKey = "7vwdrlk6bp8rihe4"

    private val cipher by lazy {
        Cipher.getInstance("AES/GCM/NoPadding")
    }

    fun encrypt(content: String): String {
        try {
            val iv = ByteArray(12).apply {
                SecureRandom().nextBytes(this)
            }
            val contentBytes = content.toByteArray(Charsets.UTF_8)
            val params = GCMParameterSpec(128, iv)
            cipher.init(
                Cipher.ENCRYPT_MODE,
                secretKey, params
            )
            val encryptData = cipher.doFinal(contentBytes)
            if (encryptData.size != contentBytes.size + 16) {
                throw IllegalStateException("Encryption failed")
            }
            val message = ByteArray(12 + contentBytes.size + 16)
            System.arraycopy(iv, 0, message, 0, 12)
            System.arraycopy(encryptData, 0, message, 12, encryptData.size)
            return String(Base64.encode(message, Base64.NO_WRAP), Charsets.UTF_8)
        } catch (_: Exception) {
        }
        return content
    }

    @Synchronized
    fun decrypt(content: String): String {
        try {
            val con = content.replace(" ".toRegex(), "+")
            val contentByte = Base64.decode(con, Base64.NO_WRAP)
            require(contentByte.size >= 12 + 16)
            val params = GCMParameterSpec(128, contentByte, 0, 12)
            cipher.init(
                Cipher.DECRYPT_MODE,
                secretKey, params
            )
            val decryptData = cipher.doFinal(contentByte, 12, contentByte.size - 12)
            return String(decryptData, Charsets.UTF_8)
        } catch (_: Exception) {
        }
        return content
    }

    private val secretKey by lazy {
        SecretKeySpec(aesKey.toByteArray(), "AES")
    }
}