MalwareServer/Connect.kt
2024-04-30 16:27:44 +02:00

91 lines
3.1 KiB
Kotlin

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)
secureRandom.nextBytes(keyBytes)
val key = SecretKeySpec(keyBytes, "AES")
val ivBytes = ByteArray(16)
secureRandom.nextBytes(ivBytes)
val iv = IvParameterSpec(ivBytes)
val algorithm = "AES/CBC/PKCS5Padding"
val inputText = "abcdefghigklmnopqrstuvwxyz0123456789"
withContext(Dispatchers.IO) {
Socket(host, port).use { socket ->
val writer = PrintWriter(socket.getOutputStream(), true)
val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
val encodedKey = encodeBase64(keyBytes)
println(keyBytes.toHexString())
writer.println(encodedKey)
println(reader.readLine())
val encodedIV = encodeBase64(ivBytes)
println(ivBytes.toHexString())
writer.println(encodedIV)
println(reader.readLine())
val cipherText = encrypt(algorithm, inputText, key, iv)
println(cipherText)
writer.println(cipherText)
writer.println("END_OF_COMMUNICATION")
println(reader.readLine())
println("Client: Ready for next operation")
writer.println("Ready for next operation")
println(reader.readLine())
}
}
}
}
}