object BruteForce {
private val archiveDecrypt: ArchiveDecrypt = FileArchiveDecrypt
private val progress: ProgressFileHandler = Progress
private val passwordFoundFlow = MutableSharedFlow()
private var passwordFound = AtomicReference<String?>(null)
code
Assistant
/**
* Tenta descriptografar o arquivo fornecido utilizando a técnica de força bruta.
*
* @param file o arquivo a ser descriptografado
* @return a senha utilizada para descriptografar o arquivo
* @throws IllegalArgumentException se o arquivo não for criptografado
*/
suspend fun force(file: File): String {
if (!Encrypt().isEncrypted(file)) {
throw IllegalArgumentException("Arquivo não criptografado!")
}
progress.loadProgress(file.name)
val duration = measureTime {
val consumers = List(Runtime.getRuntime().availableProcessors()) {
CoroutineScope(Dispatchers.IO).launch { tryPasswords(file) }
}
passwordFound = passwordFoundFlow.first()
consumers.forEach { it.cancel() }
}
val passwordsGenerated = progress.passwordIterator.totalPasswordsGenerated.toInt()
JOptionPane.showMessageDialog(
null, "\n--Senha encontrada--\n$passwordFound\nTempo de execução: $duration\nSenhas testadas: " + "$passwordsGenerated\nSenhas por segundo: ${
if (duration.inWholeSeconds > 0) {
passwordsGenerated / duration.inWholeSeconds
} else {
passwordsGenerated / duration.inWholeMilliseconds
}
}", "Senha encontrada!", JOptionPane.INFORMATION_MESSAGE
)
Logger.getLogger(this.javaClass.name).info(
"\n--Senha encontrada--\n$passwordFound\nTempo de execução: $duration\nSenhas testadas: " + "$passwordsGenerated\nSenhas por segundo: ${
if (duration.inWholeSeconds > 0) {
passwordsGenerated / duration.inWholeSeconds
} else {
passwordsGenerated / duration.inWholeMilliseconds
}
}"
)
return passwordFound.get()!!.also {
passwordFound = AtomicReference<String?>(null)
progress.passwordIterator.reset()
}
}
private suspend fun tryPasswords(archiveFile: File) {
while (passwordFound.get() == null) {
if (progress.passwordIterator.totalPasswordsGenerated.toInt() % 5000 == 0) {
progress.saveProgress(archiveFile.name)
}
val result = archiveDecrypt.tryPassword(archiveFile, progress.passwordIterator.getNextPassword())
if (passwordFound.compareAndSet(null, result) && result?.isNotBlank() == true) {
passwordFoundFlow.emit(result)
break
}
}
}
}
a linha
passwordFound = passwordFoundFlow.first()
está errada, como posso corrigir?
The error in your code arises because you are attempting to assign a String value (the result of passwordFoundFlow.first()) to passwordFound, which is an AtomicReference<String?>. This is a type mismatch.
Here's the problematic line:
kotlin
passwordFound = passwordFoundFlow.first()
To fix this issue, you should retrieve the first emitted value from the passwordFoundFlow and assign it to a local variable of type String. Then, you can use this variable in your code wherever necessary.
Here's how you can modify your code:
Replace the erroneous line with:
kotlin
val foundPassword = passwordFoundFlow.first()
Use foundPassword instead of passwordFound.get()!! in the rest of your code.
Since you're now using foundPassword directly, you may not need the passwordFoundAtomicReference anymore unless it's used elsewhere for synchronization.
Here's the corrected version of your force function:
kotlin
suspend fun force(file: File): String {
if (!Encrypt().isEncrypted(file)) {
throw IllegalArgumentException("Arquivo não criptografado!")
}
progress.loadProgress(file.name)
val foundPassword: String
val duration = measureTime {
val consumers = List(Runtime.getRuntime().availableProcessors()) {
CoroutineScope(Dispatchers.IO).launch { tryPasswords(file) }
}
foundPassword = passwordFoundFlow.first()
consumers.forEach { it.cancel() }
}
val passwordsGenerated = progress.passwordIterator.totalPasswordsGenerated.toInt()
JOptionPane.showMessageDialog(
null, "\n--Senha encontrada--\n$foundPassword\nTempo de execução: $duration\nSenhas testadas: " +
"$passwordsGenerated\nSenhas por segundo: ${
if (duration.inWholeSeconds > 0) {
passwordsGenerated / duration.inWholeSeconds
} else {
passwordsGenerated / duration.inWholeMilliseconds
}
}", "Senha encontrada!", JOptionPane.INFORMATION_MESSAGE
)
Logger.getLogger(this.javaClass.name).info(
"\n--Senha encontrada--\n$foundPassword\nTempo de execução: $duration\nSenhas testadas: " +
"$passwordsGenerated\nSenhas por segundo: ${
if (duration.inWholeSeconds > 0) {
passwordsGenerated / duration.inWholeSeconds
} else {
passwordsGenerated / duration.inWholeMilliseconds
}
}"
)
return foundPassword.also {
passwordFound = AtomicReference<String?>(null)
progress.passwordIterator.reset()
}
}
By making this change, you ensure that you are assigning the result of passwordFoundFlow.first() to a variable of the correct type, and you avoid the type mismatch error.
Explanation:
passwordFoundFlow.first() is a suspend function that retrieves the first value emitted by the passwordFoundFlow, which is of type String.
Assigning this value to an AtomicReference<String?> variable (passwordFound) causes a type mismatch because you cannot assign a String directly to an AtomicReference.
By introducing a local variable foundPassword of type String, you correctly handle the value returned from the flow.
You can then use foundPassword in your user interface messages and logs.
If the AtomicReference<String?>passwordFound is no longer needed elsewhere in your code, you may consider removing it to simplify your codebase.
Note: Ensure that any other parts of your code that rely on passwordFound are updated accordingly to use foundPassword or are refactored if passwordFound is no longer necessary.
Summary: Replace passwordFound = passwordFoundFlow.first() with val foundPassword = passwordFoundFlow.first(), and adjust subsequent code to use foundPassword.