0
$\begingroup$

I have found interesting answer, written by GeneQ and now want to understand and implement it. I think, that first point of this answer can be rewritten in follwing way:

suppose we have n bytes of cipher text where $c_i=p_i\oplus {k_{i \mod keyLength}}, i=1,...,n.$

Then, to find $keyLength$ we should for $offsets =1,2,...$ do the follwing:

$offset = 1, c'_i=c_i\oplus{c_{i+offset}}, i =1,...,n$

$offset = 2, c'_i=c_i\oplus{c_{i+offset}}, i =1,...,n$

and so on. After than check how many bytes are the same. Let's save number of same bytes in $numOfIntersect$. Then if $c'_i=c_i$, numOfIntersect++.

Code for this simple algorithm:

byte[] key = new byte[] {48, 49, 50 };
            using (BinaryReader br = new BinaryReader(File.Open(path, FileMode.Open)))
            {
                byte[] plainText = new byte[br.BaseStream.Length];
                byte[] cipherText = new byte[br.BaseStream.Length];
                br.BaseStream.Read(plainText, 0, plainText.Length);
                for (int i = 0; i < plainText.Length; i++)
                    cipherText[i] = Convert.ToByte((int)plainText[i] ^ key[i % key.Length]);

                for (int offset = 1; offset <= 16; offset++)
                {
                    byte[] cipherTmpText = new byte[cipherText.Length - offset];
                    int numOfIntersect = 0;
                    for (int i = 0; (i + offset) < cipherText.Length; i++)
                        cipherTmpText[i] = Convert.ToByte((int)cipherText[i] ^ (int)cipherText[i + offset]);
                    for (int i = 0; i < cipherTmpText.Length; i++)
                        if (cipherText[i] == cipherTmpText[i])
                            numOfIntersect++;
                    Console.WriteLine("Offset - {0}, numOfIntersects - {1}", offset, numOfIntersect);
                }
            }

Well, this is result.

Can`t understand, what i am doing wrong.

$\endgroup$

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.