Skip to content

Instantly share code, notes, and snippets.

@JamesMarino
Created March 18, 2017 03:14
Show Gist options
  • Save JamesMarino/ae0aeee0d8daff14820212bb357acad8 to your computer and use it in GitHub Desktop.
Save JamesMarino/ae0aeee0d8daff14820212bb357acad8 to your computer and use it in GitHub Desktop.
Vigenere Breaker
"use strict";
function getIncidenceOfCoincidence(sequence) {
// Get frequency
let frequencyTable = {};
for (let letter of sequence) {
if (!frequencyTable.hasOwnProperty(letter)) {
frequencyTable[letter] = 1;
} else {
frequencyTable[letter]++;
}
}
let sum = 0;
// Go Over frequency table
for (let frequencyKey in frequencyTable) {
if (frequencyTable.hasOwnProperty(frequencyKey)) {
let lambda = frequencyTable[frequencyKey];
// Get frequency Sum
sum += (Math.pow(lambda, 2) - lambda);
}
}
let stringLength = sequence.length;
return (sum / (Math.pow(stringLength, 2) - stringLength));
};
(() => {
const vigereneString = "afcusooqbqgywvohgqiunuwvalvzoooqpngeyshqhkzmnwvsebuwvwptbquwcwabojzeuhbpdmldhhavtwvqjjbxbzimnqresifssniqgwszpwflhebmywhdwbzbgajarvkanmyhorevtpspdmfhbpavphhdalehozomawsjymbirawbuzoopprooopwsgwopqafhwykrqhqwbvrbsdqpkfawkuhriumnugwbbruhdwbgksokcagcbpprlbmqqflhknqnojkekrvgaaurgaanorgwjkvrgfawullbzabruaejighvqiqgfcjrmlhrpkulvcqhbuhwzaibifarwyxhekvchfdwxfifkiqgvooowplopewalbbwvpbkeppgksxqzertwiqyokdamy";
const vigereneStringLength = vigereneString.length;
const lengthMax = 10;
let results = {};
for (let length = 2; length < lengthMax; length++) {
// Initialise the object for length 2
results[length] = {};
let lengthCounter = 1;
while ((lengthCounter + 1) <= length) {
results[length][lengthCounter] = [];
lengthCounter++
}
lengthCounter = 1;
// Iterate over the string
for (let vigerenePosition = 0; vigerenePosition < vigereneStringLength; vigerenePosition++) {
// Reset
if (lengthCounter == length) {
lengthCounter = 1;
}
// Store
results[length][lengthCounter].push(vigereneString[vigerenePosition])
// Increase length
lengthCounter++;
}
}
// Print out
for (let resultKey in results) {
if (results.hasOwnProperty(resultKey)) {
console.log(`Result Key: ${resultKey - 1}`);
let sequence = results[resultKey];
for (let sequenceKey in sequence) {
if (sequence.hasOwnProperty(sequenceKey)) {
// Print Sequence
console.log(`Sequence ${sequenceKey}: ` + sequence[sequenceKey]);
// Get IC of each Sequence
let incidenceOfCoincidence = getIncidenceOfCoincidence(sequence[sequenceKey]);
console.log(`IC ${sequenceKey}: ${incidenceOfCoincidence}`);
}
}
console.log("\n");
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment