2014-02-19 37 views
1

我有兩個java程序,一個是打開文本文件的gui。還有一種使用MD5加密數據。我怎麼能結合這兩個,所以我的GUI會顯示文件中的文本和文本的加密版本。使用文件測試MD5的Java測試

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 encryptedBuffernew 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
  • 加密的純文本文件,保存它的內容到第二個文件
  • 創建兩個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); 
     } 

    } 

} 

而不是複製的MD5計算,直接和我一樣,你可能只需要調用TestMD5.encryptionMD5,因爲它是一個static方法

0

只需創建PS-第二個JTextArea,並將其文本設置爲TestMD5.encryptionMD5(無論)