import java.awt.*; import java.applet.*; /** Program: ShiftCipher Purpose: do shift cipher in text areas @author: Paul Garrett, garrett@math.umn.edu copyright Paul Garrett, GNU Public License, 1997 @version: Mon Oct 20 11:44:52 CDT 1997 */ final public class ShiftCipher extends Applet { int height, width; Color background_color, foreground_color; TextArea plainTA, cipherTA; Button encryptB, decryptB; TextField keyF; int theKey; boolean queryDataOK; TextField msgF; /***************************/ public void init() { try { background_color = new Color(Integer.parseInt(getParameter("background_color"), 16)); foreground_color = new Color(Integer.parseInt(getParameter("foreground_color"), 16)); height = Integer.parseInt(getParameter("height")); width = Integer.parseInt(getParameter("width")); } catch (Exception e) { background_color = new Color(0xbaaaaa); foreground_color = new Color(0x503030); height = 320; width = 550; } setBackground(background_color); setForeground(foreground_color); setFont(new Font("TimesRoman", Font.PLAIN, 14)); encryptB = new Button("encrypt"); decryptB = new Button("decrypt"); add(encryptB); add(decryptB); keyF = new TextField(5); add(new Label(" Key =")); add(keyF); msgF = new TextField(30); add(msgF); plainTA = new TextArea(5,60); add(plainTA); cipherTA = new TextArea(5,70); add(cipherTA); } // end of init() synchronized String shift(int key, String inp) { // converts to lower-case... and returns lower-case key = ((key % 26) + 26) % 26; byte b; String outp; byte[] theBytes = new byte[inp.length()]; inp.toLowerCase().getBytes(0, inp.length(), theBytes, 0); // latter puts the lower-cased version into "theBytes" for (int i=0; i < theBytes.length; i++) { if (theBytes[i] >= 97 && theBytes[i] < 97+26) { theBytes[i] = (byte) (((theBytes[i] - 97 + key +26)%26) + 97); } } outp = new String(theBytes, 0); // high byte set to 0 return outp; } public synchronized boolean action(Event e, Object arg) { if (e.target instanceof Button) { try { theKey = Integer.parseInt(keyF.getText()); queryDataOK = true; } catch (NumberFormatException nfe) { queryDataOK = false; msgF.setText("The key must be an integer."); } if (queryDataOK) { if (e.target == encryptB) { cipherTA.setText(shift(theKey, plainTA.getText()).toUpperCase()); //__EDIT__ msgF.setText("Encrypting with key "+theKey); } else if (e.target == decryptB) { int neg_key = -theKey; plainTA.setText(shift(-theKey,cipherTA.getText())); //__EDIT__ msgF.setText("Decrypting with key "+theKey); } } else { msgF.setText("Improper data"); } return true; } else { return false; // old AWT event model... } } } /*********** The End ************/