javaencryptionfor-loopchar

How to encrypt a text from my code?


I have had this code made to encrypt a text and place the new text in a TextView. I was then thinking of a way to do several things.

  1. How to make every every letter =< 29 as there only is that many letters (in Denmark)

  2. How to make change the 1st letter one way, the 2nd letter another way and the 3rd letter yet another way. The next letter, 4th, should then be change like the 1st letter was, the 5th like the 2nd and so on e.g. "that" change 1,2,3 = "ujdu"

    C = Integer.valueOf(ceasarNr);
    String initialString = yourString.getText().toString();
    char[] chars = initialString.toCharArray();
    for (int i = 0; i < chars.length; ++i)
        chars[i] = (char)((int)chars[i] + C);
    String resultString = new String(chars);
    krypteredeTekst.setText(resultString);
    

Solution

  • I believe you are wanting to use a different Ceasar key for each of the first 3 letters, then repeat those same Ceasar keys for the next set of three and so on correct?

    I'm not 100% sure how to deal with more than just the standard 26 characters of the alphabet i always deal with but one way to handle this would be to make a List with the characters in order in the list. If you do this be sure to switch your string to all lowercase so you dont get matching errors if there are capitals

    Please not I was not able to test the code below so ther could easily be errors in it (including syntax errors) I think it should work but you should be able to make it more elegant (for instance those IFs inside the for are all a bit ugly) and a few thigns should be moved out to their own methods.

    List<String> characters = new ArrayList<String>();
    ...Fill the List with the alphabet in order here (best to do in it's own method)
    String initialString = yourString.getText().toString().toLowercase();
    char[] chars = initialString.toCharArray();
    for (int i = 1; i <= chars.length; i++) {
        C = Integer.valueOf(ceasarNr1);
        if ( i%2 ==0 ) C = Integer.valueOf(ceasarNr2);
        if ( i%3 ==0 ) C = Integer.valueOf(ceasarNr3);
    
        chars[i-1] = characters.get((characters.indexOf(chars[i-1]) + C)%29);
    }
    String resultString = new String(chars);
    krypteredeTekst.setText(resultString);