2013-08-16 4 views
1

Je tente de créer un programme de discussion (basé sur this) qui utilise le cryptage AES pour envoyer les données, mais j'ai rencontré quelques problèmes. J'ai bien crypté les messages (je pense ... [Ceci est seulement mon deuxième programme donc je suis vraiment nouveau sur Java]) mais quand j'essaye de décrypter le message, le programme ne trouve pas le symbole "cryptage" qui a été créé . Heres où l'erreur est:Impossible de trouver le symbole/erreur variable

public void run() throws IOException { 

// Make connection and initialize streams 
String serverAddress = getServerAddress(); 
Socket socket = new Socket(serverAddress, 9001); 
in = new BufferedReader(new InputStreamReader(
    socket.getInputStream())); 
out = new PrintWriter(socket.getOutputStream(), true); 
// Process all messages from server, according to the protocol. 
while (true) { 
    String line = in.readLine(); 
if (line.startsWith("SUBMITNAME")) { 
     out.println(getName()); 
    } else if (line.startsWith("NAMEACCEPTED")) { 
     textField.setEditable(true); 
    } else if (line.startsWith("MESSAGE")) { 
       //DECRYPTION 
       messageArea.append(line.substring(8) + "\n"); 
       cipher.init(Cipher.DECRYPT_MODE, key); 
       line = new String(cipher.doFinal(line)); 
       System.out.println(line); 
    } 
} 
} 

Heres où chiffre est créé:

public void actionPerformed(ActionEvent e) { 
    try { 
     String input = (textField.getText()); 
     //ENCRYPTION 
     MessageDigest md5 = MessageDigest.getInstance("MD5"); 
     md5.update("So What's Up Doc?".getBytes()); 

     SecretKeySpec key = new SecretKeySpec(md5.digest(), "AES"); 

     Cipher cipher = Cipher.getInstance("AES"); 
     cipher.init(Cipher.ENCRYPT_MODE, key); 

     byte encryptedMessage[] = cipher.doFinal(input.getBytes()); 
     //Sends the encrypted version of message 
     System.out.println(encryptedMessage); 
     out.println(encryptedMessage); 
     //Clears the input box 
     textField.setText(""); 
    } catch ( NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) { 
     Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    } 

Le code complet est ici:

package Chat.Application; 

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.Socket; 

import javax.swing.JFrame; 
import javax.swing.JOptionPane; 
import javax.swing.JScrollPane; 
import javax.swing.JTextArea; 
import javax.swing.JTextField; 

import java.security.GeneralSecurityException; 
import java.security.InvalidKeyException; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.crypto.BadPaddingException; 
import javax.crypto.Cipher; 
import javax.crypto.IllegalBlockSizeException; 
import javax.crypto.NoSuchPaddingException; 
import javax.crypto.spec.SecretKeySpec; 
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; 
/** 
* A simple Swing-based client for the chat server. Graphically 
* it is a frame with a text field for entering messages and a 
* textarea to see the whole dialog. 
* 
* The client follows the Chat Protocol which is as follows. 
* When the server sends "SUBMITNAME" the client replies with the 
* desired screen name. The server will keep sending "SUBMITNAME" 
* requests as long as the client submits screen names that are 
* already in use. When the server sends a line beginning 
* with "NAMEACCEPTED" the client is now allowed to start 
* sending the server arbitrary strings to be broadcast to all 
* chatters connected to the server. When the server sends a 
* line beginning with "MESSAGE " then all characters following 
* this string should be displayed in its message area. 
*/ 
public class ChatClient { 

    BufferedReader in; 
    PrintWriter out; 
    JFrame frame = new JFrame("ELECTRON Chatroom"); 
    JTextField textField = new JTextField(40); 
    JTextArea messageArea = new JTextArea(8, 40); 

    /** 
    * Constructs the client by laying out the GUI and registering a 
    * listener with the textfield so that pressing Return in the 
    * listener sends the textfield contents to the server. Note 
    * however that the textfield is initially NOT editable, and 
    * only becomes editable AFTER the client receives the NAMEACCEPTED 
    * message from the server. 
    */ 
    public ChatClient() { 

     // Layout GUI 
     textField.setEditable(false); 
     messageArea.setEditable(false); 
     messageArea.setWrapStyleWord(true); 
     messageArea.setLineWrap(true); 
     frame.getContentPane().add(textField, "North"); 
     frame.getContentPane().add(new JScrollPane(messageArea), "Center"); 
     frame.pack(); 
     // Add Listeners 
     textField.addActionListener(new ActionListener() { 
      /** 
      * Responds to pressing the enter key in the textfield by sending 
      * the contents of the text field to the server. Then clear 
      * the text area in preparation for the next message. 
      */ 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      try { 
       String input = (textField.getText()); 
       //ENCRYPTION 
       MessageDigest md5 = MessageDigest.getInstance("MD5"); 
       md5.update("So What's Up Doc?".getBytes()); 

       SecretKeySpec key = new SecretKeySpec(md5.digest(), "AES"); 

       Cipher cipher = Cipher.getInstance("AES"); 
       cipher.init(Cipher.ENCRYPT_MODE, key); 

       byte encryptedMessage[] = cipher.doFinal(input.getBytes()); 
       //Sends the encrypted version of message 
       System.out.println(encryptedMessage); 
       out.println(encryptedMessage); 
       //Clears the input box 
       textField.setText(""); 
      } catch ( NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) { 
       Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); 
      } 
      } 
     }); 
    } 

    /** 
    * Prompt for and return the address of the server. 
    */ 
    private String getServerAddress() { 
     return JOptionPane.showInputDialog(
      frame, 
      "Enter IP Address of the Server:", 
      "ELECTRON Chatroom", 
      JOptionPane.QUESTION_MESSAGE); 
    } 

    /** 
    * Prompt for and return the desired screen name. 
    */ 
    private String getName() { 
     return JOptionPane.showInputDialog(
      frame, 
      "Choose a screen name:", 
      "Screen name selection", 
      JOptionPane.PLAIN_MESSAGE); 
    } 

    /** 
    * Connects to the server then enters the processing loop. 
    */ 
    public void run() throws IOException { 

     // Make connection and initialize streams 
     String serverAddress = getServerAddress(); 
     Socket socket = new Socket(serverAddress, 9001); 
     in = new BufferedReader(new InputStreamReader(
      socket.getInputStream())); 
     out = new PrintWriter(socket.getOutputStream(), true); 
     // Process all messages from server, according to the protocol. 
     while (true) { 
      String line = in.readLine(); 
     if (line.startsWith("SUBMITNAME")) { 
       out.println(getName()); 
      } else if (line.startsWith("NAMEACCEPTED")) { 
       textField.setEditable(true); 
      } else if (line.startsWith("MESSAGE")) { 
         //DECRYPTION 
         messageArea.append(line.substring(8) + "\n"); 
         cipher.init(Cipher.DECRYPT_MODE, key); 
         line = new String(cipher.doFinal(line)); 
         System.out.println(line); 
      } 
     } 
    } 

    /** 
    * Runs the client as an application with a closeable frame. 
    */ 
    public static void main(String[] args) throws Exception { 
     ChatClient client = new ChatClient(); 
     client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     client.frame.setVisible(true); 
     client.run(); 
    } 
} 

Le code de cryptage AES est de here

Je suis sûr que c'est une solution facile un doute la partie de chiffrement AES a quelque chose à voir avec i t mais pourrait aussi bien l'ajouter. Merci pour votre aide! -Silver

EDIT - ERREUR:

no suitable method found for doFinal(String) 
    method Cipher.doFinal(ByteBuffer,ByteBuffer) is not applicable 
     (actual and formal argument lists differ in length) 
    method Cipher.doFinal(byte[],int,int,byte[],int) is not applicable 
     (actual and formal argument lists differ in length) 
    method Cipher.doFinal(byte[],int,int,byte[]) is not applicable 
     (actual and formal argument lists differ in length) 
    method Cipher.doFinal(byte[],int,int) is not applicable 
     (actual and formal argument lists differ in length) 
    method Cipher.doFinal(byte[]) is not applicable 
     (actual argument String cannot be converted to byte[] by method invocation conversion) 
    method Cipher.doFinal(byte[],int) is not applicable 
     (actual and formal argument lists differ in length) 
    method Cipher.doFinal() is not applicable 
     (actual and formal argument lists differ in length) 

Répondre

1

Faire cicher une variable globale. Déclarer au niveau supérieur de votre classe:

Cipher cipher; 

Change:

Cipher cipher = Cipher.getInstance("AES"); 

à:

cipher = Cipher.getInstance("AES"); 

Ajouter un chèque de null ici:

if (cipher != null) { 
    cipher.init(Cipher.DECRYPT_MODE, key); 
    line = new String(cipher.doFinal(line)); 
    System.out.println(line); 
} 

Fondamentalement , la variable cipher on ne sait pas où vous essayez de l'utiliser. Le déclarer au niveau supérieur le rendra visible tout au long de la classe. La vérification null n'est pas requise si actionPerformed(ActionEvent) et run() sont appelés dans cet ordre <.

+0

Tout va mieux, sauf pour la ligne qui comprend "line = new String (cipher.doFinal (line));" où il y a une grosse erreur. J'ai énuméré l'erreur dans ma question – Silver

+0

Une idée sur la façon de résoudre ce problème? Merci aussi pour toute l'aide! – Silver

+0

@Silver Vous voyez cette erreur beacuse: 'Cipher.doFinal()' est une méthode surchargée et aucune des signatures de méthode ne correspond - 'Cipher.doFinal (String)' qui est ce que vous essayez de faire. Jetez un oeil à l'API Cipher et vérifiez que 'Cipher.doFinal (String)' n'existe pas. Je vous suggère de quitter 'AES' pour le moment. – Vikram

Questions connexes