Vigenère cipher/Cryptanalysis

From Rosetta Code
Revision as of 04:57, 4 June 2011 by rosettacode>MagiMaster (More specifications)
Vigenère cipher/Cryptanalysis is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text:

MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD
ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS
FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG
ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ
ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS
JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT
LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST
MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH
QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV
RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW
TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO
SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR
ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX
BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB
BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA
FWAML ZZRXJ EKAHV FASMU LVVUT TGK

Letter frequencies for English can be found here.

Specifics for this task:

  • Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace.
  • Assume the plaintext is written in English.
  • Find and output the key.
  • Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional.
  • The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm.

C++

Not guaranteed to give a 100% correct answer, but it works here.

<lang cpp>#include <iostream>

  1. include <string>
  2. include <vector>
  3. include <map>
  4. include <algorithm>

using namespace std;

class VigenereAnalyser { public:

 vector<double> targets;
 vector<double> sortedTargets;
 VigenereAnalyser(vector<double> targetFreqs)
 {
   targets = targetFreqs;
   sortedTargets = targets;
   sort(sortedTargets.begin(), sortedTargets.end());
 }
 vector<pair<char, double>> frequency(string input)
 {
   vector<pair<char, double>> out;
   for(char c = 'A'; c <= 'Z'; ++c)
     out.push_back(make_pair(c, 0));
   for(int i = 0; i < input.size(); ++i)
     ++out[input[i] - 'A'].second;
   return out;
 }
 double correlation(string input)
 {
   double out = 0.0;
   vector<pair<char, double>> freq = frequency(input);
   sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool
     { return u.second < v.second; });
   for(int i = 0; i < 26; ++i)
     out += freq[i].second * sortedTargets[i];
   return out;
 }
 pair<string, string> analyze(string input)
 {
   string cleaned;
   for(int i = 0; i < input.size(); ++i)
   {
     if(input[i] >= 'A' && input[i] <= 'Z')
       cleaned += input[i];
     else if(input[i] >= 'a' && input[i] <= 'z')
       cleaned += input[i] + 'A' - 'a';
   }
   string out;
   string key;
   int bestLength = 0;
   double bestCorr = -100.0;
   // Assume that if there are less than 20 characters per column, the key's too long to guess
   for(int i = 2; i < cleaned.size()/20; ++i)
   {
     vector<string> pieces(i);
     for(int j = 0; j < cleaned.size(); ++j)
       pieces[j % i] += cleaned[j];
     // The correlation seems to increase for smaller pieces/longer keys, so weigh against them a little
     double corr = -0.5*i;
     for(int j = 0; j < i; ++j)
       corr += correlation(pieces[j]);
     if(corr > bestCorr)
     {
       bestLength = i;
       bestCorr = corr;
     }
   }
   if(bestLength == 0)
     return make_pair("Text is too short to analyze", "");
   vector<string> pieces(bestLength);
   for(int i = 0; i < cleaned.size(); ++i)
     pieces[i % bestLength] += cleaned[i];
   vector<vector<pair<char, double>>> freqs;
   for(int i = 0; i < bestLength; ++i)
     freqs.push_back(frequency(pieces[i]));
   key = "";
   out = "";
   for(int i = 0; i < bestLength; ++i)
   {
     sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool
       { return u.second > v.second; });
     int m = 0;
     double corr, mCorr = 0.0;
     for(int j = 0; j < 26; ++j)
     {
       corr = 0.0;
       char c = 'A' + j;
       for(int k = 0; k < 26; ++k)
       {
         int d = (freqs[i][k].first - c + 26) % 26;
         corr += freqs[i][k].second * targets[d];
       }
       if(corr > mCorr)
       {
         m = j;
         mCorr = corr;
       }
     }
     key += m + 'A';
   }
   for(int i = 0; i < cleaned.size(); ++i)
     out += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';
   return make_pair(out, key);
 }

};

int main() {

 string input = 
   "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH"
   "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD"
   "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS"
   "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG"
   "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ"
   "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS"
   "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT"
   "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST"
   "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH"
   "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV"
   "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW"
   "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO"
   "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR"
   "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX"
   "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB"
   "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA"
   "FWAML ZZRXJ EKAHV FASMU LVVUT TGK";
 double fs[] = {0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 
   0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074};
 vector<double> english(&fs[0], &fs[26]);
 VigenereAnalyser va(english);
 pair<string, string> output = va.analyze(input);
 cout << "Key: " << output.second << endl << endl;
 cout << "Text: " << output.first << endl;

}</lang>