All Downloads are FREE. Search and download functionalities are using the official Maven repository.

main.com.wisetrack.sdk.Encrypt.kt Maven / Gradle / Ivy

There is a newer version: 1.5.8-alpha
Show newest version
package com.wisetrack.sdk

import android.os.Build
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec

class Encrypt {

    private val AES_TRANSFORMATION = "AES/GCM/NoPadding"
    private val AES = "AES"
    private val LENGTH = 128
    private val DELIMITER = ":"


    fun encryptAES(plainText: String, key: ByteArray): String {
        val cipher = Cipher.getInstance(AES_TRANSFORMATION)
        val secretKey: SecretKey = SecretKeySpec(key, AES)
        cipher.init(Cipher.ENCRYPT_MODE, secretKey)
        val iv = cipher.iv
        val encryptedBytes = cipher.doFinal(plainText.toByteArray())
        return android.util.Base64.encodeToString(
            encryptedBytes,
            android.util.Base64.DEFAULT
        ) + DELIMITER + android.util.Base64.encodeToString(iv, android.util.Base64.DEFAULT)

    }

    fun decryptAES(encryptedText: String, key: ByteArray): String {

        val parts = encryptedText.split(DELIMITER)
        val encryptedData = android.util.Base64.decode(parts[0], android.util.Base64.DEFAULT)
        val iv = android.util.Base64.decode(parts[1], android.util.Base64.DEFAULT)
        val cipher = Cipher.getInstance(AES_TRANSFORMATION)
        val secretKey: SecretKey = SecretKeySpec(key, AES)
        val gcmParameterSpec = GCMParameterSpec(LENGTH, iv)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec)
        }
        val decryptedBytes = cipher.doFinal(encryptedData)


        return String(decryptedBytes)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy