Vigenère cipher/Cryptanalysis: Difference between revisions

Content added Content deleted
No edit summary
m (syntax highlighting fixup automation)
Line 33: Line 33:
{{trans|Python}}
{{trans|Python}}


<lang 11l>-V ascii_uppercase = Array(‘A’..‘Z’)
<syntaxhighlight lang="11l">-V ascii_uppercase = Array(‘A’..‘Z’)


F vigenere_decrypt(target_freqs, input)
F vigenere_decrypt(target_freqs, input)
Line 125: Line 125:
V (key, decoded) = vigenere_decrypt(english_frequences, encoded)
V (key, decoded) = vigenere_decrypt(english_frequences, encoded)
print(‘Key: ’key)
print(‘Key: ’key)
print("\nText: "decoded)</lang>
print("\nText: "decoded)</syntaxhighlight>


{{out}}
{{out}}
Line 136: Line 136:
=={{header|Ada}}==
=={{header|Ada}}==
The program is not fully auto, but makes a small number of suggestions for the right key and plaintext.
The program is not fully auto, but makes a small number of suggestions for the right key and plaintext.
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure Vignere_Cryptanalysis is
procedure Vignere_Cryptanalysis is
Line 302: Line 302:
end;
end;
end loop;
end loop;
end Vignere_Cryptanalysis;</lang>
end Vignere_Cryptanalysis;</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
This finds the right key (I think, I didn't try to decode it after getting the key). The program is not fully auto, but by its output, the result is pretty obvious.
This finds the right key (I think, I didn't try to decode it after getting the key). The program is not fully auto, but by its output, the result is pretty obvious.
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 408: Line 408:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Not guaranteed to give a 100% correct answer, but it works here. Requires C++0x.
Not guaranteed to give a 100% correct answer, but it works here. Requires C++0x.


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <string>
#include <vector>
#include <vector>
Line 579: Line 579:
cout << "Key: " << output.second << endl << endl;
cout << "Key: " << output.second << endl << endl;
cout << "Text: " << output.first << endl;
cout << "Text: " << output.first << endl;
}</lang>
}</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
{{trans|C++}}
{{trans|C++}}
<lang d>import std.stdio, std.algorithm, std.typecons, std.string,
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.string,
std.array, std.numeric, std.ascii;
std.array, std.numeric, std.ascii;


Line 714: Line 714:
immutable key_dec = vigenereDecrypt(englishFrequences, encoded);
immutable key_dec = vigenereDecrypt(englishFrequences, encoded);
writefln("Key: %s\n\nText: %s", key_dec[0], key_dec[1]);
writefln("Key: %s\n\nText: %s", key_dec[0], key_dec[1]);
}</lang>
}</syntaxhighlight>
{{out|Output (cut)}}
{{out|Output (cut)}}
<pre>Key: THECHESHIRECAT
<pre>Key: THECHESHIRECAT
Line 722: Line 722:
=={{header|Go}}==
=={{header|Go}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 840: Line 840:
fmt.Println("\nBest key :", bestKey)
fmt.Println("\nBest key :", bestKey)
fmt.Printf("\nDecrypted text:\n%s\n", decrypt(enc, bestKey))
fmt.Printf("\nDecrypted text:\n%s\n", decrypt(enc, bestKey))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 890: Line 890:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>{-# LANGUAGE TupleSections #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE TupleSections #-}
import Data.List(transpose, nub, sort, maximumBy)
import Data.List(transpose, nub, sort, maximumBy)
import Data.Ord (comparing)
import Data.Ord (comparing)
Line 987: Line 987:
\BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\
\BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\
\FWAML ZZRXJ EKAHV FASMU LVVUT TGK\
\FWAML ZZRXJ EKAHV FASMU LVVUT TGK\
\"</lang>
\"</syntaxhighlight>
{{out}}
{{out}}
<pre style="font-size:80%">
<pre style="font-size:80%">
Line 997: Line 997:
{{trans|C}}
{{trans|C}}


<lang Java>public class Vig{
<syntaxhighlight lang="java">public class Vig{
static String encodedMessage =
static String encodedMessage =
"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";
"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";
Line 1,105: Line 1,105:
}
}
</syntaxhighlight>
</lang>


=={{header|Julia}}==
=={{header|Julia}}==


<lang Julia># ciphertext block {{{1
<syntaxhighlight lang="julia"># ciphertext block {{{1
const ciphertext = filter(isalpha, """
const ciphertext = filter(isalpha, """
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
Line 1,315: Line 1,315:
gc()
gc()
t = @elapsed cryptanalyze(ciphertext)
t = @elapsed cryptanalyze(ciphertext)
println("\nelapsed time: ", t, " seconds")</lang>
println("\nelapsed time: ", t, " seconds")</syntaxhighlight>


{{out}}
{{out}}
Line 1,328: Line 1,328:
{{trans|C}}
{{trans|C}}
This is a reasonably faithful translation of the C entry though I've restricted the key lengths examined to 26 to automatically produce the correct key and hence decrypted text. This is because the C entry examines key lengths up to 29 and a value of 28 gives a slightly better fit even though the key produced (THECHESCIRECATTHECHESHIRECAT) and resulting text don't make as much sense and so would be rejected if one were examining the candidate keys manually.
This is a reasonably faithful translation of the C entry though I've restricted the key lengths examined to 26 to automatically produce the correct key and hence decrypted text. This is because the C entry examines key lengths up to 29 and a value of 28 gives a slightly better fit even though the key produced (THECHESCIRECATTHECHESHIRECAT) and resulting text don't make as much sense and so would be rejected if one were examining the candidate keys manually.
<lang scala>// version 1.1.3
<syntaxhighlight lang="scala">// version 1.1.3


val encoded =
val encoded =
Line 1,429: Line 1,429:
println("Best key : $bestKey")
println("Best key : $bestKey")
println("\nDecrypted text:\n${decrypt(enc, bestKey)}")
println("\nDecrypted text:\n${decrypt(enc, bestKey)}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,471: Line 1,471:
{{trans|Phix}}
{{trans|Phix}}
This is a translation of Julia algorithm with some ideas from Phix translation.
This is a translation of Julia algorithm with some ideas from Phix translation.
<lang Nim>import sequtils, strutils, sugar, tables, times
<syntaxhighlight lang="nim">import sequtils, strutils, sugar, tables, times


const
const
Line 1,573: Line 1,573:
echo "key: ", key, '\n'
echo "key: ", key, '\n'
echo dec, '\n'
echo dec, '\n'
echo "Elapsed time: ", (cpuTime() - t0).formatFloat(ffDecimal, precision = 3), " s"</lang>
echo "Elapsed time: ", (cpuTime() - t0).formatFloat(ffDecimal, precision = 3), " s"</syntaxhighlight>


{{out}}
{{out}}
Line 1,587: Line 1,587:
Uses the Vigenere decrypt function from the Vigenere task solution (not included in the code below).
Uses the Vigenere decrypt function from the Vigenere task solution (not included in the code below).
{{works with|OCaml|above 4.05}}
{{works with|OCaml|above 4.05}}
<syntaxhighlight lang="ocaml">
<lang OCaml>
(* Task : Vigenere cipher/Cryptanalysis *)
(* Task : Vigenere cipher/Cryptanalysis *)


Line 1,709: Line 1,709:
Printf.printf "Key: %s\n\nText: %s" key pt
Printf.printf "Key: %s\n\nText: %s" key pt
;;
;;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,718: Line 1,718:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use feature 'say';
use feature 'say';
Line 1,823: Line 1,823:
"Key length " . length($key) . "\n" .
"Key length " . length($key) . "\n" .
"Plaintext " . substr(mycrypt($text, $key), 0, 80) . "...\n";
"Plaintext " . substr(mycrypt($text, $key), 0, 80) . "...\n";
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,848: Line 1,848:
=={{header|Phix}}==
=={{header|Phix}}==
{{trans|Julia}}
{{trans|Julia}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Cryptanalysis.exw
-- demo\rosetta\Cryptanalysis.exw
Line 2,060: Line 2,060:
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,082: Line 2,082:
=={{header|Python}}==
=={{header|Python}}==
{{trans|D}}
{{trans|D}}
<lang python>from string import uppercase
<syntaxhighlight lang="python">from string import uppercase
from operator import itemgetter
from operator import itemgetter


Line 2,187: Line 2,187:
print "\nText:", decoded
print "\nText:", decoded


main()</lang>
main()</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 2,194: Line 2,194:
This is a simple method that just tries to find a key of any length that minimizes the difference from the expected English character distributions.
This is a simple method that just tries to find a key of any length that minimizes the difference from the expected English character distributions.


<syntaxhighlight lang="racket">
<lang Racket>
#lang at-exp racket
#lang at-exp racket


Line 2,266: Line 2,266:
(display (integer->char (+ first-char (decode-num n))))))
(display (integer->char (+ first-char (decode-num n))))))
(newline)
(newline)
</syntaxhighlight>
</lang>


Output:
Output:
Line 2,279: Line 2,279:
This is an attempt at following the [http://en.wikipedia.org/wiki/Index_of_coincidence#Example Wikipedia] description. However, it performs just as well as the simple version. Most likely because I know almost nothing about cryptography...
This is an attempt at following the [http://en.wikipedia.org/wiki/Index_of_coincidence#Example Wikipedia] description. However, it performs just as well as the simple version. Most likely because I know almost nothing about cryptography...


<syntaxhighlight lang="racket">
<lang Racket>
#lang at-exp racket
#lang at-exp racket


Line 2,385: Line 2,385:
(display (integer->char (+ first-char (decode-num n))))))
(display (integer->char (+ first-char (decode-num n))))))
(newline)
(newline)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{trans|Perl}}
{{trans|Perl}}
<lang perl6># from Wikipedia
<syntaxhighlight lang="raku" line># from Wikipedia
constant %English-letter-freq = (
constant %English-letter-freq = (
E => 12.70, L => 4.03, Y => 1.97, P => 1.93, T => 9.06, A => 8.17, O => 7.51, I => 6.97, N => 6.75,
E => 12.70, L => 4.03, Y => 1.97, P => 1.93, T => 9.06, A => 8.17, O => 7.51, I => 6.97, N => 6.75,
Line 2,482: Line 2,482:
"Key length {$key.chars}\n" ~
"Key length {$key.chars}\n" ~
"Plaintext {substr(mycrypt($cipher-text, $key), 0, 80)}...\n";
"Plaintext {substr(mycrypt($cipher-text, $key), 0, 80)}...\n";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Key THECHESHIRECAT
<pre>Key THECHESHIRECAT
Line 2,507: Line 2,507:
{{trans|Kotlin}}
{{trans|Kotlin}}
Note that the character to/from byte ('''u8''') conversions work here only because the key and cryptogram are composed of ASCII characters only. Indeed, Rust's '''char''' type is a ''Unicode scalar value'', how they are represented is well summarized in the Rust book's [https://doc.rust-lang.org/std/primitive.char.html subchapter on strings].
Note that the character to/from byte ('''u8''') conversions work here only because the key and cryptogram are composed of ASCII characters only. Indeed, Rust's '''char''' type is a ''Unicode scalar value'', how they are represented is well summarized in the Rust book's [https://doc.rust-lang.org/std/primitive.char.html subchapter on strings].
<syntaxhighlight lang="rust">
<lang Rust>
use std::iter::FromIterator;
use std::iter::FromIterator;


Line 2,617: Line 2,617:
println!("\nDecrypted text:\n{}", decrypt(&enc, &best_key));
println!("\nDecrypted text:\n{}", decrypt(&enc, &best_key));
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,628: Line 2,628:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{trans|Python}}
{{trans|Python}}
<lang tcl>package require Tcl 8.6
<syntaxhighlight lang="tcl">package require Tcl 8.6


oo::class create VigenereAnalyzer {
oo::class create VigenereAnalyzer {
Line 2,745: Line 2,745:
return [my GetKeyFromFreqs $freqs]
return [my GetKeyFromFreqs $freqs]
}
}
}</lang>
}</syntaxhighlight>
Demonstration (that assumes that the Tcl solution to [[Vigenère cipher#Tcl|Vigenère cipher]] task is present):
Demonstration (that assumes that the Tcl solution to [[Vigenère cipher#Tcl|Vigenère cipher]] task is present):
<lang tcl>set encoded "
<syntaxhighlight lang="tcl">set encoded "
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD
VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD
Line 2,771: Line 2,771:
set decoded [decoder decrypt $encoded]
set decoded [decoder decrypt $encoded]
puts "Key: $key"
puts "Key: $key"
puts "Text: $decoded"</lang>
puts "Text: $decoded"</syntaxhighlight>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
Line 2,787: Line 2,787:
If this does not solve some encrypted text, you could increase the number of key combinations to be checked.
If this does not solve some encrypted text, you could increase the number of key combinations to be checked.


<lang vedit>// (1) Copy text into tmp buffer and remove non-alpha chars.
<syntaxhighlight lang="vedit">// (1) Copy text into tmp buffer and remove non-alpha chars.


Chdir(PATH_ONLY)
Chdir(PATH_ONLY)
Line 3,103: Line 3,103:
BOL
BOL
#37 = Search_Block("|V", Cur_Pos, EOL_Pos, ALL+NOERR)
#37 = Search_Block("|V", Cur_Pos, EOL_Pos, ALL+NOERR)
Return </lang>
Return </syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|Go}}
{{trans|Go}}
<lang vlang>import strings
<syntaxhighlight lang="vlang">import strings
const encoded =
const encoded =
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" +
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" +
Line 3,220: Line 3,220:
println("\nBest key : $best_key")
println("\nBest key : $best_key")
println("\nDecrypted text:\n${decrypt(enc, best_key)}")
println("\nDecrypted text:\n${decrypt(enc, best_key)}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,275: Line 3,275:
{{libheader|Wren-str}}
{{libheader|Wren-str}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/math" for Nums
<syntaxhighlight lang="ecmascript">import "/math" for Nums
import "/trait" for Stepped
import "/trait" for Stepped
import "/str" for Char, Str
import "/str" for Char, Str
Line 3,379: Line 3,379:
System.print()
System.print()
System.print("Best key : %(bestKey)")
System.print("Best key : %(bestKey)")
System.print("\nDecrypted text:\n%(decrypt.call(enc, bestKey))")</lang>
System.print("\nDecrypted text:\n%(decrypt.call(enc, bestKey))")</syntaxhighlight>


{{out}}
{{out}}
Line 3,419: Line 3,419:
=={{header|zkl}}==
=={{header|zkl}}==
{{trans|Python}}
{{trans|Python}}
<lang zkl>var[const] uppercase=["A".."Z"].pump(String),
<syntaxhighlight lang="zkl">var[const] uppercase=["A".."Z"].pump(String),
english_frequences=T( // A..Z
english_frequences=T( // A..Z
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
Line 3,480: Line 3,480:
}).concat() :
}).concat() :
T(key,_);
T(key,_);
}</lang>
}</syntaxhighlight>
<lang zkl>encryptedText:=
<syntaxhighlight lang="zkl">encryptedText:=
#<<<
#<<<
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
Line 3,503: Line 3,503:
key,decoded:=vigenere_decrypt(english_frequences,encryptedText);
key,decoded:=vigenere_decrypt(english_frequences,encryptedText);
println("Key:", key);
println("Key:", key);
println("Decoded text:", decoded);</lang>
println("Decoded text:", decoded);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>