1.AES加密解密软件界面效果:
2.工程目录:
3.源代码:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JOptionPane;
/**
* @author【轰隆隆】
*
*/
publicclass AES {
/**
* AES加密算法
*/
public AES() {
}
/**
* 加密
* @param content 需要加密的内容
* @param keyWord加密密钥
* @return byte[] 加密后的字节数组
*/
publicstaticbyte[] encrypt(byte[] content, String keyWord) {
try {
KeyGeneratorkgen = KeyGenerator.getInstance("AES"); SecureRandomsecureRandom = SecureRandom.getInstance("SHA1PRNG" ); secureRandom.setSeed(keyWord.getBytes());
kgen.init(128,secureRandom);
SecretKeysecretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器byte[] byteContent = content;
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchPaddingException e) {
JOptionPane.showConfirmDialog(null, "密码有误!", "警告!", 1); } catch (InvalidKeyException e) {
JOptionPane.showConfirmDialog(null, "密码有误!", "警告!", 1);
} catch (IllegalBlockSizeException e) {
JOptionPane.showConfirmDialog(null, "密码有误!", "警告!", 1); } catch (BadPaddingException e) {
JOptionPane.showConfirmDialog(null, "密码有误!", "警告!", 1); } catch(Exception e)
{
JOptionPane.showConfirmDialog(null, "密码有误!", "警告!", 1);
}
returnnull;
}
/**
* @param content 需要加密的内容
* @param password 加密密钥
* @return String 加密后的字符串
*/
publicstatic String encrypttoStr(byte[] content, String password){ return parseByte2HexStr(encrypt(content,password));
}
/**解密
* @param content 待解密内容
* @param keyWord解密密钥
* @return byte[]
*/
publicstaticbyte[] decrypt(byte[] content, String keyWord) {
try {
KeyGeneratorkgen = KeyGenerator.getInstance("AES"); SecureRandomsecureRandom = SecureRandom.getInstance("SHA1PRNG" );
secureRandom.setSeed(keyWord.getBytes());
kgen.init(128,secureRandom);
SecretKeysecretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码
器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
JOptionPane.showMessageDialog(null, "密码有误!", "警告!", 1);
} catch (InvalidKeyException e) {
JOptionPane.showMessageDialog(null, "密码有误!", "警告!", 1);
} catch (IllegalBlockSizeException e) {
JOptionPane.showMessageDialog(null, "密码有误!", "警告!", 1);
} catch (BadPaddingException e) {
JOptionPane.showMessageDialog(null, "密码有误!", "警告!", 1);
}
returnnull;
}
publicstaticbyte[] decrypt(String content, String keyWord) {
return decrypt(parseHexStr2Byte(content),keyWord);
}
/**将二进制转换成16进制
* @param buf
* @return String
*/
publicstatic String parseByte2HexStr(byte buf[]) {
StringBuffersb = new StringBuffer();
for (int i = 0; i String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /**将16进制转换为二进制 * @param hexStr * @return byte[] */ publicstaticbyte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) returnnull; byte[] result = newbyte[hexStr.length()/2]; for (int i = 0;i int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16); int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16); result[i] = (byte) (high * 16 + low); } return result; } /*public static void main(String[] args) { String content = "HongLonglong"; String Key = "https://www.wendangku.net/doc/6a5043416.html,"; //加密 System.out.println("加密前:" + content); String encryptResult = encrypttoStr(content, Key); System.out.println("加密后:" + encryptResult); //解密 byte[] decryptResult = decrypt(encryptResult,Key); System.out.println("解密后:" + new String(decryptResult)); }*/ } importjava.awt.Color; importjava.awt.EventQueue; importjava.awt.Font; importjavax.swing.JButton; importjavax.swing.JFrame; importjavax.swing.JLabel; importjavax.swing.JPanel; importjavax.swing.JTabbedPane; importjavax.swing.SwingConstants; importjavax.swing.border.BevelBorder; importjavax.swing.border.MatteBorder; importjavax.swing.border.TitledBorder; importcom.swtdesigner.SwingResourceManager; public class AesLocher extends JFrame { /** * */ /** * */ /** * */ private static final long serialVersionUID = 1L; /** * Launch the application * @paramargs */ public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { public void run() { try { AesLocher frame = new AesLocher(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame */ publicAesLocher() { super(); setResizable(false); setIconImage(SwingResourceManager.getImage(AesLocher.class, "com/yan/icon1.png")); /*Image icon = Toolkit.getDefaultToolkit().createImage( this.getClass().getResource("com/yan/icon.png")); this.setIconImage(icon);*/ //setIconImage(SwingResourceManager.getImage(AesLocher.class, "com/yan/icon.png")); setFont(new Font("宋体-PUA", Font.PLAIN, 28)); setTitle("AES加密解密器"); getContentPane().setLayout(null); setBounds(100, 100, 375, 334); //Dimension dimension = this.getSize(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); finalJTabbedPanetabbedPane = new JTabbedPane(); tabbedPane.setBounds(0, 0, 367, 307); getContentPane().add(tabbedPane); JPanel panel = new JPanel(); panel.setBorder(new MatteBorder(0, 0, 0, 0, Color.black)); panel.setLayout(null); tabbedPane.setFont(new Font("微软雅黑_GB2312", Font.PLAIN, 14)); tabbedPane.addTab("加密", null, panel, null); finalJButton button_1 = new JButton(); button_1.addActionListener(new MyLockButtonListener(panel)); button_1.setIcon(SwingResourceManager.getIcon(AesLocher.class, "com/yan/unlock.png")); button_1.setText("加密到"); button_1.setBounds(110, 65, 128, 128); panel.add(button_1); finalJPanel panel_2 = new JPanel(); panel_2.setLayout(null); panel_2.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED), "步骤", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("WST_Swed", Font.BOLD | Font.ITALIC, 16), Color.GRAY)); panel_2.setBounds(10, 211, 342, 56); panel.add(panel_2); finalJLabel label = new JLabel(); label.setFont(new Font("楷体_GB2312", Font.ITALIC, 14)); label.setHorizontalAlignment(SwingConstants.CENTER); label.setText("找要加密的文件>>输入密钥>>找到密文存放文件夹"); label.setBounds(10, 15, 322, 34); panel_2.add(label); finalJPanel panel_1 = new JPanel(); panel_1.setLayout(null); tabbedPane.addTab("解密", null, panel_1, null); finalJButton button = new JButton(); button.addActionListener(new MyLockButtonListener(panel_1) ); button.setIcon(SwingResourceManager.getIcon(AesLocher.class, "com/yan/lock.png")); button.setText("jiemi"); button.setBounds(110, 65, 128, 128); panel_1.add(button); finalJPanel panel_3 = new JPanel(); panel_3.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED), "步骤", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("", Font.BOLD | Font.ITALIC, 16), Color.GRAY)); panel_3.setLayout(null); panel_3.setBounds(10, 211, 342, 56); panel_1.add(panel_3); finalJLabel label_1 = new JLabel(); label_1.setHorizontalAlignment(SwingConstants.CENTER); label_1.setFont(new Font("楷体_GB2312", Font.ITALIC, 14)); label_1.setBackground(Color.GREEN); label_1.setBounds(10, 15, 322, 34); label_1.setText("找要解密的文件>>输入密钥>>找到明文存放文件夹"); panel_3.add(label_1); // } } import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.util.Arrays; import java.util.HashMap; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.ProgressMonitor; import javax.swing.ProgressMonitorInputStream; import com.swtdesigner.SwingResourceManager; publicclass MyLockButtonListener implements ActionListener { JPanel panel; File sorFile; String detPathString; String keyString; JTextField jtField; JButton button; static String title; staticint con; static JLabel label; public MyLockButtonListener(JPanel panel) { this.panel=panel; } publicvoid actionPerformed(ActionEvent e) { JFileChooserfDialog = new JFileChooser(); int b = fDialog.showOpenDialog(panel); this.button = (JButton )e.getSource(); if(b == JFileChooser.APPROVE_OPTION) { JLabeljla = new JLabel(new ImageIcon(ClassLoader.getSystemResource("com/yan/key.pn g"))); jla.setBounds(0,0,128,128); sorFile = fDialog.getSelectedFile(); panel.remove(panel.getComponentAt(110, 65)); jtField = new JTextField(); label = new JLabel(title="字节数:"); label.setFont(new Font("微软雅黑_GB2312", https://www.wendangku.net/doc/6a5043416.html,YOUT_NO_LIMIT_CONTEXT, 17)); label.setBounds(140,34,76,39); panel.add(label); panel.add(jla); jtField.addKeyListener(new KeyAdapter(){ publicvoid keyPressed(KeyEvent e) { if(!(e.getSource() instanceof MouseEvent)) { con = jtField.getText().getBytes().length+1; MyLockButtonListener.title+=con; https://www.wendangku.net/doc/6a5043416.html,bel .setText(title); title="字节数:"; } } }); jtField.setBounds(60,90,252,22); panel.add(jtField); JButton button = new JButton("确定"); button.setBounds(panel.getWidth()/2-56,118,106,28); panel.add(button); button.addMouseListener(new MyMouseadapter()); panel.updateUI(); } } class MyMouseadapter extends MouseAdapter { publicvoid mouseClicked(MouseEvent e) { keyString = jtField.getText(); if(jtField.getText().equals("")||jtField.getText()==null) { JOptionPane.showMessageDialog(null, "请你输入密码!", "警告", 1); } else { JPaneljp = (JPanel)panel.getComponentAt(10,211); panel.removeAll(); panel.add(jp); JButtonjButton = new JButton(); jButton.setIcon(SwingResourceManager.getIcon(AesLocher.class, (button.getText().equals("jiemi")?"com/yan/unlock.png":"com/yan/lock .png"))); jButton.setBounds(110, 65, 128, 128); jButton.addMouseListener(new MyunlockPath()); panel.add(jButton); panel.updateUI(); } } } class MyunlockPath extends MouseAdapter { publicvoid mouseClicked(MouseEvent e) { JFileChooserfDialog = new JFileChooser(); int b = fDialog.showSaveDialog(panel); if(b==JFileChooser.APPROVE_OPTION) { detPathString=fDialog.getSelectedFile().getPath(); //System.out.println(detPathString); panel.remove(panel.getComponentAt(110, 65)); JLabel jLabel1 = new JLabel(); jLabel1.setText("源文件: "+sorFile.getPath()); jLabel1.setHorizontalTextPosition(JLabel.LEFT); JLabel jLabel2 = new JLabel(); jLabel2.setText("密钥:"+keyString); jLabel2.setHorizontalTextPosition(JLabel.LEFT); JLabel jLabel3 = new JLabel(); jLabel3.setText("保存路径:"+detPathString); jLabel3.setHorizontalTextPosition(JLabel.LEFT); jLabel1.setBounds(10,40,342,18); jLabel2.setBounds(10,64,342,18); jLabel3.setBounds(10,88,342,18); panel.add(jLabel1); panel.add(jLabel2); panel.add(jLabel3); JButtonstartButton = new JButton("开始"); startButton.addMouseListener(new saveButtonListener()); startButton.setBounds(119,112,106,28); panel.add(startButton); panel.updateUI(); } } } class saveButtonListener extends MouseAdapter { finalstaticint bufferUnit = 1024; int bufferSize; publicvoid mouseClicked(final MouseEvent e) { ((JButton)e.getSource()).setEnabled(false); new Thread() { publicvoid run() { ProgressMonitor progress =null; try{ BufferedInputStream in=null; BufferedOutputStream out=null; in = new BufferedInputStream(new FileInputStream(sorFile)); ProgressMonitorInputStreamdatainInputStream = new ProgressMonitorInputStream(null,button.getText().equals("jiemi")? "文件解密中...":"文件加密中...",in); progress = datainInputStream.getProgressMonitor(); progress.setMillisToDecideToPopup(0); out = new BufferedOutputStream(new FileOutputStream(detPathString)); if(button.getText().equals("jiemi")) { HashMap hm.put((int)'G',bufferUnit); hm.put((int)'H',10*bufferUnit); hm.put((int)'I',100*bufferUnit); hm.put((int)'J',512*bufferUnit); bufferSize = hm.get(datainInputStream.read()); } else { out.write(decbuffersize(datainInputStream.available())); } String midTemp = ""; String prefixTempString = ""; String postfixTempString=""; byte[] b2 =null; int len=0; byte[] bytes = newbyte[bufferSize]; while((len = datainInputStream.read(bytes))!=-1) { byte[] b = Arrays.copyOf(bytes, len); if(button.getText().equals("jiemi")) { int index = byteArrayIndexOf(b,"|".getBytes()[0]); if(index==-1) { midTemp+=new String(b); } else { b2 = Arrays.copyOfRange(b, 0, index); if(b2!=null) { postfixTempString = new String(b2); } String enCodeBlock = prefixTempString+midTemp+postfixTempString; midTemp = ""; out.write(AES.decrypt(enCodeBlock, keyString)); b2=Arrays.copyOfRange(b, index+1, b.length); if(b2!=null) { prefixTempString=new String(b2); } } } else { String str = AES.encrypttoStr(b, keyString); out.write(str.getBytes()); out.write("|".getBytes()); } } if(!(button.getText().equals("jiemi"))) { BufferedWriterbWriter = new BufferedWriter(new FileWriter(new File(new File(detPathString).getParent(),"key.txt"))); bWriter.write(keyString); bWriter.flush(); bWriter.close(); } out.flush(); out.close(); in.close(); } catch (Exception e) { progress.close(); //e.printStackTrace(); } ((JButton)e.getSource()).setText("完成!"); } }.start(); } publicint byteArrayIndexOf(byte[] bt,byte by) { //ArrayList for(int i=0;i { if(bt[i]==by) { return i; } } return -1; } publicint decbuffersize (int s) { int defBuffersize = 1024*1024; if(s { bufferSize = bufferUnit; return'G'; } elseif(s<10*defBuffersize) { bufferSize = 10*bufferUnit; return'H'; } elseif(s<100*defBuffersize) { bufferSize = 100*bufferUnit; return'I'; } else { bufferSize = 512*bufferUnit; return'J'; } } } }