You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
2.0 KiB
54 lines
2.0 KiB
package cipher_analytical_machine.analyzers.caesar;
|
|
|
|
import cipher_analytical_machine.analyzers.caesar.IsNonsense;
|
|
import cipher_analytical_machine.ciphers.caesar.Decrypted;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.Map.Entry;
|
|
|
|
public class FrequencyAnalyzer {
|
|
private String ciphertext;
|
|
private String symbols;
|
|
private String symbol_frequences;
|
|
private Decrypted decryptor;
|
|
private IsNonsense isNonsense;
|
|
|
|
public FrequencyAnalyzer(String ciphertext, String symbols, String symbol_frequences, Decrypted decryptor, IsNonsense isNonsense) {
|
|
this.ciphertext = ciphertext;
|
|
this.symbol_frequences = symbol_frequences;
|
|
this.symbols = symbols;
|
|
this.decryptor = decryptor;
|
|
this.isNonsense = isNonsense;
|
|
}
|
|
|
|
public String crack() {
|
|
// Знаходимо кількість літер
|
|
Map<Character, Integer> encryptedLetterCounts = new HashMap<>();
|
|
|
|
for (char c : ciphertext.toLowerCase().toCharArray()) {
|
|
encryptedLetterCounts.put(c, encryptedLetterCounts.getOrDefault(c, 0) + 1);
|
|
}
|
|
|
|
// Знаходимо букву, яка зустрічається найчастіше
|
|
char mostFrequentEncryptedLetter = ' ';
|
|
int mostFrequentEncryptedLetterCount = 0;
|
|
|
|
for (Entry<Character, Integer> entry : encryptedLetterCounts.entrySet()) {
|
|
if (entry.getValue() > mostFrequentEncryptedLetterCount) {
|
|
mostFrequentEncryptedLetter = entry.getKey();
|
|
mostFrequentEncryptedLetterCount = entry.getValue();
|
|
}
|
|
}
|
|
|
|
// Обчислимо зміщення
|
|
int size = symbols.length();
|
|
int indexOfMostFrequentEncryptedLetter = symbols.indexOf(mostFrequentEncryptedLetter);
|
|
int indexOfMostFrequentLetter = symbols.indexOf(symbol_frequences.charAt(0));
|
|
int shift = (indexOfMostFrequentEncryptedLetter - indexOfMostFrequentLetter) % size;
|
|
|
|
return decryptor.decrypt(ciphertext, shift, symbols);
|
|
}
|
|
}
|
|
|