⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 frameencipherdecipher.java

📁 利用SUNJCE进行文件加密
💻 JAVA
字号:
/*
 * FrameEncipherDecipher.java
 *
 * Created on 2007年10月11日, 下午8:51
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package encipherdecipher;

/**
 *
 * @author linda
 */

/**
创建一个Frame,可以创建一个文件,对文件进行加密
*/

// 装载java核心包
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.security.*;
import java.security.spec.*;

// 装入JCE包
import com.sun.crypto.provider.SunJCE;

// 装入java扩展包
import javax.swing.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class FrameEncipherDecipher extends JFrame {

   // 用基于密码的加密-解密算法获取数据
   private static final byte[] salt = {
      ( byte )0xf5, ( byte )0x33, ( byte )0x01, ( byte )0x2a,
      ( byte )0xb2, ( byte )0xcc, ( byte )0xe4, ( byte )0x7f
   };
    
   // 迭代次数
   private int iterationCount = 100;

   // 用户输入组件
   private JTextField passwordTextField;
   private JTextField fileNameTextField;
   private JEditorPane fileContentsEditorPane;
    
   // 构造方法
   public FrameEncipherDecipher() {

      // 设置安全提供者
      Security.addProvider( new SunJCE() );

      // 主窗口初始化
      setSize( new Dimension( 400, 400 ) );
      setTitle( "用SunJCE进行文件的加密和解密" );
      
      // 主界面顶部面板
      JPanel topPanel = new JPanel();     
      topPanel.setBorder( BorderFactory.createLineBorder( 
         Color.black ) );
      topPanel.setLayout( new BorderLayout() );      

      // “密码”和“文件名”标签面板
      JPanel labelsPanel = new JPanel();
      labelsPanel.setLayout( new GridLayout( 2, 1 ) );
      JLabel passwordLabel = new JLabel( " 密  码: " );
      JLabel fileNameLabel = new JLabel( " 文件名: " );
      labelsPanel.add( fileNameLabel );
      labelsPanel.add( passwordLabel );
      topPanel.add( labelsPanel, BorderLayout.WEST );

      // “密码”和“文件名”文本框面板
      JPanel textFieldsPanel = new JPanel();
      textFieldsPanel.setLayout( new GridLayout( 2, 1 ) );
      passwordTextField = new JPasswordField();
      fileNameTextField = new JTextField();
      textFieldsPanel.add( fileNameTextField );
      textFieldsPanel.add( passwordTextField );
      topPanel.add( textFieldsPanel, BorderLayout.CENTER );
     
      // 主界面中部面板
      JPanel middlePanel = new JPanel();
      middlePanel.setLayout( new BorderLayout() );

      // “文件内容”编辑器面板标签
      JLabel fileContentsLabel = new JLabel();
      fileContentsLabel.setText( " 文件内容" );
      middlePanel.add( fileContentsLabel, BorderLayout.NORTH );
      
      // “文件内容”编辑器面板
      fileContentsEditorPane = new JEditorPane();
      middlePanel.add(  
         new JScrollPane( fileContentsEditorPane ),
                          BorderLayout.CENTER );
      
      // 主界面底部面板
      JPanel bottomPanel = new JPanel();
      
      // “加密”按钮
      JButton encryptButton = 
         new JButton( "加密并写入文件" );
      encryptButton.addActionListener( 
      
         new ActionListener() {
            
            public void actionPerformed( ActionEvent event ) 
            {
               encryptAndWriteToFile();
            }
         }
      );
      bottomPanel.add( encryptButton );

      // “解密”按钮
      JButton decryptButton = 
         new JButton( "读取文件并解密" );
      decryptButton.addActionListener( 
      
         new ActionListener() {
      
            public void actionPerformed( ActionEvent event ) {
               readFromFileAndDecrypt();
            }
         }
      );
      bottomPanel.add( decryptButton );

      // 主窗口
      JPanel contentPane = ( JPanel ) this.getContentPane();
      contentPane.setLayout( new BorderLayout() );
      contentPane.add( topPanel, BorderLayout.NORTH );
      contentPane.add( middlePanel, BorderLayout.CENTER );
      contentPane.add( bottomPanel, BorderLayout.SOUTH );
      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);      
   } 
   
   // 获取“文件内容”编辑器面板中的内容并加密
   private void encryptAndWriteToFile() {
   
      // 获取用户输入
      String originalText = fileContentsEditorPane.getText();
      String password = passwordTextField.getText();
      String fileName = fileNameTextField.getText();

      // 创建密钥和Cipher对象
      Cipher cipher = null;
      
      try {
          
         // 从原始密匙数据创建密码(PBEKeySpec对象)
         PBEKeySpec keySpec = 
            new PBEKeySpec( password.toCharArray() );
                  
         // 获取一个密匙工厂实例
         SecretKeyFactory keyFactory = 
            SecretKeyFactory.getInstance( "PBEWithMD5AndDES" );
         
         // 生成加密密钥
         SecretKey secretKey = keyFactory.generateSecret( keySpec );

         // 指定加密参数
         PBEParameterSpec parameterSpec = 
            new PBEParameterSpec( salt, iterationCount );
         
         // 获取Cipher对象实例
         cipher = Cipher.getInstance( "PBEWithMD5AndDES" );
   
         // 在加密模式用密匙初始化Cipher对象(加密)
         cipher.init( Cipher.ENCRYPT_MODE, secretKey, 
            parameterSpec );
      } 
      
      // 处理NoSuchAlgorithmException异常
      catch ( NoSuchAlgorithmException exception ) {
         exception.printStackTrace();
         System.exit( 1 );
      }
      
      // 处理InvalidKeySpecException异常 
      catch ( InvalidKeySpecException exception ) {
         exception.printStackTrace();
         System.exit( 1 );
      }
      
      // 处理InvalidKeyException异常 
      catch ( InvalidKeyException exception ) {
         exception.printStackTrace();
         System.exit( 1 );
      }
      
      // 处理NoSuchPaddingException异常 
      catch ( NoSuchPaddingException exception ) {
         exception.printStackTrace();
         System.exit( 1 );          
      }
      
      // 处理InvalidAlgorithmParameterException异常
      catch ( InvalidAlgorithmParameterException exception ) {
         exception.printStackTrace();
         System.exit( 1 );          
      }
     
      // 创建字节数组
      byte[] outputArray = null;

      try {
         outputArray = originalText.getBytes( "ISO-8859-1" );//GB2312
      } 
      
      // 处理UnsupportedEncodingException异常
      catch ( UnsupportedEncodingException exception ) {
         exception.printStackTrace();
         System.exit( 1 );
      }
      
      // 创建FileOutputStream对象
      File file = new File( fileName );
      FileOutputStream fileOutputStream = null;
      
      try {
         fileOutputStream = new FileOutputStream( file );
      } 
      
      // 处理IOException异常
      catch ( IOException exception ) {
         exception.printStackTrace();
         System.exit( 1 );
      }
      
      // 创建CipherOutputStream对象
      CipherOutputStream out = 
         new CipherOutputStream( fileOutputStream, cipher );
      
      // 写入文件
      try {
         out.write( outputArray );
         out.flush();
         out.close();
      } 
      
      // 处理IOException异常 
      catch ( IOException exception ) {
         exception.printStackTrace();
         System.exit( 1 );
      }
         
      // 创建Vector对象以存储读取的文件内容
      Vector fileBytes = new Vector();

      // 读取文件并显示
      try {
         FileInputStream in = new FileInputStream( file );
            
         // 读取文件
         byte contents;
         
         while ( in.available() > 0 ) {
            contents = ( byte )in.read();
            fileBytes.add( new Byte( contents ) );
         }
           
         in.close();
      } 
      
      // 处理IOException异常
      catch ( IOException exception ) {
         exception.printStackTrace();
         System.exit( 1 );
      }
      
      // Vector对象内容存储到字节数组
      byte[] encryptedText = new byte[ fileBytes.size() ];
      
      for ( int i = 0; i < fileBytes.size(); i++ ) {
         encryptedText[ i ] = 
            ( ( Byte ) fileBytes.elementAt( i ) ).byteValue();
      }
      
      // 更新“文件内容”编辑器面板中的内容
      fileContentsEditorPane.setText( new String( encryptedText ) );      
   }

   // 读取文件并解密
   private void readFromFileAndDecrypt() {

      // 创建Vector对象
      Vector fileBytes = new Vector();
          
      // 获取用户输入
      String password = passwordTextField.getText();
      String fileName = fileNameTextField.getText();

      // 创建Cipher对象
      Cipher cipher = null;
      
      try {
          // 从原始密匙数据创建密码(PBEKeySpec对象)
         PBEKeySpec keySpec = 
            new PBEKeySpec( password.toCharArray() );
                  
         // 获取一个密匙工厂实例
         SecretKeyFactory keyFactory = 
            SecretKeyFactory.getInstance( "PBEWithMD5AndDES" );
         
         // 生成加密密钥
         SecretKey secretKey = keyFactory.generateSecret( keySpec );

         // 指定加密参数
         PBEParameterSpec parameterSpec = 
            new PBEParameterSpec( salt, iterationCount );
         
         // 获取Cipher对象实例
         cipher = Cipher.getInstance( "PBEWithMD5AndDES" );
   
         // 在解密模式用密匙初始化Cipher对象         
          cipher.init( Cipher.DECRYPT_MODE, secretKey, 
            parameterSpec );
      }
      
      // 处理NoSuchAlgorithmException异常
      catch ( NoSuchAlgorithmException exception ) {
         exception.printStackTrace();
         System.exit( 1 );
      }
      
      // 处理InvalidKeySpecException异常 
      catch ( InvalidKeySpecException exception ) {
         exception.printStackTrace();
         System.exit( 1 );
      }
      
      // 处理InvalidKeyException异常 
      catch ( InvalidKeyException exception ) {
         exception.printStackTrace();
         System.exit( 1 );
      }
      
      // 处理NoSuchPaddingException异常 
      catch ( NoSuchPaddingException exception ) {
         exception.printStackTrace();
         System.exit( 1 );          
      }
      
      // 处理InvalidAlgorithmParameterException异常
      catch ( InvalidAlgorithmParameterException exception ) {
         exception.printStackTrace();
         System.exit( 1 );          
      }
           
      // 读取文件并解密
      try {
         File file = new File( fileName );
         FileInputStream fileInputStream = 
            new FileInputStream( file );
         
         CipherInputStream in = 
            new CipherInputStream( fileInputStream, cipher );
         
         // 读取文件
         byte contents = ( byte ) in.read();
         
         while ( contents != -1 ) {   
            fileBytes.add( new Byte( contents ) );
            contents = ( byte ) in.read();
         }           
         in.close();
      
      } 
      
      // 处理IOException异常
      catch ( IOException exception ) {
         exception.printStackTrace();
         System.exit( 1 );
      }
      
      // Vector对象内容存储到字节数组
      byte[] decryptedText = new byte[ fileBytes.size() ];
      
      for ( int i = 0; i < fileBytes.size(); i++ ) {
         decryptedText[ i ] = 
            ( ( Byte )fileBytes.elementAt( i ) ).byteValue();
      }
                
      // 更新“文件内容”编辑器面板中的内容
      fileContentsEditorPane.setText( new String( decryptedText ) );
   }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -