June 2018 Update
This commit is contained in:
parent
ba8067c3b7
commit
22f33d4004
5278 changed files with 84726 additions and 14379 deletions
|
|
@ -0,0 +1,119 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var encoded =
|
||||
"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"
|
||||
|
||||
var freq = [26]float64{
|
||||
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,
|
||||
}
|
||||
|
||||
func sum(a []float64) (sum float64) {
|
||||
for _, f := range a {
|
||||
sum += f
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func bestMatch(a []float64) int {
|
||||
sum := sum(a)
|
||||
bestFit, bestRotate := 1e100, 0
|
||||
for rotate := 0; rotate < 26; rotate++ {
|
||||
fit := 0.0
|
||||
for i := 0; i < 26; i++ {
|
||||
d := a[(i+rotate)%26]/sum - freq[i]
|
||||
fit += d * d / freq[i]
|
||||
}
|
||||
if fit < bestFit {
|
||||
bestFit, bestRotate = fit, rotate
|
||||
}
|
||||
}
|
||||
return bestRotate
|
||||
}
|
||||
|
||||
func freqEveryNth(msg []int, key []byte) float64 {
|
||||
l := len(msg)
|
||||
interval := len(key)
|
||||
out := make([]float64, 26)
|
||||
accu := make([]float64, 26)
|
||||
for j := 0; j < interval; j++ {
|
||||
for k := 0; k < 26; k++ {
|
||||
out[k] = 0.0
|
||||
}
|
||||
for i := j; i < l; i += interval {
|
||||
out[msg[i]]++
|
||||
}
|
||||
rot := bestMatch(out)
|
||||
key[j] = byte(rot + 65)
|
||||
for i := 0; i < 26; i++ {
|
||||
accu[i] += out[(i+rot)%26]
|
||||
}
|
||||
}
|
||||
sum := sum(accu)
|
||||
ret := 0.0
|
||||
for i := 0; i < 26; i++ {
|
||||
d := accu[i]/sum - freq[i]
|
||||
ret += d * d / freq[i]
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func decrypt(text, key string) string {
|
||||
var sb strings.Builder
|
||||
ki := 0
|
||||
for _, c := range text {
|
||||
if c < 'A' || c > 'Z' {
|
||||
continue
|
||||
}
|
||||
ci := (c - rune(key[ki]) + 26) % 26
|
||||
sb.WriteRune(ci + 65)
|
||||
ki = (ki + 1) % len(key)
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func main() {
|
||||
enc := strings.Replace(encoded, " ", "", -1)
|
||||
txt := make([]int, len(enc))
|
||||
for i := 0; i < len(txt); i++ {
|
||||
txt[i] = int(enc[i] - 'A')
|
||||
}
|
||||
bestFit, bestKey := 1e100, ""
|
||||
fmt.Println(" Fit Length Key")
|
||||
for j := 1; j <= 26; j++ {
|
||||
key := make([]byte, j)
|
||||
fit := freqEveryNth(txt, key)
|
||||
sKey := string(key)
|
||||
fmt.Printf("%f %2d %s", fit, j, sKey)
|
||||
if fit < bestFit {
|
||||
bestFit, bestKey = fit, sKey
|
||||
fmt.Print(" <--- best so far")
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
fmt.Println("\nBest key :", bestKey)
|
||||
fmt.Printf("\nDecrypted text:\n%s\n", decrypt(enc, bestKey))
|
||||
}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
{-# LANGUAGE TupleSections #-}
|
||||
import Data.List(transpose, nub, sort, maximumBy)
|
||||
import Data.Ord (comparing)
|
||||
import Data.Char (ord)
|
||||
import Data.Map (Map, fromListWith, toList, findWithDefault)
|
||||
|
||||
average :: Fractional a => [a] -> a
|
||||
average as = sum as / fromIntegral (length as)
|
||||
|
||||
-- Create a map from each entry in list to the number of occurrences of
|
||||
-- that entry in the list.
|
||||
countEntries :: Ord a => [a] -> Map a Int
|
||||
countEntries = fromListWith (+) . fmap (,1)
|
||||
|
||||
-- Break a string up into substrings of n chars.
|
||||
breakup :: Int -> [a] -> [[a]]
|
||||
breakup _ [] = []
|
||||
breakup n as =
|
||||
let (h, r) = splitAt n as
|
||||
in h:breakup n r
|
||||
|
||||
-- Dole out elements of a string over a n element distribution.
|
||||
distribute :: [a] -> Int -> [[a]]
|
||||
distribute as n = transpose $ breakup n as
|
||||
|
||||
-- The probability that members of a pair of characters taken randomly
|
||||
-- from a given string are equal.
|
||||
coincidence :: (Ord a, Fractional b) => [a] -> b
|
||||
coincidence str =
|
||||
let charCounts = snd <$> toList (countEntries str)
|
||||
strln = length str
|
||||
d = fromIntegral $ strln * (strln - 1)
|
||||
n = fromIntegral $ sum $ fmap (\cc -> cc * (cc-1)) charCounts
|
||||
in n / d
|
||||
|
||||
-- Use the average probablity of coincidence for all the members of
|
||||
-- a distribution to rate the distribution - the higher the better.
|
||||
-- The correlation increases artificially for smaller
|
||||
-- pieces/longer keys, so weigh against them a little
|
||||
rate :: (Ord a, Fractional b) => [[a]] -> b
|
||||
rate d = average (fmap coincidence d) - fromIntegral (length d) / 3000.0
|
||||
|
||||
-- Multiply elements of lists together and add up the results.
|
||||
dot :: Num a => [a] -> [a] -> a
|
||||
dot v0 v1 = sum $ zipWith (*) v0 v1
|
||||
|
||||
-- Given two lists of floats, rotate one of them by the number of
|
||||
-- characters indicated by letter and then 'dot' them together.
|
||||
rotateAndDot :: Num a => [a] -> [a] -> Char -> a
|
||||
rotateAndDot v0 v1 letter = dot v0 (drop (ord letter - ord 'A') (cycle v1))
|
||||
|
||||
-- Find decoding offset that results in best match
|
||||
-- between actual char frequencies and expected frequencies.
|
||||
getKeyChar :: RealFrac a => [a] -> String -> Char
|
||||
getKeyChar expected sample =
|
||||
let charCounts = countEntries sample
|
||||
countInSample c = findWithDefault 0 c charCounts
|
||||
actual = fmap (fromIntegral . countInSample) ['A'..'Z']
|
||||
in maximumBy (comparing $ rotateAndDot expected actual) ['A'..'Z']
|
||||
|
||||
main = do
|
||||
let cr = filter (/=' ') crypt
|
||||
-- Assume that if there are less than 20 characters
|
||||
-- per column, the key's too long to guess
|
||||
distributions = fmap (distribute cr) [1..length cr `div` 20]
|
||||
bestDistribution = maximumBy (comparing rate) distributions
|
||||
key = fmap (getKeyChar englishFrequencies) bestDistribution
|
||||
alphaSum a b = ['A'..'Z'] !! ((ord b - ord a) `mod` 26)
|
||||
mapM_ putStrLn ["Key: " ++ key, "Decrypted Text: " ++ zipWith alphaSum (cycle key) cr]
|
||||
|
||||
englishFrequencies =
|
||||
[ 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 ]
|
||||
|
||||
crypt = "\
|
||||
\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\
|
||||
\"
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
public class Vig{
|
||||
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";
|
||||
|
||||
final static double freq[] = {
|
||||
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
|
||||
};
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
int lenghtOfEncodedMessage = encodedMessage.length();
|
||||
char[] encoded = new char [lenghtOfEncodedMessage] ;
|
||||
char[] key = new char [lenghtOfEncodedMessage] ;
|
||||
|
||||
encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0);
|
||||
int txt[] = new int[lenghtOfEncodedMessage];
|
||||
int len = 0, j;
|
||||
|
||||
double fit, best_fit = 1e100;
|
||||
|
||||
for (j = 0; j < lenghtOfEncodedMessage; j++)
|
||||
if (Character.isUpperCase(encoded[j]))
|
||||
txt[len++] = encoded[j] - 'A';
|
||||
|
||||
for (j = 1; j < 30; j++) {
|
||||
fit = freq_every_nth(txt, len, j, key);
|
||||
System.out.printf("%f, key length: %2d ", fit, j);
|
||||
System.out.print(key);
|
||||
if (fit < best_fit) {
|
||||
best_fit = fit;
|
||||
System.out.print(" <--- best so far");
|
||||
}
|
||||
System.out.print("\n");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static String decrypt(String text, final String key) {
|
||||
String res = "";
|
||||
text = text.toUpperCase();
|
||||
for (int i = 0, j = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c < 'A' || c > 'Z') continue;
|
||||
res += (char)((c - key.charAt(j) + 26) % 26 + 'A');
|
||||
j = ++j % key.length();
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
static int best_match(final double []a, final double []b) {
|
||||
double sum = 0, fit, d, best_fit = 1e100;
|
||||
int i, rotate, best_rotate = 0;
|
||||
for (i = 0; i < 26; i++)
|
||||
sum += a[i];
|
||||
for (rotate = 0; rotate < 26; rotate++) {
|
||||
fit = 0;
|
||||
for (i = 0; i < 26; i++) {
|
||||
d = a[(i + rotate) % 26] / sum - b[i];
|
||||
fit += d * d / b[i];
|
||||
}
|
||||
|
||||
if (fit < best_fit) {
|
||||
best_fit = fit;
|
||||
best_rotate = rotate;
|
||||
}
|
||||
}
|
||||
|
||||
return best_rotate;
|
||||
}
|
||||
|
||||
static double freq_every_nth(final int []msg, int len, int interval, char[] key) {
|
||||
double sum, d, ret;
|
||||
double [] accu = new double [26];
|
||||
double [] out = new double [26];
|
||||
int i, j, rot;
|
||||
|
||||
for (j = 0; j < interval; j++) {
|
||||
for (i = 0; i < 26; i++)
|
||||
out[i] = 0;
|
||||
for (i = j; i < len; i += interval)
|
||||
out[msg[i]]++;
|
||||
rot = best_match(out, freq);
|
||||
try{
|
||||
key[j] = (char)(rot + 'A');
|
||||
} catch (Exception e) {
|
||||
System.out.print(e.getMessage());
|
||||
}
|
||||
for (i = 0; i < 26; i++)
|
||||
accu[i] += out[(i + rot) % 26];
|
||||
}
|
||||
|
||||
for (i = 0, sum = 0; i < 26; i++)
|
||||
sum += accu[i];
|
||||
|
||||
for (i = 0, ret = 0; i < 26; i++) {
|
||||
d = accu[i] / sum - freq[i];
|
||||
ret += d * d / freq[i];
|
||||
}
|
||||
|
||||
key[interval] = '\0';
|
||||
return ret;
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue