17 February 2013

New German Java Programming Blog

My last post is already several weeks old since I had to focus on university, but since I'm going to have more free time after February I decided to also start a second programming blog about Java. It's going to offer tutorials for the basics of Java at first but also offer information for intermediate programmers. I also decided to make a German website since it's my native language and writing German is much easier for me than English since writing German text is much more natural. So if you're a German who wants to learn Java, I suggest you check out my new site: Java Programmieren.

13 January 2013

How to break the Vigenere Cipher in Java, C++ and Visual Basic

After learning how to use the Vigenere Cipher, you might ask yourself: Is there a way to break it? The answer is yes. There are just some assumptions you have to make. First of all you have to know the length of the key that was used for the encryption. You also have to know the language of the plaintext. Furthermore, the text has to be long enough. For this example we also assume that the text consists only of upper case letters.
Recall what the Vigenere Cipher does. It shifts the letters of the plaintext based on the letters of a keyword. For example, imagine the keyword to be "MAGIC". Since the key is 5 letters long and the zero based index of the first letter of the key is 12, the first, sixth, eleventh, sixteenth etc. letter of the plaintext is shifted by 12 positions.
Now just consider the first, sixth, eleventh, sixteenth etc. letter of the plaintext. If the plaintext is long enough, the most frequent letter you find there is "E" (at least in English or German). Now if you take the first, sixth, eleventh, sixteenth etc. letter of the ciphertext, the most frequent letter out of them is "Q". Why? It's because the "E"s were shifted by 12 positions and became "Q"s. Or, using an equations:
 E + M = Q
If we use the zero based indices of the letters, we can also write this as:
 4 + 12= 16
This means that, in order to get the zero based index of the key character we are currently looking at, we have to subtract 4 from the index of the most frequent character in the letters of the ciphertext we are currently using. All this has to be performed for each letter of the key word.
Now we have to convert this into a program. The best thing is to first write a function that returns the index of the most frequent letter within a string. We'll later concatenate the characters of the ciphertext that were encrypted with the same key character and use this function to determine its most frequent letter index.

    int getMaxLet(String ciphertext){
        int lettersInAlphabet = 26;
        char[] alphabet = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        int[] letterCount = new int[26];
        int maxLetterCount = 0;
        byte indexOfHighestCount = 0;
       
        for(int i = 0;i<lettersInAlphabet;i++){
            letterCount[i] = 0;
        }
        for(int i = 0; i<ciphertext.length();i++){
            for(int j = 0; j<lettersInAlphabet;j++){
                if(ciphertext.charAt(i)==alphabet[j]){
                    letterCount[j]=letterCount[j]+1;
                    break;
                }
            }
        }
        for(byte i = 0; i<lettersInAlphabet;i++){
            if(letterCount[i]>maxLetterCount){
                indexOfHighestCount = i;
                maxLetterCount=letterCount[i];
            }
        }
        return indexOfHighestCount;
    }

Now we can write a function that determines the key word. The function takes the ciphertext and the key length as parameters. Then we determine step by step each character of the key word. In order to determine the first letter, we build a string consisting of the characters at the 0+k*keylength (zero based) positions of the ciphertext. To get the alphabet index of the most frequent letter within this string, we use our function from before. Considering our previous deliberations, we now have to subtract 4 from this number to get the alphabet index of the first character of the key word. Since the result might be negative, we add 26 and perform modulo 26.
For the second key character we only have to use the formula 1+k*keylength, for the third 2+k*keylength etc.

    String doBreak(String ciphertext, int keyLength){
        byte[] alphabet = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        String key = "";
        int ciphertextLength = ciphertext.length();
       
        for(int i = 0; i<keyLength;i++){
            String lettersAtMultiplesOfI = "";
            int currentIndex = i;
            while(currentIndex<ciphertextLength){
                lettersAtMultiplesOfI = lettersAtMultiplesOfI+ciphertext.charAt(currentIndex);
                currentIndex = currentIndex+keyLength;
            }
            int maxLetterIndex = getMaxLet(lettersAtMultiplesOfI);
            byte keyCharIndex = (byte)((maxLetterIndex-4+26)%26);
            key = key+(char)alphabet[keyCharIndex];
        }
        return key;
    }

You can decrypt the ciphertext using the key and my Implementation of the Vigenere Cipher.
Now you probably wonder: "Well this wasn't too difficult since we assumed that we know the length of the key word. But how the **** do we get the actual key length?" In order to get the key length you have to combine the Friedman and Kasiski test. I'll show you how to do this in the near future.

31 December 2012

How to print a christmas tree

When learning how to program, a common task around christmas is printing a christmas tree.


      *     
     ***    
    *****   
   *******  
  ********* 
 ***********
*************


The first thing you have to do is calculate the Width of the tree depending on its height. The formula you need for this is:
tree width = 1+2*(tree height-1)
For each "line" of the tree, you have to determine which char is " " and which is "*". As you can see, in the first line, only the char in the middle is a star. In the next line, it's the char in the middle as welle as the chars left and right from it etc. So the tree grows each line one char to the left and one char to the right.

        int treeHeight = 9;    
        int treeWidth = 1+2*(treeHeight-1);
        for(int i = 0;i<treeHeight;i++){
            String treeLine = "";
            for(int j = 0; j<treeWidth;j++){
                if(j<treeWidth/2-i || j>treeWidth/2+i){
                    treeLine = treeLine + " ";
                }else{
                    treeLine = treeLine + "*";
                }
            }
            System.out.println(treeLine);
        }


But your christmas tree also needs a trunk:


        int trunkHeight = 3;
        String trunkLine = "";
        for(int i = 0; i<treeWidth;i++){
            if(i<treeWidth/2-1 || i>treeWidth/2+1){
                trunkLine = trunkLine + " ";
            }else{
                trunkLine = trunkLine + "#";
            }
        }
        for(int i = 0;i<trunkHeight;i++){
            System.out.println(trunkLine);
        }


The christmas tree is finally ready. But it looks a little boring, so we add some random ornaments. Here's the complete program:


public class ChristmasTree {
    public static void main(String args[]){
        int treeHeight = 7;   
        int treeWidth = 1+2*(treeHeight-1);
        int trunkHeight = 3;
        for(int i = 0;i<treeHeight;i++){
            String treeLine = "";
            for(int j = 0; j<treeWidth;j++){
                if(j<treeWidth/2-i || j>treeWidth/2+i){
                    treeLine = treeLine + " ";
                }else{
                    if(Math.random()<0.15){
                        treeLine = treeLine + "x";
                    }else{
                        treeLine = treeLine + "*";
                    }
                }
            }
            System.out.println(treeLine);
        }
        String trunkLine = "";
        for(int i = 0; i<treeWidth;i++){
            if(i<treeWidth/2-1 || i>treeWidth/2+1){
                trunkLine = trunkLine + " ";
            }else{
                trunkLine = trunkLine + "#";
            }
        }
        for(int i = 0;i<trunkHeight;i++){
            System.out.println(trunkLine);
        }
    }
}

19 December 2012

Implementing the Vigenere Cipher in Java, Visual Basic and C++

Previously I implemented the Caesar Cipher in Java, vb.net and c++. You could say that the Vigenere Cipher is the Caesar Cipher taken to the next level. Instead of shiften each letter by the same fixed number, you use a key to determine by how much positions you shift each letter. Consider the plaintext "ATTACKATDAWN" and the key "LEMON". Since the zero based index of L in the alphabet is 11, you have to shift A by 11 positions, which again is L.

plaintext:   ATTACKATDAWN
key:           LEMONLEMONLE
ciphertext: LXFOPVEFRNHR

Translating the letters A-Z into the numbers 0-25, each character C of the ciphertext can be calculated like this:

Ci = (Pi + Ki) mod 26

Pi and Ki obviously stand for the corresponding characters/numbers of the plaintext and the key.

In order to encrypt a string using the Vigenere Cipher, you have to loop through every character in the plaintext, add it's index in the alphabet with the number of the corresponding key character. The result tells you the number of the ciphertext character. The solutions provided below assume that the plaintext only contains upper case letters.


    String encrypt(String plaintext, String key){
        int lettersInAlphabet = 26;
        char[] alphabet = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        int plaintextLength = plaintext.length();
        String ciphertext = "";
       
        for(int i=0; i<plaintextLength ; i++){
            byte keyCharIndex = 0;
            byte plaintextCharIndex = 0;
            for(byte j = 0; j<lettersInAlphabet;j++){
                if(key.charAt(i%key.length())==alphabet[j]){
                    keyCharIndex=j;
                    break;
                }
            }
            for(byte j = 0; j<lettersInAlphabet;j++){
                if(plaintext.charAt(i)==alphabet[j]){
                    plaintextCharIndex=j;
                    break;
                }
            }
            ciphertext = ciphertext + alphabet[(plaintextCharIndex+keyCharIndex)%26];
        }
        return ciphertext;
    }


The decryption works almost the same way, except that you have to substract the index of the key character from the index of the ciphertext character and add 26 instead of merely adding the index of the key character:



    String decrypt(String ciphertext, String key){
        int lettersInAlphabet = 26;
        char[] alphabet = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        int ciphertextLength = ciphertext.length();
        String plaintext = "";
       
        for(int i=0; i<ciphertextLength ; i++){
            byte keyCharIndex = 0;
            byte ciphertextCharIndex = 0;
            for(byte j = 0; j<lettersInAlphabet;j++){
                if(key.charAt(i%key.length())==alphabet[j]){
                    keyCharIndex=j;
                    break;
                }
            }
            for(byte j = 0; j<lettersInAlphabet;j++){
                if(ciphertext.charAt(i)==alphabet[j]){
                    ciphertextCharIndex=j;
                    break;
                }
            }
            plaintext = plaintext + alphabet[(ciphertextCharIndex-keyCharIndex+26)%26];
        }
        return plaintext;
    }

Now you might think that it's almost impossible to break the Vigenere Cipher since there unlimited key words you could use to encrypt your plaintext. But I'm going to show you how to break the Vigenere Cipher.

15 December 2012

Implementing Caesar Cipher in Java, C++ and VB.net and how to break it

The Caesar cipher is one of the simplest encryption ciphers. Understanding it will help you understand the Vigenere cipher. The Caesar cipher shifts ach letter in the plaintext by a letter some fixed number of positions down the alphabet. For example, with a shift of 5, A would become F, B would become G etc. An implementation of the Caesar Cipher might look like this:

    String encrypt(String plaintext, int shift){
        byte[] alphabet = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        String ciphertext ="";
        for(int i = 0; i<plaintext.length();i++){
            int charIndex = -1;
            for(int j = 0; j<alphabet.length;j++){
                if(plaintext.charAt(i)==alphabet[j]){
                    charIndex = j;
                    break;
                }
            }
            if(charIndex>-1){
                ciphertext = ciphertext + (char)alphabet[(charIndex+shift)%26];
            }else{
                ciphertext = ciphertext + plaintext.charAt(i);
            }
        }
        return ciphertext;
    }


As you can see you loop through every char of the plaintext, determine its index in the alphabet, add the given number to it and calculate modulo 26 since the result may be bigger than 25. The result is the index of the letter you have to take for the ciphertext. This implementation assumes that the characters are upper case letters only or else you take the same letter unaltered into the ciphertext.
The decryption works similar, but you have to apply a twist. Instead of adding the given number to the letter's index, you have to substract it. since the result could be smaller than 0, you first have to add 26 before calculating modulo 26:

    String decrypt(String ciphertext, int shift){
        byte[] alphabet = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        String plaintext ="";
        for(int i = 0; i<ciphertext.length();i++){
            int charIndex = -1;
            for(int j = 0; j<alphabet.length;j++){
                if(ciphertext.charAt(i)==alphabet[j]){
                    charIndex = j;
                    break;
                }
            }
            if(charIndex>-1){
                plaintext = plaintext + (char)alphabet[(charIndex-shift+26)%26];
            }else{
                plaintext = plaintext + plaintext.charAt(i);
            }
        }
        return plaintext;
    }


In order to break the Caesar Cipher, you have to determine the key of the encryption which means the number of positions you shift the letters by. Since there are only 26 possible keys, you could try each one and check whether the decrypted text makes sense. A better approach is to find the index of the most frequent letter in the text (will only work if the text is long enough) and compare it with the index of the most frequent letter in the language of the plaintext (assuming you know the language of the plaintext). Calsculate the difference of ciphertext's most frequent letter's index and the language's most frequent letter's index and add 26 if the result is negative. Now you have the key value.