package com.ti.mobpo.ui.util import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.BufferedReader import java.io.InputStreamReader import java.io.PrintWriter import java.net.Socket import java.security.SecureRandom import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec class Connect { companion object { fun decodeBase64(input: String): ByteArray { return android.util.Base64.decode(input, android.util.Base64.DEFAULT) } fun encodeBase64(input: ByteArray): String { return android.util.Base64.encodeToString(input, android.util.Base64.DEFAULT) } fun decrypt(algorithm: String, cipherText: String, key: SecretKeySpec, iv: IvParameterSpec): String { val cipher = Cipher.getInstance(algorithm) cipher.init(Cipher.DECRYPT_MODE, key, iv) val plainText = cipher.doFinal(decodeBase64(cipherText)) return String(plainText) } fun encrypt(algorithm: String, inputText: String, key: SecretKeySpec, iv: IvParameterSpec): String { val cipher = Cipher.getInstance(algorithm) cipher.init(Cipher.ENCRYPT_MODE, key, iv) val cipherText = cipher.doFinal(inputText.toByteArray()) return encodeBase64(cipherText) } @OptIn(ExperimentalStdlibApi::class) suspend fun main() { val host = "192.168.90.151" val port = 8080 val secureRandom = SecureRandom() val keyBytes = ByteArray(16) val ivBytes = ByteArray(16) secureRandom.nextBytes(keyBytes) secureRandom.nextBytes(ivBytes) val key = SecretKeySpec(keyBytes, "AES") val iv = IvParameterSpec(ivBytes) val algorithm = "AES/CBC/PKCS5Padding" var sendData = "Hello, World!" val chunkSize = 45 val chunks = sendData.chunked(chunkSize) withContext(Dispatchers.IO) { Socket(host, port).use { socket -> val writer = PrintWriter(socket.getOutputStream(), true) val reader = BufferedReader(InputStreamReader(socket.getInputStream())) val encodedKey = encodeBase64(keyBytes) writer.println(encodedKey) reader.readLine() val encodedIV = encodeBase64(ivBytes) writer.println(encodedIV) reader.readLine() for (chunk in chunks) { val cipherText = encrypt(algorithm, chunk, key, iv) writer.println(cipherText) reader.readLine() } writer.println("END_OF_COMMUNICATION") reader.readLine() println("Client: Ready for next operation") writer.println("Ready for next operation") reader.readLine() } } } } }