Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- string readFile(const string& fileName)
- {
- ifstream inFile(fileName, ifstream::binary);
- if (!inFile.is_open()) {
- cerr << "Error: Cannot open " << fileName << endl;
- exit(EXIT_FAILURE);
- }
- string cipherText = string((istreambuf_iterator<char>(inFile)), istreambuf_iterator<char>());
- // erasing special symbols from cipher text
- cipherText.erase(std::remove(cipherText.begin(), cipherText.end(), '\r'));
- cipherText.erase(std::remove(cipherText.begin(), cipherText.end(), '\n'));
- return cipherText;
- }
- string getTruncText(const string& cipherText, int d, int off = 0)
- {
- string cipherTextBuf;
- int ctr = 0;
- for (const auto &ch : cipherText.substr(off)) {
- if (ch != '\n') {
- if (ctr++ % d == 0) {
- cipherTextBuf += ch;
- }
- }
- }
- return cipherTextBuf;
- }
- map<char, int> calcFrequency(const string &cipherText)
- {
- map<char, int> frequency;
- for (const auto &ch : cipherText)
- frequency[ch]++;
- return frequency;
- }
- double getDelta(map<char, double> frequencyAlphabet)
- {
- double delta = 0.0;
- for (auto [key, value] : frequencyAlphabet)
- delta += value * value;
- return delta;
- }
- void methodFriedman_2(const string &fileName, int keyLen, bool isLog)
- {
- auto cipherText = readFile(fileName);
- // array, where stored truncated text, based on key len
- vector<string> stringArr;
- // splitting cipher text to keyLen pieces
- for (size_t i = 0; i < keyLen; i++)
- stringArr.push_back(getTruncText(cipherText, keyLen, i));
- auto str0Freq = calcFrequency(stringArr[0]);
- auto str0Size = stringArr[0].size();
- vector<int> offsetArr;
- auto delta = getDelta(g_frequencyAlphabet);
- // finding maximum mutual coincidence index and minimal offset
- for (size_t strNum = 1; strNum < stringArr.size(); strNum++) {
- double minDiff = 1.0;
- int minOffset = 0;
- for (size_t offset = 0; offset < g_alphabet.size(); offset++) {
- auto curStr = offsetCipher(stringArr[strNum], offset, g_alphabet);
- auto strSize = curStr.size();
- auto trunkFreq = calcFrequency(curStr);
- double sumFreq = 0.0;
- for (const auto &symbol : g_alphabet)
- sumFreq += str0Freq[symbol] * trunkFreq[symbol];
- double mutualCoincidenceIndex = sumFreq / (str0Size * strSize);
- double diff = fabs(delta - mutualCoincidenceIndex);
- if (diff < minDiff) {
- minDiff = diff;
- minOffset = offset;
- }
- }
- offsetArr.push_back(minOffset);
- }
- vector<int> key(keyLen);
- vector<vector<int>> keyArr;
- for (size_t key0 = 0; key0 <= g_alphabet.size(); key0++) {
- key[0] = key0;
- for (size_t i = 1; i < key.size(); i++)
- key[i] = (key0 - offsetArr[i - 1]) % g_alphabet.size();
- keyArr.push_back(key);
- for (auto el : key)
- cout << el << " ";
- cout << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement