10 Replies Latest reply: Sep 12, 2009 3:26 PM by 843853 RSS

    Encryption program

    843853
      I have developed several of my own unique code languages that I want to expand my uses for. They appear complicated, but they are actually simple replacement style codes in which some logic is involved in their making. I find them very useful, however, one problem is that whenever I want to translate some text into a code, it takes a long time to do it by hand. It even takes a long time if I know the translation rules by memory. That is why I want to make a Java program to help me out:

      I started experimenting a long time ago with how to make such a program. I did not get very far at that time because I did not know enough about Java yet. Today, I know quite a bit more, but not enough to make the program like I would really like it. This is how I want it to work:

      The program will be made using BreezySwing GUI. One major thing that must be true in my program is that it must be simple. BreezySwing does this very nicely. There is no need for multiple classes, AWT, event listeners or any other complicated things. Even if you do not know anything about BreezySwing, it should not matter because I have already done all the work I needed to with BreezySwing (lay out the window). The rest of the program (the encryption syntax), should not have to deal with any of the BreezySwing methods. Back to the program, the window will contain two text area objects with a button in between (see source code below). The user will interact with the program by typing whatever they want into the upper text area. Once they are finished, and it is just like they want it, they will click the button in the middle of the window. This action will activate the encryption method which will first evaluate the user's input and then display the coded text in the lower text area. Below is the source code for the development program:
      import javax.swing.*;
      import BreezySwing.*; 
      public class KeyTranslator extends GBFrame {
           
           JTextArea inputArea,outputArea;
           JButton translateBtn = addButton("Translate",2,1,1,1);
           private String input = "",output = "";
           public KeyTranslator(){
                String ini = Format.justify('l',"",1);
                inputArea = addTextArea(ini,1,1,1,1);
                outputArea = addTextArea(ini,3,1,1,1);
                setTitle("KeyTranslator Ver. [development]");
           }
           public void buttonClicked(JButton bobj){
                input = inputArea.getText();
                if (bobj == translateBtn)
                     translateInput();
           }
           /*translation method*/
           private void translateInput(){
                //this is where the translation syntax goes
           }
          
          static public void main(String[] args) {
               KeyTranslator obj = new KeyTranslator();
               obj.setSize(400,300);
               obj.setVisible(true);
          }
      }
      Compile and run the above source code on your computer to see what the window looks like. When the program is functional, the window should not change. The only thing that I want to change in this program, is what is in the translateInput() method.

      Here is what I think might work for the syntax for this program:
      *1. Find and replace*
      I got this idea from the find and replace feature that some IDEs have. My program might be able to utilize this type of coding process. This is how it could work:
      Each individual letter, number, symbol, and space in the user's input could be evaluated for matches with a certain letter, number, or symbol. When the program finds matches, it could begin to replace the matches with the corresponding code for that letter, number, or symbol.
      *2. Scan each character*
      Another possibility is a type of scanning of the text. Somehow, each character within the user input would have to be evaluated based on a set of if-else statements that would contain the 'key' for the code. For example, if the user's input was:
      "hello", the program would evaluate each letter in the same order as it appears. It would then add the coded "hello" to a String variable which would eventually be displayed back to the user.
      Possible leads:
      While examining my possibilities, I carefully read through the methods for the classes String and Character. Some methods appealed, but I did not find any uses for them. The methods in these classes may be the solution.

      I only need help in designing the syntax for the encryption method. The rest of the program is just how I want it. I appreciate any positive encouragement.
      Remember, it should be kept as simple as possible.
        • 1. Re: Encryption program
          843853
          bengal513 wrote:
          I appreciate any positive encouragement.
          It is difficult for me to see what you are trying to get us to do. You have created a GUI (which I can't run because I don't have a needed library) and you have developed some "unique code languages" which we can't help with since you have not posted the code and you want help in plumbing this snake-oil that we can't see into code we (or at least I) can't run. What am I missing?

          Forget creating your own encryption algorithms. Use one or more of the well tested, well designed, well implement standard algorithms such a AES or Blowfish possibly using PBE to turn a passphrase into a key.
          • 2. Re: Encryption program
            843853
            I see that this topic needs some more details; starting with a code language. I will use my simplest one, which incorporates the use of special number combinations that correspond to letters, prefixes, and special letter combinations. This code uses all single digit numbers (1-9 and 0).

            Prefixes:
            -All proper names are preceded by the combination: 30
            -All abbreviations are preceded by the combination: 20
            Combinations:
            -Any pair of letters (aa, bb, cc, dd, ee and so on) has special meaning. The second letter in a pair of letters is replaced with the combination: 10 (see examples below)
            Standard alphabet:
            A 5
            B 6
            C 7
            D 8
            E 9
            F 01
            G 02
            H 03
            I 04
            J 11
            K 12
            L 13
            M 14
            N 21
            O 22
            P 23
            Q 24
            R 31
            S 32
            T 33
            U 34
            V 41
            W 42
            X 43
            Y 44
            Z 00

            See the pattern and rules? This code is actually very simple. It incorporates the use of all single digit numbers. The only combination that currently has no use or meaning is 40 (all other combinations like 42 are read as "four two"; not "forty two"). Combinations with the digits 5, 6, 7, 8, and 9 are not possible because they are reserved as non-paired combinations which correspond to the first five letters of the alphabet without the need for any other numbers. Another feature of the code is that it is not case differentiating. Both 'A' and 'a' both correspond with '5'. If you still do not see how it works, here are some example words:
            [as you read the examples, if you see the numbers 5, 6, 7, 8, or 9, you can make a letter out of them alone. otherwise, if you see a 1, 2, 3, or 4, you must read the number to the right of it in order to make a letter]

            Hello 039131022 (with each pair seperated, it looks like this: 03 9 13 10 22, however, it is never written like this)
            Computer 72214233433931
            do you see how this code works? 822 442234 32910 032242 33030432 72289 4222311232?

            It takes me about ten seconds to type up the last example sentence because I already know this code by memory.

            Now incorporate this into my program. This is how I would want it to work:

            Say for example, the user enters the following into the first text area (without the quotes):
            "Your goal should be out of reach, but not out of sight."

            This is the text that the user wants the program to convert to code (using the alphabet and rules shown above). The user will activate the translator method by clicking a GUI button. The program will convert the entire sentence first, and then display the whole thing all at once to the user. When displayed in the second text area, it should look like this (without the quotes):
            "44223431 0222513 32032234138 69 223433 2201 3195703, 63433 212233 223433 2201 3204020333."

            P.S.
            For anybody that wants to see my program's window, but cannot because they do not have the BreezySwing .jar file, you can get it here:
            http://faculty.cs.wwu.edu/martin/Software%20Packages/BreezySwing/breezyhome.htm
            Go here for method and object uses:
            http://www.ccsd.edu/south/math/nickels/Breezyswing/index.htm
            • 3. Re: Encryption program
              843853
              Sorry but I had to stop reading that. I was loosing the will to live.
              • 4. Re: Encryption program
                843853
                OK, I'm definitely not going to read all that, but I at least understand now that by code you mean a cypher.

                Anyway what I would do is your "scan" alternative but instead of using a serious of if-blocks, populate a map with what each plaintext character's corresponding cyphertext characters are:
                Map subs;
                private void populateSubstitutions() {
                   subs = new HashMap<String, String>();
                   subs.put('A', "5");
                   // ... SNIP ...
                   subs.put('Z', "00");
                }
                
                // ... SNIP ...
                public String encrypt(String input) {
                   StringBuffer cypherText = new StringBuffer();
                   //for each character c in input
                  cypherText.append(subs.get(c));
                  return cypherText.toString();
                }
                If you want to do one better, populate your substitution map from an externally specified file so that you can use different codes.
                • 5. Re: Encryption program
                  843853
                  This is really complicated; not what I was expecting, but I see where some logic comes into this. One problem is that I do not know anything about the Map, HashMap or StringBuffer classes so if I would want to troubleshoot this, I would have to first learn some things about these classes.

                  I am not even sure if I used the code properly as the compiler error messages said that it could not find the classes Map or HashMap.

                  I will try yet again to simplify the program and start with the basics:
                  Forget about the use of prefixes and special rules; just stick to the standard alphabet.

                  It may be possible to base a simpler version of the program on the pseudocode shown below. I created it by putting forth the easiest possible solution. I know that this code is not worthy of being correct, but perhaps a few changes could make it work:
                  /*
                  //within the encryption method, called translateInput(), activated by the BreezySwing buttonClicked method...
                  private void translateInput(){
                  input = inputArea.getText();        //now the String variable input has the value of whatever the user input is
                  int length = input.length();    //get the length for the user input
                  
                  //start scanning each letter based on its position
                  //e.g. the user's input is "java"
                  //'j' is position 1, 'a' is position 2, 'v' is position 3, and 'a' is position 4; the position variable would be assigned to each character with some method (see bottom)
                  //the variable position could be controlled by a count-controlled for loop all the way to the length of the String input
                  if (position == 'a' || position == 'A')
                  output += "5";
                  else if (position == 'b' || position == 'B')
                  output += "6";
                  //and so on, all the way to z; then include other character options like space, comma, period, question, etc...
                  
                  //since the loop should be controlling how the string is read, the text will appear in order when displayed
                  outputArea.setText(output);
                  }
                  */
                  I scanned the methods in the String and Character classes. Within the String class, I found a method called toCharArray() which does something similar to the imaginary position variable in the pseudocode:
                  String letters = "abcde";
                  char[] character = letters.toCharArray();
                  //creates a character array of {'a', 'b', 'c', 'd', 'e'} in which each individual character can be viewed like:
                  char indchar = character[0]; //returns 'a'
                  Right now, I see toCharArray() as the program's best hope. How can my program use it so that it incorporates the use of my code? If toCharArray() has no hope, simplify as much as possible.
                  • 6. Re: Encryption program
                    jduprez
                    You didn't comment sabre150's reply, so I insist: unless this is a pet project to help you learn Java, I see no point in trying to develop a new ciphering algorithm. In particular a substitution-based cipher is very easy to break compared to well-know existing algorithms (e.g. 3DES).

                    If you're doing this to learn Java, as your last post suggests, I recommend you try to code something easier (if you're fanc of ciphers, use yet a simpler one such as Caesar's cipher).

                    To help you along, the [Java tutorial|http://java.sun.com/docs/books/tutorial/] is a good resource. it has a few chapters dedicated to essential classes, such as the core java.lang ones (String, StringBuffer, StringBuilder,...) or the collection classes.
                    • 7. Re: Encryption program
                      843853
                      bengal513 wrote:
                      This is really complicated; not what I was expecting, but I see where some logic comes into this. One problem is that I do not know anything about the Map, HashMap or StringBuffer classes so if I would want to troubleshoot this, I would have to first learn some things about these classes.
                      Well yeah, you're a complete Java newb, so presumably anything you do will require learning. And if you're not doing this little app to learn something, why the heck are you doing it? If you seriously need something to encrypt stuff for you, use one of the myriad of better options already available to you.
                      I am not even sure if I used the code properly as the compiler error messages said that it could not find the classes Map or HashMap.
                      This is Java, you'll have to import them. Maybe you should start with the basic structure of the language before having attempted to use Swing?
                      I will try yet again to simplify the program and start with the basics:
                      The solution I suggested really isn't that complicated. It's essentially the second option you suggested but using a look-up table (the Map) instead of a ridiculous amount of if-statements. If you think it's complicated, than you shouldn't be doing this project, and should instead be starting with [the Java basics|http://java.sun.com/docs/books/tutorial/], not the basics for this app.

                      And by the way, never, ever come here and say "I'm pretty much done; I've got a GUI working, I've only to finish the algorithm." It's like saying "I've got a nice frame, now I just need to paint a masterpiece to put in it." The masterpiece doesn't need a frame, and neither does your little trivial app. Don't waste your time on the frame when you haven't got a painting yet. Learn to use the command line.
                      • 8. Re: Encryption program
                        843853
                        Apparently I do know enough about my program to make it work because that was what I did last night. My goal is to keep this program as simple as possible so I tried to do that one more time (after I typed the pseudocode, I got an idea).

                        I decided to take another look at the toCharArray() method based on my pseudocode which generally suggested to "evaluate each individual letter" and reference the basic code alphabet (no prefixes, or special rules).

                        toCharArray() is a method within class String that converts a string into an array of its individual characters. Since arrays have indexes (like positions), each position could be evaluated by starting at [0] (first position) and going up to the string's length - 1. This is the content of the translation method (with comments on how it works):
                        /*translation method*/
                        private void translateInput(){
                             int length = input.length(); //get the length for the inputted text
                             char[] schars = input.toCharArray(); //make a character array for the user's input
                        
                             for (int pos = 0; pos >= 0 && pos <= length - 1; pos++){ //start a for loop to cycle through the indexes in the array BASED ON the length of input
                        //the highest value in length is not included in the loop because the array's first position is [0]
                        //start a set of if-else statements to find matches for each index in the array
                        //search starts at schars[0] and ends at schars[length - 1]
                                             if (schars[pos] == 'a' || schars[pos] == 'A')
                                            output += "5";
                                  else if (schars[pos] == 'b' || schars[pos] == 'B')
                                            output += "6";
                                  else if (schars[pos] == 'c' || schars[pos] == 'C')
                                            output += "7";
                                  else if (schars[pos] == 'd' || schars[pos] == 'D')
                                            output += "8";
                                  else if (schars[pos] == 'e' || schars[pos] == 'E')
                                            output += "9";
                                  else if (schars[pos] == 'f' || schars[pos] == 'F')
                                            output += "01";
                                  else if (schars[pos] == 'g' || schars[pos] == 'G')
                                            output += "02";
                                  else if (schars[pos] == 'h' || schars[pos] == 'H')
                                            output += "03";
                        //and so on for the alphabet, all the way to z
                        //then add in some punctuation
                                  else if (schars[pos] == ' ')
                                            output += " ";
                                  else if (schars[pos] == '\n')
                                            output += "\n";
                                  else if (schars[pos] == '.')
                                            output += ".";
                                  else if (schars[pos] == ',')
                                            output += ",";
                                  else if (schars[pos] == '?')
                                            output += "?";
                                  else if (schars[pos] == '-')
                                            output += "-";
                                  else if (schars[pos] == ':')
                                            output += ":";
                                  else if (schars[pos] == ';')
                                            output += ";";
                                  outputArea.setText(output); //after the string of the input has been translated, and stored in the variable output, it is displayed to the user
                                  }
                             }
                        Works perfectly. After this program's success I kept experimenting with it and added a second button that cleared the two text areas, and the string variables for them which allows for an endless number of keyings per program execution. I made this program without any complicated stuff; just stuck to the objective.

                        Of course, there is room for some improvement in the diversity of the application (such as the use of prefixes and the 10 combination), but now I know that I can figure it out.
                        • 9. Re: Encryption program
                          843853
                          bengal513 wrote:
                          Apparently I do know enough about my program to make it work because that was what I did last night. My goal is to keep this program as simple as possible so I tried to do that one more time (after I typed the pseudocode, I got an idea).
                          Congratulations! Actually I was trying to encourage you to keep it simple, because you weren't. Simple programs don't have a graphical user interface.

                          Allow me to give you a few pointers, since you're obviously pretty new to the language.
                          toCharArray() is a method within class String that converts a string into an array of its individual characters. Since arrays have indexes (like positions), each position could be evaluated by starting at [0] (first position) and going up to the string's length - 1.
                          Good that you found it on your own. This is what I had in mind when I suggested the part with "for each character...".
                               int length = input.length(); //get the length for the inputted text
                          This isn't really necessary. Instead of using a separate variable to store the length, just access it directly in your for-loop condition using schars.length.
                               char[] schars = input.toCharArray(); //make a character array for the user's input

                               for (int pos = 0; pos >= 0 && pos <= length - 1; pos++){ //start a for loop to cycle through the indexes in the array BASED ON the length of input{code}
                          This is better written like this:
                          for (int pos = 0; pos < schars.length; pos++) { 
                          Everything's minor, but here's the deal: pos can't be less than zero because you're starting at zero and then going up, so that check is pointless. Using the "<=" and "length-1" is like a double-negative; they negate each other and it's easier to just use the less-than operator. And as I've already said, you can just use schars.length directly.

                          Even better, you can use the Java 1.5 for-loop which simplifies things even more:
                          for ( char c : schars ) {
                            //you can reference c, which will go through each element in schars
                          }
                               
                          if (schars[pos] == 'a' || schars[pos] == 'A')
                          The if-else blocks are OK for a beginner, but to make this more extensible and way cleaner, I would still hold that you should investigate using a Map. A Map just associates a key with a value: in this case a character with a number (as a String). It would save you all the if statements: instead of checking every character in turn, just request from the Map which string should be appended to the output. But since you're pretty new to Java, I would hold off a bit and start from the beginning with the [Collections tutorial|http://java.sun.com/docs/books/tutorial/collections/index.html].
                                              
                          output += "5";
                          You use String concatenation here. The reason I suggested using a StringBuffer is because it is much more efficient. Strings are actually immutable: they can't be changed, which means that what is actually happening here is every time you append to the end of output, you're actually creating a new String from the two operands (the old output and "5", in this case) and assigning it back to output. That's really, really expensive and hugely noticable with any large input. So research StringBuffer. It's specifically designed for the case where you want to keep appending to a certain string.
                          Works perfectly.
                          I'm happy you got it working!
                          • 10. Re: Encryption program
                            843853
                            bengal513 wrote:
                            Since arrays have indexes (like positions), each position could be evaluated by starting at [0] (first position) and going up to the string's length - 1.
                            This is so a common idiom that Java provides the ' [enhanced for loop|http://java.sun.com/mailers/techtips/corejava/2007/tt0907.html#1] ' to do it for you.

                            For anything non-trivial in size, is strongly advised to use a [string builder|http://java.sun.com/docs/books/tutorial/java/data/buffers.html] rather than creating strings using += - each time round the loop, it creates a new string, so if you put in 1000 characters you have to create 1000 strings, and copy half a million characters to them, rather than copying 1000.

                            It would be cleaner to use an array or a map to convert your characters to the corresponding cipher text; failing that don't use many exclusive if/else blocks but use a [switch statement|http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html]

                            In real software, you will often find that you want to use the same function in multiple places, and you want to test it in small pieces, so will end up factoring large blocks of code into smaller functions. I'd suggest an obvious refactoring would be to create a class implements the cypher separate from the UI, and which has a method which converts a single character into the corresponding cypher text.
                            /* translation method in the UI */
                            private void translateInput () {
                                outputArea.setText ( cypher.encrypt ( input.getText() ) );
                            }
                            
                            /* the encrypt method of the cypher object encrypts on a per-character basis */
                            public String encrypt ( String input ) {
                                final StringBuilder buffer = new StringBuilder ( input.length() * 2 );
                                
                                for ( char ch : input.toCharArray() )
                                    buffer.append ( encryptChar ( ch ) );
                                
                                return buffer.toString();
                            }
                            
                            /* the code to encrypt one character using a switch ( I'd use an array personally, but it's not that important ) */
                            private String encryptChar ( char ch ) {
                                switch ( Character.toLowerCase ( ch ) ) { // saves having multiple cases for A and a
                                    case 'a' : return "5";
                                    case 'b' : return "6";
                                // ...
                                    default: return "?";
                                }
                            }
                            HTH