2014-02-19 2 views
1

У меня есть две java-программы, одна из которых - gui, которая открывает текстовый файл. И тот, который шифрует данные с использованием MD5. Как я могу объединить два, чтобы мой gui отображал текст в файле и зашифрованную версию текста.Тест Java для MD5 с использованием файла

GUI

import java.awt.*; 
import javax.swing.*; 
import java.awt.event.*; 
import java.io.*; 

public class Editor extends JFrame implements WindowListener, ActionListener { 

JTextField fileName; 
JTextArea fileBuffer; 
JButton load, save, quit; 

/** Creates a new instance of Editor */ 
public Editor() { 

this.setLayout(null); 
//  this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); 

JLabel label=new JLabel("File Name: "); 
label.setBounds(10,30,300,20); 
label.setBackground(Color.LIGHT_GRAY); 
this.add(label); 

fileName=new JTextField(); 
fileName.setBounds(10,50,290,20); 
this.add(fileName); 

load=new JButton("Load"); 
load.setBounds(10,80,80,20); 
this.add(load); 

save=new JButton("Save"); 
save.setBounds(110,80,80,20); 
this.add(save); 

quit=new JButton("Quit"); 
quit.setBounds(210,80,80,20); 
this.add(quit); 



fileBuffer=new JTextArea("",10,20); 
JScrollPane p=new JScrollPane(fileBuffer); 

JPanel panel=new JPanel(); 
//  panel.setLayout(new FlowLayout(FlowLayout.CENTER)); 
panel.add(p); 
panel.setBounds(15, 110,275,210); 


this.getContentPane().add(panel); 



this.addWindowListener(this); 
load.addActionListener(this); 
save.addActionListener(this); 
quit.addActionListener(this); 

}//Constructor Editor 


public void actionPerformed(ActionEvent e){ 
    String command=e.getActionCommand(); 
    if (command.equals("Quit")) dispose(); 
    else if (command.equals("Load")) load(); 
    else if (command.equals("Save")) save();  
} 

public void windowClosing(WindowEvent e){dispose();} 
public void windowActivated(WindowEvent e){} 
public void windowClosed(WindowEvent e){} 
public void windowDeactivated(WindowEvent e){} 
public void windowDeiconified(WindowEvent e){} 
public void windowIconified(WindowEvent e){} 
public void windowOpened(WindowEvent e){} 


void load(){ 
    try{ 
     RandomAccessFile input=new RandomAccessFile(fileName.getText() ,"r"); 
     byte buffer[]=new byte [(int) input.length()]; 
     input.read(buffer); 
     input.close(); 
     fileBuffer.setText(new String(buffer));   
    } 
    catch(IOException e) {System.out.println(e);} 

} 

void save(){ 
    try{ 
     FileWriter output= new FileWriter(fileName.getText()); 
     output.write(fileBuffer.getText()); 
     output.close();   
    } 
    catch(IOException e) {System.out.println(e);} 

} 


public static void main(String [] args){ 
    Editor edit=new Editor(); 
    edit.setSize(320,320); 
    edit.setBackground(Color.LIGHT_GRAY); 
    edit.setTitle("Editor de Texto SWING"); 
    edit.setVisible(true);  
} 
} 

MD5 Программа:

import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 

public class TestMD5 
{ 
private static final char[] CONSTS_HEX = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' }; 
public static String encryptionMD5(String token) 
{ 
    try 
    { 
     MessageDigest msgd = MessageDigest.getInstance("MD5"); 
     byte[] bytes = msgd.digest(token.getBytes()); 
     StringBuilder strbMD5 = new StringBuilder(2 * bytes.length); 
     for (int i = 0; i < bytes.length; i++) 
     { 
      int low = (int)(bytes[i] & 0x0f); 
      int high = (int)((bytes[i] & 0xf0) >> 4); 
      strbMD5.append(CONSTS_HEX[high]); 
      strbMD5.append(CONSTS_HEX[low]); 
     } 
     return strbMD5.toString(); 
    }catch (NoSuchAlgorithmException e) { 
      return null; 
    } 
} 

public static void main(String args[]) 
{ 
    String msg01=new String("12345678910"); 
    String msg02=new String("12345678910 "); 
    System.out.println("\n\nMD5 Encryption of" +msg01+": "+encryptionMD5(msg01)); 
    System.out.println("MD5 Encryption of "+msg02+":"+encryptionMD5(msg02)); 
} 

}

ответ

1

Добавить new TextArea say encryptedBuffer к new Scroll Pane и добавить его в JPanel и изменить метод загрузки, как это:

void load(){ 
    try{ 
     RandomAccessFile input=new RandomAccessFile(fileName.getText() ,"r"); 
     byte buffer[]=new byte [(int) input.length()]; 
     input.read(buffer); 
     input.close(); 
     String content = new String(buffer); 
     fileBuffer.setText(content); 
     encryptedBuffer.setText(TestMD5.encryptionMD5(content));   
    } 
    catch(IOException e) {System.out.println(e);} 

} 

Надеется, что это помогает.

+0

Спасибо, ваше предложение обработано – Jessica

+0

@Jessica Ваш прием. Получайте удовольствие от кодирования :) – Sanjeev

1
  • Encrypt равнину файл, сохранив его содержимое на второй файл
  • Создать два JTextArea «с и используйте метод JTextArea#read(Reader, Object) для прочитайте два файла ...

Swing-приложения предназначены для независимой от платформы, по наиболее значимым проблемам поддерживаются различия в рендеринге платформы, в том числе различия шрифтов и DPI, чтобы упомянуть пару.

Swing использует функциональность менеджера компоновки, чтобы уменьшить эту сложность, что позволяет больше сосредоточиться на удобстве использования и рабочем потоке, а не на попытке рассчитать разницу между компонентами из-за различий в способе вывода результатов.

Обновлены например

enter image description here

import java.awt.BorderLayout; 
import java.awt.EventQueue; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.ByteArrayInputStream; 
import java.io.File; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.Reader; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 
import javax.swing.JButton; 
import javax.swing.JFileChooser; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 
import javax.swing.JTextArea; 
import javax.swing.JTextField; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class Crypto { 

    public static void main(String[] args) { 
     new Crypto(); 
    } 

    public Crypto() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new GridBagLayout()); 
       GridBagConstraints gbc = new GridBagConstraints(); 
       gbc.gridx = 0; 
       gbc.gridy = 0; 
       gbc.weighty = 1; 
       gbc.weightx = 1; 
       gbc.fill = GridBagConstraints.BOTH; 

       final FilePane sourcePane = new FilePane(true); 
       final FilePane encryptPane = new FilePane(false); 

       frame.add(sourcePane, gbc); 
       gbc.gridx = 2; 
       frame.add(encryptPane, gbc); 

       JButton encrypt = new JButton("Encrypt >>"); 
       JPanel panel = new JPanel(new GridBagLayout()); 
       panel.add(encrypt); 

       encrypt.addActionListener(new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent e) { 
         File source = sourcePane.getFile(); 
         try (BufferedReader br = new BufferedReader(new FileReader(source))) { 
          char[] buffer = new char[1024]; 
          StringBuilder sb = new StringBuilder(1024); 
          int bytesRead = -1; 
          while ((bytesRead = br.read(buffer)) != -1) { 
           sb.append(buffer, 0, bytesRead); 
          } 
          String encrypted = encryptionMD5(sb.toString()); 

          File enrypt = new File(source.getPath() + ".enrypted"); 
          try (BufferedWriter bw = new BufferedWriter(new FileWriter(enrypt))) { 
           bw.write(encrypted); 
          } catch (Exception exp) { 
           exp.printStackTrace(); 
          } 

          encryptPane.setFile(enrypt); 

         } catch (Exception exp) { 
          exp.printStackTrace(); 
         } 
        } 
       }); 

       gbc.gridx = 1; 
       gbc.weighty = 1; 
       gbc.weightx = 0; 
       gbc.fill = GridBagConstraints.VERTICAL; 
       frame.add(panel, gbc); 

       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public static String encryptionMD5(String token) { 
     char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 
     try { 
      MessageDigest msgd = MessageDigest.getInstance("MD5"); 
      byte[] bytes = msgd.digest(token.getBytes()); 
      StringBuilder strbMD5 = new StringBuilder(2 * bytes.length); 
      for (int i = 0; i < bytes.length; i++) { 
       int low = (int) (bytes[i] & 0x0f); 
       int high = (int) ((bytes[i] & 0xf0) >> 4); 
       strbMD5.append(hex[high]); 
       strbMD5.append(hex[low]); 
      } 
      return strbMD5.toString(); 
     } catch (NoSuchAlgorithmException e) { 
      return null; 
     } 
    } 

    public class FilePane extends JPanel { 

     private JTextField field; 
     private JButton browse; 
     private JTextArea content; 

     private File file; 

     public FilePane(boolean canOpen) { 
      setLayout(new BorderLayout()); 

      field = new JTextField(); 
      field.setEditable(false); 

      content = new JTextArea(20, 20); 
//   content.setLineWrap(true); 
//   content.setWrapStyleWord(true); 
      content.setEditable(false); 

      add(new JScrollPane(content)); 

      JPanel header = new JPanel(new GridBagLayout()); 
      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.gridx = 0; 
      gbc.gridy = 0; 
      gbc.weightx = 1; 
      gbc.fill = GridBagConstraints.HORIZONTAL; 
      header.add(field, gbc); 
      gbc.gridx = 1; 
      gbc.weightx = 0; 
      gbc.fill = GridBagConstraints.NONE; 
      if (canOpen) { 
       browse = new JButton("..."); 
       browse.addActionListener(new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent e) { 
         JFileChooser chooser = new JFileChooser(); 
         chooser.setCurrentDirectory(new File(System.getProperty("user.dir"))); 
         chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); 
         switch (chooser.showOpenDialog(FilePane.this)) { 
          case JFileChooser.APPROVE_OPTION: 
           setFile(chooser.getSelectedFile()); 
           break; 
         } 
        } 
       }); 
       header.add(browse, gbc); 
      } 

      add(header, BorderLayout.NORTH); 

     } 

     public File getFile() { 
      return file; 
     } 

     public void setFile(File f) { 
      file = f; 
      field.setText(file.getPath()); 
      if (file != null) { 
       try (Reader r = new FileReader(file)) { 
        content.read(r, file); 
       } catch (Exception exp) { 
       } 
      } else { 
       content.setText(null); 
      } 
      content.setCaretPosition(0); 
     } 

    } 

} 

ps- Вместо того, чтобы копировать вычисления MD5 непосредственно, как я сделал, вы могли бы просто назвать TestMD5.encryptionMD5, как это static метод

0

Просто создайте a второй JTextArea, и установите его текст на TestMD5.encryptionMD5(независимо от того,)

Смежные вопросы