Skip to content

Commit

Permalink
Use secure random for socketio secret
Browse files Browse the repository at this point in the history
  • Loading branch information
vinkabuki committed Oct 30, 2023
1 parent 426c52b commit d758341
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,11 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.random.Random
import org.json.JSONException
import org.json.JSONObject
import org.torproject.android.binary.TorResourceInstaller
import java.util.concurrent.ThreadLocalRandom
import kotlin.collections.ArrayList
import kotlin.math.pow


class BackendWorker(private val context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) {
Expand Down Expand Up @@ -95,7 +93,7 @@ class BackendWorker(private val context: Context, workerParams: WorkerParameters

// Get and store data port for usage in methods across the app
val dataPort = Utils.getOpenPort(11000)
val socketIOSecret = Random.nextLong(0, 100.0.pow(10.0).toLong()).toString()
val socketIOSecret = Utils.generateRandomString(20)

// Init nodejs project
launch {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import java.io.*
import java.net.ConnectException
import java.net.InetSocketAddress
import java.net.Socket
import java.security.SecureRandom
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

Expand All @@ -29,6 +30,19 @@ object Utils {
return dataDirectory.absolutePath
}

fun generateRandomString(length: Int): String {
val CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
val secureRandom = SecureRandom()
val randomString = StringBuilder(length)

repeat(length) {
val randomIndex = secureRandom.nextInt(CHARACTERS.length)
randomString.append(CHARACTERS[randomIndex])
}

return randomString.toString()
}

suspend fun getOpenPort(starting: Int) = suspendCoroutine<Int> { continuation ->
val port = checkPort(starting)
continuation.resume(port)
Expand Down

0 comments on commit d758341

Please sign in to comment.