Created
April 28, 2023 19:27
-
-
Save kamaci/7c2f79c13c6cd7610da26da1c71df47e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from tabulate import tabulate | |
from stats_collector import StatsCollector | |
import matplotlib.pyplot as plt | |
desired_ioc_value = 0.065 | |
random_ioc_value = 0.038 | |
class IndexOfCoincidence: | |
def __init__(self, cipher_statistics: StatsCollector): | |
self.cipher_statistics = cipher_statistics | |
self.ioc_map = {} | |
def find_length(self): | |
for m in range(1, 14): | |
substrings = self.substrings(m) | |
average_ioc = sum(self.calculate_ioc(y) for y in substrings) / m | |
self.ioc_map[m] = average_ioc | |
print(tabulate(self.ioc_map.items(), headers="firstrow", tablefmt="rounded_grid")) | |
self.plot() | |
def substrings(self, m): | |
return [ | |
"".join( | |
self.cipher_statistics.data[j] | |
for j in range(i, self.cipher_statistics.total_chars, m) | |
) | |
for i in range(m) | |
] | |
@staticmethod | |
def calculate_ioc(data): | |
print(data) | |
data_stats = StatsCollector(data) | |
data_stats.print_stats() | |
f = sum(v * v for v in data_stats.freq_dict.values()) | |
return f / (data_stats.total_chars * data_stats.total_chars) | |
def plot(self): | |
plt.bar(self.ioc_map.keys(), self.ioc_map.values()) | |
plt.axhline(y=desired_ioc_value, color='b', linestyle='-', label='Desired IoC') | |
plt.axhline(y=random_ioc_value, color='r', linestyle='-', label='Random IoC') | |
plt.errorbar(self.ioc_map.keys(), self.ioc_map.values(), | |
yerr=[abs(self.ioc_map[i] - desired_ioc_value) for i in self.ioc_map], fmt='.', ecolor='orange', | |
color='yellow', capsize=5) | |
plt.legend() | |
plt.xlabel("Key Length") | |
plt.ylabel("IoC") | |
plt.title("IoC Values for Random Key Length") | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment