java写的aes加密解密

java写的aes加密解密函数 

java写的aes加密解密

选择文件:

java写的aes加密解密

选择加密后的文件解密

附源代码

import java.awt.EventQueue;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JFrame;


import java.awt.Font;


import org.eclipse.wb.swing.FocusTraversalOnArray;


import java.awt.Component;


import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;


import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import java.security.spec.KeySpec;


import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JTextField;


import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import java.security.spec.KeySpec;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;




public class AES {


private JFrame frmaes;
private JTextField textField;
public static JTextField textField_1;
public static File file;
public static String password;


/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AES window = new AES();
window.frmaes.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}


/**
* Create the application.
*/
public AES() {
initialize();
}


/**
* Initialize the contents of the frame.
*/
public static void encryptFile(File file) throws Exception
    {
        
        FileInputStream inp = new FileInputStream(file);
        
        FileOutputStream out = new FileOutputStream(file+"-Encrypted") ;
        
        System.out.println("Encrypting file: "+file);
        password=textField_1.getText();


        
        //password , iv , salt should be transfered to other end in secure manner
        //salt is used for encoding.
        //salt should be transferred to the recipient securely for decryption
        byte[] salt = new byte[8] ;
        
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(salt);
        
        FileOutputStream saltOut = new FileOutputStream("salt.enc") ;
        
        saltOut.write(salt);
        saltOut.close();
        
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        
        KeySpec keySpec = new PBEKeySpec(password.toCharArray() , salt , 65536 , 256 ) ;
        
        SecretKey secretKey = factory.generateSecret(keySpec) ;
        SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES") ;
        
        
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") ;
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        
        AlgorithmParameters algoParams = cipher.getParameters() ;
        
        //iv adds randomness to text and just makes more secure
        //used while initialising cipher
        FileOutputStream ivOut = new FileOutputStream("iv.enc");
        byte[] iv = algoParams.getParameterSpec(IvParameterSpec.class).getIV() ;
        
        ivOut.write(iv);
        ivOut.close();
        
        
         ///////////////      File Encryption.
         
         
         byte[] input = new byte[64] ;
         int bytesRead ;
         
         while( (bytesRead = inp.read(input)) != -1 )
         {
             byte[] output = cipher.update(input,0,bytesRead) ;
             
             if( output != null )
             {
                 out.write(output);
             }
         }
         
         byte[] output = cipher.doFinal() ;
         
         if( output != null )
         {
             out.write(output);
         }
         
         inp.close();
         out.flush();
         out.close();
        
         System.out.println("File "+file+" Successfully Encrypted.");
         
         ////////////////////////////////////////////////////////
         
    }
    
    
    public static void decryptFile(File file , String password ) throws Exception
    {
        FileInputStream inp = new FileInputStream(file) ;
        
        FileOutputStream out = new FileOutputStream(file+"--Decrypted") ;
        
        System.out.println("Decrypting file : "+file);
        
        //reading salt file
        FileInputStream saltIn = new FileInputStream("salt.enc");
        byte[] salt = new byte[8] ;
        
        saltIn.read(salt) ;
        saltIn.close();
        
        //reading iv file
        FileInputStream ivIn = new FileInputStream("iv.enc");
        byte[] iv = new byte[16];
        
        ivIn.read(iv);
        ivIn.close();
        
        
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1") ;
        
        KeySpec keySpec = new PBEKeySpec(password.toCharArray() , salt , 65536 , 256);
        
        SecretKey secretKey = factory.generateSecret(keySpec) ;
        
        SecretKey secret = new SecretKeySpec(secretKey.getEncoded() , "AES") ;
        
        
        /////////////   File decryption.
        
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") ;
        cipher.init(Cipher.DECRYPT_MODE, secret , new IvParameterSpec(iv) );
        
        byte[] in = new byte[64] ;
        int read ;
        
        while( (read = inp.read(in)) != -1 )
        {
            byte[] output = cipher.update(in ,0 , read);
            
            if( output != null )
            {
                out.write(output);
            }
        }
        
        byte[] output = cipher.doFinal() ;
        
        if( output != null )
        {
            out.write(output);
        }
        
        inp.close();
        out.flush();
        out.close();
        
        System.out.println("File : "+ file +" successfully Decrypted");
    }


private void initialize() {
frmaes = new JFrame();
frmaes.getContentPane().setFont(new Font("隶书", Font.PLAIN, 20));
frmaes.getContentPane().setBackground(new Color(127, 255, 212));
frmaes.setFont(new Font("隶书", Font.PLAIN, 30));
frmaes.setTitle("AES\u52A0\u5BC6");
frmaes.setBounds(100, 100, 450, 324);
frmaes.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel lblaes = new JLabel("AES\u52A0\u5BC6");
lblaes.setFont(new Font("隶书", Font.PLAIN, 30));

JLabel label = new JLabel("\u8BF7\u9009\u62E9\u4E00\u4E2A\u6587\u4EF6\uFF1A");
label.setFont(new Font("隶书", Font.PLAIN, 20));

JButton button = new JButton("\u9009\u62E9\u6587\u4EF6");
button.setFont(new Font("隶书", Font.PLAIN, 20));


JLabel label_1 = new JLabel("\u83B7\u53D6\u7684\u6587\u4EF6\u8DEF\u5F84\u4E3A\uFF1A");
label_1.setFont(new Font("隶书", Font.PLAIN, 20));

textField = new JTextField();
textField.setFont(new Font("隶书", Font.PLAIN, 20));
textField.setColumns(10);

JLabel label_2 = new JLabel("\u8BF7\u8F93\u5165\u79D8\u94A5\uFF1A");
label_2.setFont(new Font("隶书", Font.PLAIN, 20));

textField_1 = new JTextField();
textField_1.setFont(new Font("隶书", Font.PLAIN, 20));
textField_1.setColumns(10);

JLabel label_3 = new JLabel("\u70B9\u51FB\u52A0\u5BC6\uFF1A");
label_3.setFont(new Font("隶书", Font.PLAIN, 20));

JButton button_1 = new JButton("\u52A0\u5BC6\u6587\u4EF6");
button_1.setFont(new Font("隶书", Font.PLAIN, 20));

JLabel label_4 = new JLabel("\u70B9\u51FB\u52A0\u5BC6\uFF1A");
label_4.setFont(new Font("隶书", Font.PLAIN, 20));

JButton button_2 = new JButton("\u89E3\u5BC6\u6587\u4EF6");
button_2.setFont(new Font("隶书", Font.PLAIN, 20));

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser filechooser = new JFileChooser();
int returnValue = filechooser.showOpenDialog(filechooser);
{

if(returnValue == JFileChooser.APPROVE_OPTION)
{
file=filechooser.getSelectedFile();

try {
String path=file.getCanonicalPath();
textField.setText(path);
} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
}

});

button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
encryptFile(file) ;
} catch (Exception e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}

});
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
decryptFile(file , password ) ;
} catch (Exception e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}

});
 

GroupLayout groupLayout = new GroupLayout(frmaes.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(label)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(button))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(label_1)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(label_2)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField_1, GroupLayout.PREFERRED_SIZE, 114, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(label_3)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(button_1))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(label_4)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(button_2))
.addGroup(groupLayout.createSequentialGroup()
.addGap(155)
.addComponent(lblaes)))
.addContainerGap(58, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblaes)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(label)
.addComponent(button))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(label_1)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(label_2)
.addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(label_3)
.addComponent(button_1))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(label_4)
.addComponent(button_2))
.addContainerGap(17, Short.MAX_VALUE))
);
frmaes.getContentPane().setLayout(groupLayout);
frmaes.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{frmaes.getContentPane()}));
}
}