Caesar Cipher

I'm trying to do a basic caesar cipher shift by 1. This is my code so far but its off by one letter. Could someone tell me whats wrong with it? Thx
     public void caesarCipher()
          char[] letters = {'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'};
          for(int x=0; x<letters.length; x++)
               int n=1;
               letters[x]=letters[(x+n)%26];
               System.out.print(letters[x]);
     }This is the output of this code:
BCDEFGHIJKLMNOPQRSTUVWXYZB

You start at the beginning of the array, modifying its contents, and at the end loop around to the beginning of the array again, after you have already modified that position.
Don't even bother trying to encode it in-place. Create a new array for output.

Similar Messages

  • Caesar Cipher and non printing ascii

    I am writing a program to implements the caesar cipher. For the program I am using ASCII code so my encryption algorithm is:
    c = (p + k) mod 128
    The only problem is, is that depending on the characters being encrypted and depending on the key I use some of the characters are encrypted to non-printing ascii characters such as 'del'.
    So my code reads in the plain text from a file converts each character to ascii, encrypts each character using the key. It then writes the encrypted ascii values to a file as text (i.e. the character equivalent of the ascii).
    If I do then encounter a non-printing ascii value it is written to the file as a square shape. Is there any way I can get around this?
    Thanks for your help on the matter.
    Wallace

    Modify your encryption function so that it only covers those ASCII values that print, i.e. you need to implement the mod and + function yourself so that only good ASCII characters are considered.

  • Is any one give me a Caesar Cipher algo in Jsp

    hi frnds
    i want to give password security in my web-page so what i want i simple input simple password text and i store that password text as a Caesar Cipher encription and when i retrive that it come with descriptions example like below
    if enter
    abcd
    store in db like
    fjsd
    and when user enter
    abcd
    it dycript [fjsd] and come abcd
    means password store in db as Caesar Cipher text
    if send me then my id is [email protected]
    thnx

    The libs needed for the OS including the hearders
    may not be installed if the OS was not originally
    installed as a developer system. The libs are not
    included in the compilers if they have to be
    supported at runtime in the OS, or if they have to
    be there at link time for third party compilers,
    such as gcc. You must find the package that contains
    them on the OS distribution and install them from
    that package. Your sysadmin should be able to do
    this.

  • Caesar Cipher Algorithm Wrong  ??

    public class caesarCipher {
          public static void main(String args[]) {
          int num1=0,donothing=0;
          char[] s1 = {'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'};
          System.out.println("Please enter a caesar cipher shift between 1-26 :");
          num1 = SavitchIn.readInt();
              do {
                    System.out.println("ERROR: Please enter a caesar cipher shift between 1-26 :");
                    num1 = SavitchIn.readInt();
              }while(num1>26 && num1<1);
              while(num1<27 && num1>0) {
                    System.out.println("Please enter some plaintext to be  encoded");
                    String s2 = SavitchIn.readLine();
                    s2=s2.toLowerCase();
                    int length1 = s2.length();
                    for (int i=0; i<s2.length(); i++) {
                          for (int j=0; j<s2.length(); j++) {
                                if( s2.charAt(i)==s1[j] )
                                      System.out.print( s1[(j+num1)%26] );
                                else if ( s2.charAt(i)!=s1[j] )
                                      donothing++;
                    System.out.println();
                    System.exit(0);
    }The program works fine if the user enters abc.. but if anything else is entered e.g fghkl the program prints a blank.
    Any ideas where I went wrong on this as I am pulling my hair out trying to work it out :)
    Thanks for any help
    Se�n

    I tried 26 instead of s1.length(), thanks for the help
    as the idea was correct.No, no, no. Again, use s1.length (not s1.length()). Don't hard-code constants like "26", as then your code is more fragile if you change the actual array size.

  • Ask  help  for a question about Caesar cipher

    "Caesar ciphers are among the simplest devised, and rely solely on remapping characters to others in the alphabet using a constant shift modulo the size of the alphabet. The amount shifted is the key used to encipher, or decipher, the message. This remapping is usually restricted to letters, so that with a key of 2, `A' is replaced by `C', `B' by `D', ..., `X' by `Z', `Y' by `A', and `Z' by `B'. Lower case letters are mapped in an identical way to give their lower case replacements. Thus here the key is an integer in the range 1 to 25 (not 0 to 25, as there is no point replacing every `A' by an `A' etc.).
    Straightforward Caesar ciphers are rather too easy to recognise however. In an attempt to maintain the basic idea, but complicate the result, what we will do is systemmatically jumble up the letters. Treating `I' and `J' as one letter from the start (so now there are only 24 different keys, assuming we still exclude mapping `A' to `A'), the 25 letters will be written to a 5 by 5 grid, by rows, and read back by columns. So, for example, with a key of 10, `A' is mapped into `L', and the grid produced is:
    L M N O P
    Q R S T U
    V W X Y Z
    A B C D E
    F G H I K
    and the uppercase alphabet upon encryption becomes: LQVAFMRWBBGNSXCHOTYDIPUZEK Note that here the `B' is doubled up because it represents both `I' and `J'. Thus, with this key of 10, the following line is enciphered to the one after it.
    Caesar ciphers are child's play.
    Vlfylt vbhwfty ltf vwbna'y hnle.
    An acceptable drawback of the treatment of `I' and `J' in the grid is that a decoded message will have all `J's mapped to `I's, and all `j's to `i's"
    this is a part of requirement in the whole program,I almost finished it, but I do not know thata how to make" a decoded message will have all `J's mapped to `I's, and all `j's to `i's". "Treating `I' and `J' as one letter from the start"?what does that mean?
    this is my code about the part:
    public static char encode(char ch,int n)  {
      while (!Character.isLetter(ch))
       return ch;
      if(ch>='A'&&ch<='Z')
      return (char)('A'+(ch-'A'+n)%26);
    if(ch>='a'&&ch<='z')
      return (char)('a'+(ch-'a'+n)%26);
    return ch;
    public static char decode(char ch,int n)  {
      while (!Character.isLetter(ch))
       return ch;
      if(ch>='A'&&ch<='Z')
      return (char)('A'+(ch-'A'-n)%26);
    if(ch>='a'&&ch<='z')
      return (char)('a'+(ch-'a'-n)%26);
    return ch;
    }but
    how to make" a decoded message will have all `J's mapped to `I's, and all `j's to `i's". "Treating `I' and `J' as one letter from the start"?

    Your teacher/instructor/professor would obviously be the final authority on this, but I think all it's saying is that when you encode, treat each 'j' you come across as an 'i', and therefore, when you decode, because you've lost information that it was a 'j' to start with, it will be mapped back to an 'i'.
    One easy way to accomplish this (that would save special cases later in your for-loop) would simply be a:
    String toEncode = "Djibouti"
    toEncode = toEncode.replaceAll("j","i"); //obviously handle both cases instead
    String encoded = encode(toEncode);
    String decoded = decode(encoded);
    System.out.println(decoded); //this would print "Diibouti"The other way is to simply add a special case to your encode/decode (char) methods.
    Edited by: endasil on 28-Sep-2009 9:35 AM

  • Caesar Cipher   java source code.

    PLZ, what is the wrong her??
    import java.io.*;
    import java.util.*;
    import java.util.Scanner;
    public class Substitution
      public String str;
      public String k;
       // main function
       public static void main(String[] args)
         Scanner scan = new Scanner(System.in);
        System.out.println("Enter character: ");
        String message=scan.nextLine();
         System.out.println("Enter key: ");
         String key=scan.nextLine();
         Substitution caes= new Substitution ();
         String encrypt = caes.translate(message,key);
         System.out.println("Encrypted: "+encrypt);
          String decrypt = caes.translate(encrypt,-1*key );
         System.out.println("Decrypted: "+decrypt);
      //constractor
       public Substitution( ) { }
      //function of translate for encrypt and decrypt
       public String translate (String str ,String k)
             StringBuffer str1= new StringBuffer(str);
             String s = "abcdefghijklmnopqrstuvwxyz";
             String d="thesnowlayickpdfrvbg-----";
             for (int j=0;j<str.length();j++)
              for(int t=0;t<k.length();t++)
              for(int i=0;i<26;i++)
                if(str.charAt(j)==s.charAt(i) )
                 if(d.charAt(t)==s.charAt(i))
                  str1.setCharAt(j,s.charAt((i+t+26)%26));
                  break;
               return str1.toString();
          Thank you

    -1*key?? What might that mean? This question is probably more appropriate for [this |http://forum.java.sun.com/forum.jspa?forumID=54] forum.

  • Need help with the query to write Cipher?

    Hi, 
    I was assigned a task to write a query to encrypt and decrypt some Cipher.  I have figured out to write the procedure to encrypt and decrypt ceasar cipher. I would really appericate if you guys could help me out with this.
    .Caesar Cipher
    2.Monoalphabetic Cipher
    3.Playfair Cipher
    4.Vigenère Cipher
    5.Transposition Ciphers
    6.Rail Fence cipher
    7.Row Transposition Cipher

    Hi , 
    I sorry about just giving the names to when i resarched i saw Rail Fnce Cipher and Ceasar Cipher are the most easier ones.
    This is how rail fence cipher works .
    Codes and Ciphers :: Rail Fence
    In the rail fence cipher, the plaintext is written downwards on successive "rails" of an imaginary fence, starting a new column when the bottom is reached. The message is then read off in rows. For
    example, if we have 3 rails and a message of "This is a secret message", you would write out:
    T S A C T S G
    H I S R M S E
    I S E E E A J
    The last J is just a random letter to fill in the space. The secret message is then condensed and regrouped.
    TSACT SGHIS RMSEI SEEEA JGURL
    To decipher a message you must know the number of rails that were used to encipher it. You then break up the letters into equal groups for each rail. For example, if you are using 3 rails, you
    would break the secret message into 3 equal groups. Now you stack the groups on top of each other and read off the message vertically. If you get gibberish, then there are probably some extra letters tacked on the end of the message that are throwing off the
    grouping. Try removing one letter from the end and try again.
    So if the number of rails =3
    Plaintext :- "This is a sccerect message"
    Cipher Text:-"TSACTSGHISRMEISEEEAJ"
    Can we figure out to write a procedure or function for this.
    Rail Fence Encoder / Decoder
    Number of rails: <input class="form_txt_gr" maxlength="2" name="rails" size="3" style="font-family:verdana, arial, sans-serif;font-size:10px;vertical-align:middle;border:1px solid rgb(0, 0, 0);padding:2px 1px;margin:0px 5px 0px 2px;background-color:#ffffdd;"
    type="text" value="3" />
    Plaintext
    <textarea class="form_txt_gr" cols="40" name="message" rows="5" style="font-family:verdana, arial, sans-serif;font-size:10px;vertical-align:middle;border-color:#000000;padding-right:1px;padding-margin:0px 5px 0px 2px;background-color:#ffffdd;"></textarea>
    Ciphertext
    <textarea class="form_txt_gr" cols="40" name="encoded" rows="5" style="font-family:verdana, arial, sans-serif;font-size:10px;vertical-align:middle;border-color:#000000;padding-right:1px;padding-margin:0px 5px 0px 2px;background-color:#ffffdd;"></textarea>
    <input class="form_submit_gr" name="encipher" style="font-family:verdana, arial, sans-serif;font-size:10px;vertical-align:middle;color:#000000;border:1px solid rgb(0, 0, 0);font-weight:bold;padding-right:1px;padding-margin:0px;background-color:#ffcc66;" type="submit"
    value="Encipher" /> <input class="form_submit_gr" name="decipher" style="font-family:verdana, arial, sans-serif;font-size:10px;vertical-align:middle;color:#000000;border:1px solid rgb(0, 0, 0);font-weight:bold;padding-right:1px;padding-margin:0px;background-color:#ffcc66;"
    type="submit" value="Decipher" />
    Rail Fence Encoder / Decoder
    Number of rails: <input class="form_txt_gr" maxlength="2" name="rails" size="3" style="font-family:verdana, arial, sans-serif;font-size:10px;vertical-align:middle;border:1px solid rgb(0, 0, 0);padding:2px 1px;margin:0px 5px 0px 2px;background-color:#ffffdd;"
    type="text" value="3" />
    Plaintext
    <textarea class="form_txt_gr" cols="40" name="message" rows="5" style="font-family:verdana, arial, sans-serif;font-size:10px;vertical-align:middle;border-color:#000000;padding-right:1px;padding-margin:0px 5px 0px 2px;background-color:#ffffdd;"></textarea>
    Ciphertext
    <textarea class="form_txt_gr" cols="40" name="encoded" rows="5" style="font-family:verdana, arial, sans-serif;font-size:10px;vertical-align:middle;border-color:#000000;padding-right:1px;padding-margin:0px 5px 0px 2px;background-color:#ffffdd;"></textarea>
    <input class="form_submit_gr" name="encipher" style="font-family:verdana, arial, sans-serif;font-size:10px;vertical-align:middle;color:#000000;border:1px solid rgb(0, 0, 0);font-weight:bold;padding-right:1px;padding-margin:0px;background-color:#ffcc66;" type="submit"
    value="Encipher" /> <input class="form_submit_gr" name="decipher" style="font-family:verdana, arial, sans-serif;font-size:10px;vertical-align:middle;color:#000000;border:1px solid rgb(0, 0, 0);font-weight:bold;padding-right:1px;padding-margin:0px;background-color:#ffcc66;"
    type="submit" value="Decipher" />

  • Need to create a driver class for a program i have made...

    hey guys im new to these forums and someone told me that i could get help on here if i get in a bind...my problem is that i need help creating a driver class for a program that i have created and i dont know what to do. i need to know how to do this is because my professor told us after i was 2/3 done my project that we need at least 2 class files for our project, so i need at least 2 class files for it to run... my program is as follows:
    p.s might be kinda messy, might need to put it into a text editor
    Cipher.java
    This program encodes and decodes text strings using a cipher that
    can be specified by the user.
    import java.io.*;
    public class Cipher
    public static void printID()
    // output program ID
    System.out.println ("*********************");
    System.out.println ("* Cipher *");
    System.out.println ("* *");
    System.out.println ("* *");
    System.out.println ("* *");
    System.out.println ("* CS 181-03 *");
    System.out.println ("*********************");
    public static void printMenu()
    // output menu
    System.out.println("\n\n****************************" +
    "\n* 1. Set cipher code. *" +
    "\n* 2. Encode text. *" +
    "\n* 3. Decode coded text. *" +
    "\n* 4. Exit the program *" +
    "\n****************************");
    public static String getText(BufferedReader input, String prompt)
    throws IOException
    // prompt the user and get their response
    System.out.print(prompt);
    return input.readLine();
    public static int getInteger(BufferedReader input, String prompt)
    throws IOException
    // prompt and get response from user
    String text = getText(input, prompt);
    // convert it to an integer
    return (new Integer(text).intValue());
    public static String encode(String original, int offset)
    // declare constants
    final int ALPHABET_SIZE = 26; // used to wrap around A-Z
    String encoded = ""; // base for string to return
    char letter; // letter being processed
    // convert message to upper case
    original = original.toUpperCase();
    // process each character of the message
    for (int index = 0; index < original.length(); index++)
    // get the letter and determine whether or not to
    // add the cipher value
    letter = original.charAt(index);
    if (letter >='A' && letter <= 'Z')
    // is A-Z, so add offset
    // determine whether result will be out of A-Z range
    if ((letter + offset) > 'Z') // need to wrap around to 'A'
    letter = (char)(letter - ALPHABET_SIZE + offset);
    else
    if ((letter + offset) < 'A') // need to wrap around to 'Z'
    letter = (char)(letter + ALPHABET_SIZE + offset);
    else
    letter = (char) (letter + offset);
    // build encoded message string
    encoded = encoded + letter;
    return encoded;
    public static String decode(String original, int offset)
    // declare constants
    final int ALPHABET_SIZE = 26; // used to wrap around A-Z
    String decoded = ""; // base for string to return
    char letter; // letter being processed
    // make original message upper case
    original = original.toUpperCase();
    // process each letter of message
    for (int index = 0; index < original.length(); index++)
    // get letter and determine whether to subtract cipher value
    letter = original.charAt(index);
    if (letter >= 'A' && letter <= 'Z')
    // is A-Z, so subtract cipher value
    // determine whether result will be out of A-Z range
    if ((letter - offset) < 'A') // wrap around to 'Z'
    letter = (char)(letter + ALPHABET_SIZE - offset);
    else
    if ((letter - offset) > 'Z') // wrap around to 'A'
    letter = (char)(letter - ALPHABET_SIZE - offset);
    else
    letter = (char) (letter - offset);
    // build decoded message
    decoded = decoded + letter;
    return decoded;
    // main controls flow throughout the program, presenting a
    // menu of options the user.
    public static void main (String[] args) throws IOException
    // declare constants
    final String PROMPT_CHOICE = "Enter your choice: ";
    final String PROMPT_VALID = "\nYou must enter a number between 1" +
    " and 4 to indicate your selection.\n";
    final String PROMPT_CIPHER = "\nEnter the offset value for a caesar " +
    "cipher: ";
    final String PROMPT_ENCODE = "\nEnter the text to encode: ";
    final String PROMPT_DECODE = "\nEnter the text to decode: ";
    final String SET_STR = "1"; // selection of 1 at main menu
    final String ENCODE_STR = "2"; // selection of 2 at main menu
    final String DECODE_STR = "3"; // selection of 3 at main menu
    final String EXIT_STR = "4"; // selection of 4 at main menu
    final int SET = 1; // menu choice 1
    final int ENCODE = 2; // menu choice 2
    final int DECODE =3; // menu choice 4
    final int EXIT = 4; // menu choice 3
    final int ALPHABET_SIZE = 26; // number of elements in alphabet
    // declare variables
    boolean finished = false; // whether or not to exit program
    String text; // input string read from keyboard
    int choice; // menu choice selected
    int offset = 0; // caesar cipher offset
    // declare and instantiate input objects
    InputStreamReader reader = new InputStreamReader(System.in);
    BufferedReader input = new BufferedReader(reader);
    // Display program identification
    printID();
    // until the user selects the exit option, display the menu
    // and respond to the choice
    do
    // Display menu of options
    printMenu();
    // Prompt user for an option and read input
    text = getText(input, PROMPT_CHOICE);
    // While selection is not valid, prompt for correct info
    while (!text.equals(SET_STR) && !text.equals(ENCODE_STR) &&
    !text.equals(EXIT_STR) && !text.equals(DECODE_STR))
    text = getText(input, PROMPT_VALID + PROMPT_CHOICE);
    // convert choice to an integer
    choice = new Integer(text).intValue();
    // respond to the choice selected
    switch(choice)
    case SET:
         // get the cipher value from the user and constrain to
    // -25..0..25
    offset = getInteger(input, PROMPT_CIPHER);
    offset %= ALPHABET_SIZE;
    break;
    case ENCODE:
    // get message to encode from user, and encode it using
    // the current cipher value
    text = getText(input, PROMPT_ENCODE);
    text = encode(text, offset);
    System.out.println("Encoded text is: " + text);
    break;
    case DECODE:
    // get message to decode from user, and decode it using
    // the current cipher value
    text = getText(input, PROMPT_DECODE);
    text = decode(text, offset);
    System.out.println("Decoded text is: " + text);
    break;
    case EXIT:
    // set exit flag to true
    finished = true ;
    break;
    } // end of switch on choice
    } while (!finished); // end of outer do loop
    // Thank user
    System.out.println("Thank you for using Cipher for all your" +
    " code breaking and code making needs.");
    }

    My source in code format...sorry guys :)
       Cipher.java
       This program encodes and decodes text strings using a cipher that
       can be specified by the user.
    import java.io.*;
    public class Cipher
       public static void printID()
          // output program ID
          System.out.println ("*********************");
          System.out.println ("*       Cipher      *");
          System.out.println ("*                   *");
          System.out.println ("*                          *");
          System.out.println ("*                   *");
          System.out.println ("*     CS 181-03     *");
          System.out.println ("*********************");
       public static void printMenu()
          // output menu
          System.out.println("\n\n****************************" +
                               "\n*   1. Set cipher code.    *" +
                               "\n*   2. Encode text.        *" +
                               "\n*   3. Decode coded text.  *" +
                               "\n*   4. Exit the program    *" +
                               "\n****************************");
       public static String getText(BufferedReader input, String prompt)
                                           throws IOException
          // prompt the user and get their response
          System.out.print(prompt);
          return input.readLine();
       public static int getInteger(BufferedReader input, String prompt)
                                           throws IOException
          // prompt and get response from user
          String text = getText(input, prompt);
          // convert it to an integer
          return (new Integer(text).intValue());
       public static String encode(String original, int offset)
          // declare constants
          final int ALPHABET_SIZE = 26;  // used to wrap around A-Z
          String encoded = "";           // base for string to return
          char letter;                   // letter being processed
          // convert message to upper case
          original = original.toUpperCase();
          // process each character of the message
          for (int index = 0; index < original.length(); index++)
             // get the letter and determine whether or not to
             // add the cipher value
             letter = original.charAt(index);
             if (letter >='A' && letter <= 'Z')          
                // is A-Z, so add offset
                // determine whether result will be out of A-Z range
                if ((letter + offset) > 'Z') // need to wrap around to 'A'
                   letter = (char)(letter - ALPHABET_SIZE + offset);
                else
                   if ((letter + offset) < 'A') // need to wrap around to 'Z'
                      letter = (char)(letter + ALPHABET_SIZE + offset);
                   else
                      letter = (char) (letter + offset);
             // build encoded message string
             encoded = encoded + letter;
          return encoded;
       public static String decode(String original, int offset)
          // declare constants
          final int ALPHABET_SIZE = 26;  // used to wrap around A-Z
          String decoded = "";           // base for string to return
          char letter;                   // letter being processed
          // make original message upper case
          original = original.toUpperCase();
          // process each letter of message
          for (int index = 0; index < original.length(); index++)
             // get letter and determine whether to subtract cipher value
             letter = original.charAt(index);
             if (letter >= 'A' && letter <= 'Z')          
                // is A-Z, so subtract cipher value
                // determine whether result will be out of A-Z range
                if ((letter - offset) < 'A')  // wrap around to 'Z'
                   letter = (char)(letter + ALPHABET_SIZE - offset);
                else
                   if ((letter - offset) > 'Z') // wrap around to 'A'
                      letter = (char)(letter - ALPHABET_SIZE - offset);
                   else
                      letter = (char) (letter - offset);
             // build decoded message
             decoded = decoded + letter;
          return decoded;
       // main controls flow throughout the program, presenting a
       // menu of options the user.
       public static void main (String[] args) throws IOException
         // declare constants
          final String PROMPT_CHOICE = "Enter your choice:  ";
          final String PROMPT_VALID = "\nYou must enter a number between 1" +
                                      " and 4 to indicate your selection.\n";
          final String PROMPT_CIPHER = "\nEnter the offset value for a caesar " +
                                       "cipher: ";
          final String PROMPT_ENCODE = "\nEnter the text to encode: ";
          final String PROMPT_DECODE = "\nEnter the text to decode: ";
          final String SET_STR = "1";  // selection of 1 at main menu
          final String ENCODE_STR = "2"; // selection of 2 at main menu
          final String DECODE_STR = "3"; // selection of 3 at main menu
          final String EXIT_STR = "4";  // selection of 4 at main menu
          final int SET = 1;            // menu choice 1
          final int ENCODE = 2;         // menu choice 2
          final int DECODE =3;          // menu choice 4
          final int EXIT = 4;           // menu choice 3
          final int ALPHABET_SIZE = 26; // number of elements in alphabet
          // declare variables
          boolean finished = false; // whether or not to exit program
          String text;              // input string read from keyboard
          int choice;               // menu choice selected
          int offset = 0;           // caesar cipher offset
          // declare and instantiate input objects
          InputStreamReader reader = new InputStreamReader(System.in);
          BufferedReader input = new BufferedReader(reader);
          // Display program identification
          printID();
          // until the user selects the exit option, display the menu
          // and respond to the choice
          do
             // Display menu of options
             printMenu(); 
             // Prompt user for an option and read input
             text = getText(input, PROMPT_CHOICE);
             // While selection is not valid, prompt for correct info
             while (!text.equals(SET_STR) && !text.equals(ENCODE_STR) &&
                     !text.equals(EXIT_STR) && !text.equals(DECODE_STR))       
                text = getText(input, PROMPT_VALID + PROMPT_CHOICE);
             // convert choice to an integer
             choice = new Integer(text).intValue();
             // respond to the choice selected
             switch(choice)
                case SET:
                // get the cipher value from the user and constrain to
                   // -25..0..25
                   offset = getInteger(input, PROMPT_CIPHER);
                   offset %= ALPHABET_SIZE;
                   break;
                case ENCODE:
                   // get message to encode from user, and encode it using
                   // the current cipher value
                   text = getText(input, PROMPT_ENCODE);
                   text = encode(text, offset);
                   System.out.println("Encoded text is: " + text);
                   break;
                case DECODE:
                   // get message to decode from user, and decode it using
                   // the current cipher value
                   text = getText(input, PROMPT_DECODE);
                   text = decode(text, offset);
                   System.out.println("Decoded text is: " + text);
                   break;
                case EXIT:
                   // set exit flag to true
                   finished = true ;
                   break;
             } // end of switch on choice
          } while (!finished); // end of outer do loop
          // Thank user
          System.out.println("Thank you for using Cipher for all your" +
                             " code breaking and code making needs.");
    }

  • Could someone help me please

    I am doing a piece of code in RMI here is what i have come up with up to now:
    public class cipherimpl
        extends java.rmi.server.UnicastRemoteObject
        implements cipher {
        public cipherimpl()
             throws java.rmi.RemoteException {
             super();
         char[] tempArray;
         int b = 3;
        public String encrypt(String nameofString, int b)
             throws java.rmi.RemoteException {
                   tempArray = nameofString.toCharArray();
                   char c =  char[0];
                   int c1 = (int) c;
                   c2 = c1+b;
                   return nameofString;
         public String decrypt(String nameofString, int b)
              throws java.rmi.RemoteException {
                   tempArray = nameofString.toCharArray();
                   char d = char[0];
                   int d1 = (int) d;
                   d2 = d2-b;
                   return nameofString;
    }I also have a code called chiper.java which defines the two methods encrypt and decrypt.
    For the impl file i need to make it use the Caesar Cipher method where there is an integer and this integer is used to encrytp a word so if the integer is equal to 1 each of the letters in the word are incremented by 1 so if the word "HELLO" was inputted the output would be "IFMMP" if u get what i mean but i am finding it difficult to put into code.
    Could someone give me a few clues please.
    Thanx
    MARK

    mate, i wasn't saying why are you messing with RMI, what I mean was why are you trying to do it all at once. Try to break down the problem. If all you want to do is to increment the character by one then the simplest way to do it is to set up an array of all the letters of the alphabet. Iterate over the string getting each character. Look it up in the array, and then get the next one, and add that to an output StringBuffer. When you have reached the end of the input string, toString() the StringBuffer, and you are done.
    Fundamentally, programming is all about breaking problems up. If you try and look at everything at once you will either go mad, or not be able to cope.
    HTH

  • Logical error 2nd Edition... :~(

    here is the 2nd edition of the program.
    it runs wired, i can't exactly tell how, but the way it does just like lost-control.
    copy it and give it a try see if you have any idea what's going on.
    p.s. all called methods are sticked after the main program.
    class DecodeDriver
         public static void main(String[] args)
              char keyin;
              do
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            M A I N   M E N U             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** M) Morse Code                            **");
                   sop("** C) Caesar Cipher                         **");
                   sop("** V) Vignere Cipher                        **");
                   sop("** P) Playfair Cipher                       **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Exit Program                          **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select an encoding scheme: ");
                   keyin = SavitchIn.readNonwhiteChar();
                   switch(keyin)
                   case'M':
                   case'm': Morse();
                        break;
                        case'C':
                   case'c': Caesar();
                        break;
                        case'V':
                   case'v': Vignere();
                        break;
                        case'P':
                   case'p': Playfair();
                        break;
                        case'X':
                        case'x': sop("Thanks for using! Bye!");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } //switch
              } // do
              while(keyin != 'X' && keyin != 'x');
              System.exit(0);
         } // main
              public static void Morse()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            Morse Code Menu               **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': MorseCode.encode();
                        break;
                        case'D':
                        case'd': MorseCode.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                                       break;
                   } // switch
              } //Morse
              private static void Caesar()
                   char subKeyin = SavitchIn.readNonwhiteChar();
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Caesar Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   switch(subKeyin)
                        case'E':
                        case'e': CaesarCipher.encode();
                        case'D':
                        case'd': CaesarCipher.decode();
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                   } // switch
              } //CaesarCipher
              private static void Vignere()
                   char subKeyin = SavitchIn.readNonwhiteChar();
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Vignere Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   switch(subKeyin)
                        case'E':
                        case'e': VignereCipher.encode();
                        case'D':
                        case'd': VignereCipher.decode();
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                   } // switch
              } //VignereCipher          
              private static void Playfair()
                   char subKeyin = SavitchIn.readNonwhiteChar();
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**          Playfair Cipher Menu            **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   switch(subKeyin)
                        case'E':
                        case'e': PlayfairCipher.encode();
                        case'D':
                        case'd': PlayfairCipher.decode();
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                   } // switch
              } //PlayfairCipher     
              private static void sop(String newString)
                   System.out.println(newString);
              } // sop
    } //class
    (part of)the SavitchIn input stuff:
        public static char readNonwhiteChar( )
          char next;
          next = readChar( );
          while (Character.isWhitespace(next))
              next = readChar( );
          return next;
         The following methods are not used in the text, except
         for a brief reference in Chapter 2. No program code uses
         them. However, some programmers may want to use them.
         Precondition: The next input in the stream consists of
         an int value, possibly preceded by whitespace, but
         definitely followed by whitespace.
         Action: Reads the first string of nonwhitespace characters
         and returns the int value it represents. Discards the
         first whitespace character after the word. The next read
         takes place immediately after the discarded whitespace.
         In particular, if the word is at the end of a line, the
         next read will take place starting on the next line.
         If the next word does not represent an int value,
         a NumberFormatException is thrown.
    MorseCode.java - for debugin' propose.
    class MorseCode
       public MorseCode()
          sop("unfinished - const.");
         }//const.
         public static void encode()
              sop("unfinished - encode");
              char newchar;
              newchar = SavitchIn.readChar();
              System.out.println(newchar);
         public static void decode()
              sop("unfinished - decode");
         private static void sop(String newString)
              System.out.println(newString);
         } // sop
    }//class

    aside from the missing breaks?
    encode OR decode
    case'E':
    case'e': CaesarCipher.encode();
    break;
    case'D':
    case'd': CaesarCipher.decode();
    break;looks better this time?
    class DecodeDriver
         public static void main(String[] args)
              char keyin;
              do
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            M A I N   M E N U             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** M) Morse Code                            **");
                   sop("** C) Caesar Cipher                         **");
                   sop("** V) Vignere Cipher                        **");
                   sop("** P) Playfair Cipher                       **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Exit Program                          **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select an encoding scheme: ");
                   keyin = SavitchIn.readNonwhiteChar();
                   switch(keyin)
                   case'M':
                   case'm': Morse();
                        break;
                   case'C':
                   case'c': Caesar();
                        break;
                   case'V':
                   case'v': Vignere();
                        break;
                   case'P':
                   case'p': Playfair();
                        break;
                   case'X':
                   case'x': sop("Thanks for using! Bye!");
                        break;
                   default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } //switch
              } // do
              while(keyin != 'X' && keyin != 'x');
              System.exit(0);
         } // main
              public static void Morse()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**            Morse Code Menu               **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': MorseCode.encode();
                        break;
                        case'D':
                        case'd': MorseCode.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } // switch
              } //Morse
              private static void Caesar()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Caesar Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin =  SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': CaesarCipher.encode();
                        break;
                        case'D':
                        case'd': CaesarCipher.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                                   break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                                       break;
                   } // switch
              } //CaesarCipher
              private static void Vignere()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**           Vignere Cipher Menu             **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin  = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': VignereCipher.encode();
                        break;
                        case'D':
                        case'd': VignereCipher.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } // switch
              } //VignereCipher          
              private static void Playfair()
                   char subKeyin;
                   sop("**********************************************");
                   sop("**********************************************");
                   sop("**          Playfair Cipher Menu            **");
                   sop("**        ~~~~~~~~~~~~~~~~~~~~~~~~          **");
                   sop("** ======================================== **");
                   sop("** E) Encode                                **");
                   sop("** D) Decode                                **");
                   sop("** ---------------------------------------- **");
                   sop("** X) Return to Main Program                **");
                   sop("**                                          **");
                   sop("**********************************************");
                   sop("**********************************************");
                   sop(" ");
                   sop("Please select to encoding / decoding: ");
                   subKeyin  = SavitchIn.readNonwhiteChar();
                   switch(subKeyin)
                        case'E':
                        case'e': PlayfairCipher.encode();
                        break;
                        case'D':
                        case'd': PlayfairCipher.decode();
                        break;
                        case'X':
                        case'x': sop("Returning to main menu...");
                        break;
                        default: sop("Invalid Key Entered. Please select one from the menu.");
                        break;
                   } // switch
              } //PlayfairCipher     
              private static void sop(String newString)
                   System.out.println(newString);
              } // sop
    } //class

  • Security status not satisfied.- very urgent - please help me out

    hi,
    I am using Java card (JCOP v2.241) and eclipse. Few days back I have implemented Caesar cipher and now I have installed another applet for DES... I did not do init update or key ..
    Now it is showing me security condition not satisfied.69 82
    Aborting execution error.
    I did for three times ....the same thing happened...I have searched this forums but I could not get a clear answer.... I donot have any idea abt external authentication..
    Now this shows that I cannot access the card. Is it blocked ....
    How to unlock it.. Please help me out.. How to delete the applets..
    when we use DES to implement should we use any init -update?? .I am using JCOP sample engineering card can I configure it to any other
    Any suggestions and replies highly appreciated
    Thanks
    CM.

    1. Where should I run this code. what will it show when I run this. It enumerates all installed applets and packages, currently installed in the JCOP emulator running on TCP port 8050.
    2. When I compiled it javac cardinfo.java I got 28 errors. I too. I corrected the code (see my post in the thread "Code Sample: cardinfo for JCOP41V22 Card").
    my first error says import com.ibm.jc.*; doesnot exist. should I add this package if so how can I ...You need to add the JCOP-library "offcard.jar" to the project classpath.
    Jan

  • Simple asymmetry in XOR-type encryption

    Hi there.
    In my never-ending quest for knowledge, I've decided to implement a (very) simple and (very) weak encryption algorithm, to teach myself the extreme basics of cryptography. What I decided to do is this:
    Take a byte array, which could represent a file, or user input, or whatever, and XOR each byte with a byte from an encryption key provided by the user.
    This produces a garbled set of bits that represent the encrypted message. This also has the (dis)advantage that decryption is the same process as encryption, since XOR is symmetric. So in order to decrypt an encrypted message, you simply supply the same encryption key, and re-encrypt it. This is the code:
    public static byte[] encryptOrDecrypt(byte[] key, byte[] data)
         byte[] digest = new byte[data.length];
         for (int i = 0; i < data.length; i++)
              digest[i] = new Integer(key[i % key.length] ^ data).byteValue();
         // wipe the arrays for security.
         Arrays.fill(key, (byte) 0x00);
         Arrays.fill(data, (byte) 0x00);
         return digest;
    }Note also that I am blanking the key and data arrays so they do not remain in memory. Perhaps overkill for such a simple encryption, but it seems like a good habit to get into.
    Now that works just fine; the encryption and decryption produce the proper output. However, I would like the encryption and decryption processes to be different, so that if the user wanted to double-encrypt a file, it wouldn't produce just a decrypted file as output. My idea was this:
    First encrypt with a static array of nothing-up-my-sleeve bytes (which I called a Rubicon), then encrypt with the user's encryption key.
    Thus to decrypt, just decrypt with the user's encryption key, then with the Rubicon.private static byte[] RUBICON = {0x08, 0x29, 0x3A, 0x4B, 0x5C, 0x6D, 0x7E, 0x0F};
    public static byte[] encrypt(byte[] key, byte[] data)
         byte[] digest = new byte[data.length];
         for (int i = 0; i < data.length; i++)
              digest[i] = new Integer(RUBICON[i % RUBICON.length] ^ data[i]).byteValue();
         for (int i = 0; i < data.length; i++)
              digest[i] = new Integer(key[i % key.length] ^ digest[i]).byteValue();
         // wipe the arrays for security.
         Arrays.fill(key, (byte) 0x00);
         Arrays.fill(data, (byte) 0x00);
         return digest;
    // and the decrypt method would work in the reverse
    I thought I was being pretty clever. Turns out that because of the symmetry of XOR, it doesn't matter whether you use the Rubicon or user's key first, you'll get the same output.
    I am trying to think of a way that is simpler than RSA-level algorithms, but more realistically secure than a Caesar cipher (example: shifting 1 byte right on encryption, then 1 byte left on decryption is way too simple). Any ideas for methods to differentiate between encryption and decryption, while staying simple but not too simple?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Well, what I m searching for is something like:
    needs-client-auth="if-cert-exists"
    (i.e. when I set my secure-web-site.xml settings, in the ssl-config entity.)
    I'm new to OC4J and got no idea if this possible. I know that this can be at least done in Tomcat and Weblogic.
    By applying the settings as:
    Tomcat => clientAuth="want"
    and
    Weblogic => Two Way Client Cert Behavior = "Client Certs Requested But Not Enforced"
    Please advice, how to solve this in Oracle products ?
    Thank you

  • Need help with converting characters to ASCII code

    Hey. Im trying to write a program to make Caesar Ciphers by random numbers. This cipher must also wrap from front to end of ASCII code, so that if, for example, the character being ciphered is Z and its being modified by +3, the result ciphered character is not "]", but "c".
    Im planning on reading the text that the user inputs (using ConsoleIO) into a string and then seperating each character into a character[]. Then, i would like to find the ASCII code of each character and print out the ASCII code character of the old ASCII code + the modifier.
    So far, this is what i have (sorry for the length, i like to space things out so that its easier on the eyes and more organized... X-( ... ):
    public class EvanFinalB {
         static ConsoleIO kbd = new ConsoleIO();
         static String enteredPhrase;
         static int phraseLength;
         public static void main(String[] args)
              System.out.println("Enter a phrase and this program will cipher it into a secret message.");
              System.out.println("/nEnter your phrase here:");
              //read phrase
              enteredPhrase = kbd.toString();
              //find length of entered text
              phraseLength = enteredPhrase.length();
              //declare arrays for the individual characters of the entered text and the ciphered characters
              char[] enteredChar = new char[phraseLength + 1];
              char[] cipheredChar = new char[phraseLength + 1];
              //loop converting of entered text into seperate characters
              for(int x = 1; x <= phraseLength; x++)
                   enteredChar[x] = enteredPhrase.charAt(x);
                   cipheredChar[x] = cipher(enteredChar[x]);//call cipher() method to find new ciphered character
         //wrap from front to end of ASCII code
         static char cipher(char enteredChar)
              //choose random number to cipher message by
              int modifier = (int)(Math.random() * 26) + 1;
              if(enteredChar + modifier > 90)//90 is the ASCII code for "Z" which is the last capital letter
                   cipheredChar = (97 + (modifier - (90 - enteredChar)));//97 is the ASCII code for "a" which is the first lower case letter
              return cipheredChar[1];
    }The program is obviously in its early stages but (i started creating it today actually), if there is a simple method or anything that i can use to find the ASCII value of a character in order to use enteredChar so that 'enteredChar' is equal to the ASCII code of the new ciphered character, please help me out...Thanks
    P.S. If there's an easier way to go about creating a program for Caesar Ciphers, let me know.

    The following code is from my Java textbook Big Java by Cay Horstmann. It is not my code and it's just to guide you in your own cipher.
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.IOException;
       This class encrypts files using the Caesar cipher.
       For decryption, use an encryptor whose key is the
       negative of the encryption key.
    public class CaesarCipher
          Constructs a cipher object with a given key.
          @param aKey the encryption key
       public CaesarCipher(int aKey)
          key = aKey;
          Encrypts the contents of a stream.
          @param in the input stream
          @param out the output stream
       public void encryptStream(InputStream in, OutputStream out)
             throws IOException
          boolean done = false;
          while (!done)
             int next = in.read();
             if (next == -1) done = true;
             else
                byte b = (byte) next;
                byte c = encrypt(b);
                out.write(c);
          Encrypts a byte.
          @param b the byte to encrypt
          @return the encrypted byte
       public byte encrypt(byte b)
          return (byte) (b + key);
       private int key;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Scanner;
       This program encrypts a file, using the Caesar cipher.
    public class CaesarEncryptor
       public static void main(String[] args)
          Scanner in = new Scanner(System.in);
          try
             System.out.print("Input file: ");
             String inFile = in.next();
             System.out.print("Output file: ");
             String outFile = in.next();
             System.out.print("Encryption key: ");
             int key = in.nextInt();
             InputStream inStream = new FileInputStream(inFile);
             OutputStream outStream = new FileOutputStream(outFile);
             CaesarCipher cipher = new CaesarCipher(key);
             cipher.encryptStream(inStream, outStream);
             inStream.close();
             outStream.close();
          catch (IOException exception)
             System.out.println("Error processing file: " + exception);
    }

  • Unusual string insertion question

    Hi everybody,
    I'm trying an experiment with "encoding" a text file, and I was wondering, is there a specific way to insert a random character, say, "&", into random places in a text string a random number of times? I've heard of Math.random, but I don't think that would do what I'm looking for, can anyone help me out?
    Thanks,
    Jezzica85

    Cipher.java
    import java.util.*;
    public abstract class Cipher {
      public String encrypt(String s) {
        StringBuffer result = new StringBuffer("");        
        StringTokenizer words = new StringTokenizer(s);    
        while (words.hasMoreTokens()) {                    
          result.append(encode(words.nextToken()) + " ");  
        return result.toString();                          
      public String decrypt(String s) {
        StringBuffer result = new StringBuffer("");        
        StringTokenizer words = new StringTokenizer(s);    
        while (words.hasMoreTokens()) {                    
          result.append(decode(words.nextToken())+ " ");  
        return result.toString();                          
      public abstract String encode(String word);          
      public abstract String decode(String word);
    } Caesar.java
    public class Caesar extends Cipher {
           public String encode(String word) {
             StringBuffer result = new StringBuffer();   
             for (int k = 0; k < word.length(); k++) {   
               char ch = word.charAt(k);                
               ch = (char)('a' + (ch -'a'+ 3) % 26);     
               result.append(ch);                        
             return result.toString();                   
           public String decode(String word) {
             StringBuffer result = new StringBuffer();   
             for (int k = 0; k < word.length(); k++) {   
             char ch = word.charAt(k);                   
                ch = (char)('a' + (ch - 'a' + 23) % 26); 
                result.append(ch);                       
             return result.toString();                   
         } TestEncrypt.java
    public class TestEncrypt {
           public static void main(String argv[]) {
             Caesar caesar = new Caesar();
             //here's the message
             String plain = "this is the secret message";       
             //encrypt the message
             String secret = caesar.encrypt(plain);               
             System.out.println(" ********* Caesar Cipher Encryption *********");
             System.out.println("PlainText: " + plain);           
             System.out.println("Encrypted: " + secret);
             System.out.println("Decrypted: " + caesar.decrypt(secret));
         } Message was edited by:
    fastmike

  • I/O streams question

    I need to write a program that reads strings from a file in.dat and writes it to a file out.dat How and where in the program would I create the files? Would I have to create an object in order to read or write from the files?

    thanks. I'd done a searh earlier and came up with that link and it helped me quite a bit, but I'm still a little confused. The programming assignment is: (sorry this is a little long thanks for your patience)
    A Caesar cipher is a simple approach to encoding messages by shifting each letter in a message along the alphabet by a constant amount k. For example, if k equals 3, then in an encoded message, each letter is shifted three characters forward: a is replaced with d, b with e, c with f, and so on. The end of the alphabet wraps back around to the beginning. Thus, w is replaced with z, x with a, y with b, and z with c.
    To decode the message, each letter is shifted the same number of characters backwards. Therefore, if k equals 3, the encoded message
    vlpsolflwb iroorzv frpsohalwb
    would be decoded into
    simplicity follows complexity
    Julius Caesar actually used this type of cipher in some of his secret government correspondence (hence the name). Unfortunately, the Caesar cipher is fairly easy to break. There are only 26 possibilities for shifting the characters, and the code can be broken by trying various key values until one works.
    An improvement can be made to this encoding technique if we use a repeating key. Instead of shifting each character by a constant amount, we can shift each character by a different amount using a list of key values. If the message is longer than the list of key values, we just start using the key over again from the beginning. For example, if the key values are
    3 1 7 4 2 5
    then the first character is shifted by three, the second character by one, the third character by seven, etc. After shifting the sixth character by five, we start using the key over again. The seventh character is shifted by three, the eighth by one, etc.
    The figure below shows the message "knowledge is power" encoded using this repeating key. Note that this encryption approach encodes the same letter into different characters, depending on where it occurs in the message and thus which key value is used to encode it. Conversely, the same character in the encoded message is decoded into different characters.
    Encoded Message: n o v a n j g h l m u u r x l v
    Key: 3 1 7 4 2 5 3 1 7 4 2 5 3 1 7 4
    Decoded Message: k n o w l e d g e i s p o w e r
    Write a Java program that uses a repeating key to encode and decode messages. Assume that messages consist of lowercase letters only. Use a queue to store the repeating key. The program reads the input from a file called in.dat and stores the output in a file called out.dat. The first line in the input file is the repeating key. Each subsequent line contains a message that needs to be encoded and decoded. For each message produce four output lines. The first is the original message, the second is the encoded message, the third is the decoded message, and the fourth is a blank line. Sample input and output files are as follows.
    in.dat
    3 1 7 4 2 5
    knowledge is power
    xyzxyz xyzxyz
    you should use two copies of the key stored in two separate queues
    one would be used for encoding and the other for decoding
    good luck
    out.dat
    knowledge is power
    novanjghl mu urxlv
    hmhsjzafx eq klvxn
    xyzxyz xyzxyz
    azgbae azgbae
    uxstwu uxstwu
    you should use two copies of the key stored in two separate queues
    bpb wjtxmk yuj wxv gqulfz sh ykf ria xwpyif nq uds ujsbyevj tvlygx
    vnn ofjrkw qqz qvh ymkfdl kd oed daw nqnkab dk spk qzmzkwrz ntxqcn
    one would be used for encoding and the other for decoding
    rol aqzoe ii wxhe mst jqdvhksj buh vmh palgw ipy hghrepri
    lmx smpic ua snbc ykp zkbhzgid zgz rcb nmdcm cnk zcxlcbje
    good luck
    jpvh nzfl
    dnhz jpzj
    I've already figured out how to write the methods for encoding and decoding. I'm just confused on how to create a file in.dat and read from it using the StringTokenizer. Do I create the files inside the program? Can I tokenize strings in a file simply by creating an object of the FileReader class.
    Thanks for the help I appreciate it greatly.

Maybe you are looking for

  • User cant respond to adadmin question "Continue as though successful Y/N"

    User is SR: 7712716.992 has a form fail to generate during 11i to 12 upgrade. He is at step 12--8 'Compile and generate using adadmin' of task 'Perform the Upgrade' under category 'Upg to Rel 12.0.4' of MW. The following Oracle Forms objects did not

  • Outlook 2010 - Cannot Add or Create a Data File

    I am trying to Add both an existing Data File (.pst) into Outlook to review the emails, and add a New Email Account with a separate Data File from the Default Outlook.pst File. Setup is Windows 7 Pro x64 - Office 2010 Standard I already have 5 Email

  • ITunes & iPhoto Libraries in Time Capsule?

    For months I've been considering buying a Time Capsule. I have several questions before I spend the money and I'm finding contradicting points in the discussion groups and other websites. I have a MacBook with a 60GB HD and I'm rapidly running out of

  • Is it possible to "nest" iWeb pages?

    Is it possible to "nest" iWeb pages?

  • Refreshing mview is hanging after a database level gather stats

    hi guys, can you please help me identify the root cause of this issue. the scenario is this: 1. we have a scheduled unix job that will refresh an mview everyday, from tuesday to saturdays. 2. database maintenance being done during weekends (sundays),