Swing實現AES加密&解密工具升級


引言

在此之前加密解密工具采用的是命令行的方式,下午沒事改用Swing實現一下,使用相對友好些。命令行實現方式傳送門:java獨立小程序實現AES加密和解密

Swing實現步驟

實現效果

加密測試:輸入明文123456

  

 點擊確定將加密后的內容拷貝到剪切板。解密測試:

  

 解密結果:

  

 異常信息以提示框形式彈出:

  

大致流程

  1. 創建Frame窗體
  2. 創建卡片式布局面板
  3. 創建單選按鈕面板
  4. 創建文本框面板
  5. 創建按鈕面板
  6. 創建組合面板
  7. 將單選按鈕和按鈕面板添加到組合面板
  8. 將組合面板添加到窗體
  9. 向單選按鈕面板中填充兩個單選按鈕
  10. 向按鈕面板中填充兩個按鈕
  11. 向文本框面板中添加輸入明文或密文的文本框
  12. 給單選按鈕添加監聽事件
  13. 給按鈕添加監聽事件
  14. 設置窗體相關屬性

實現代碼

項目結構

 

 

  

Swing部分代碼

SwingDemo.java

package com.xgcd;

import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;

public class SwingDemo {

    static final String ENCRYPT = "加密";
    static final String DECRYPT = "解密";
    static final String ENCRYPTTIPS = "請輸入明文:";
    static final String DECRYPTTIPS = "請輸入密文:";
    static final String DEFAULTTIPS = "輸入框內容不得為空!";
    static final String SUCCESSTITLE = "點擊確定拷貝內容到剪切板";

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

    /**
     * 實現加解密業務
     */
    public SwingDemo() {
        /*創建Frame窗體*/
        JFrame mainWin = new JFrame("AES加密&解密工具");
        /*卡片式布局的面板*/
        JPanel cards = new JPanel(new CardLayout());
        /*單選按鈕面板*/
        JPanel radioPanel = new JPanel();
        /*文本框面板*/
        JPanel textPanel = new JPanel();
        /*按鈕面板*/
        JPanel buttonPanel = new JPanel();
        /*組合面板*/
        JPanel combinationPanel = new JPanel();

        /*將單選按鈕和按鈕面板添加到組合面板*/
        combinationPanel.setLayout(new BorderLayout());
        combinationPanel.add(radioPanel, BorderLayout.NORTH);
        combinationPanel.add(textPanel, BorderLayout.CENTER);
        combinationPanel.add(buttonPanel, BorderLayout.SOUTH);

        /*將組合面板添加到窗體*/
        mainWin.add(combinationPanel, BorderLayout.SOUTH);

        /*向單選按鈕面板中填充兩個單選按鈕*/
        radioPanel.setBorder(new TitledBorder(new EtchedBorder(), "請選擇模式"));// 設置單選按鈕的外框標題
        JRadioButton rb1 = new JRadioButton(ENCRYPT, true);//創建JRadioButton對象,默認選中
        JRadioButton rb2 = new JRadioButton(DECRYPT);//創建JRadioButton對象
        radioPanel.add(rb1);
        radioPanel.add(rb2);
        // 將單選按鈕添加到組,實現單選效果
        ButtonGroup jRadioGroup = new ButtonGroup();
        jRadioGroup.add(rb1);
        jRadioGroup.add(rb2);

        /*向按鈕面板中填充兩個按鈕*/
        JButton okButton = new JButton("確定");
        JButton clearButton = new JButton("重置");
        buttonPanel.add(okButton);
        buttonPanel.add(clearButton);

        /*向文本框面板中添加輸入明文或密文的文本框*/
        JTextField contentTextField = new JTextField(28);
        JLabel contentLabel = new JLabel();
        contentLabel.setText(ENCRYPTTIPS);
        textPanel.add(contentLabel);
        textPanel.add(contentTextField);

        /*給單選按鈕添加監聽事件*/
        rb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                contentLabel.setText(ENCRYPTTIPS);// 動態修改標簽文本
                clearJTextField(contentTextField);// 清空文本框內容
            }
        });
        rb2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                contentLabel.setText(DECRYPTTIPS);
                clearJTextField(contentTextField);
            }
        });

        /*給按鈕添加監聽事件*/
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 調用加密或解密邏輯
                String text = contentTextField.getText().trim();// 去掉文本框中字符串前后空格
                if (StringUtils.isEmpty(text)) {
                    // JOptionPane.showMessageDialog(null, DEFAULTTIPS);
                    JOptionPane.showMessageDialog(null, DEFAULTTIPS, "警告", 2);
                    return;
                }

                // 根據單選按鈕組的模式執行響應邏輯
                Enumeration<AbstractButton> jRadioGroupElements = jRadioGroup.getElements();
                while (jRadioGroupElements.hasMoreElements()) {
                    AbstractButton button = jRadioGroupElements.nextElement();
                    if (button.isSelected()) {
                        String buttonText = button.getText();// 按鈕文本域內容
                        if (buttonText.equals(ENCRYPT)) {
                            try {
                                String cleartext = AESDecoder.aesEncrypt(text);
                                JOptionPane.showMessageDialog(null, cleartext, SUCCESSTITLE, JOptionPane.PLAIN_MESSAGE);
                                setSysClipboardText(cleartext);// 拷貝到剪切板
                            } catch (Exception ex) {
                                String message = ex.getMessage();
                                System.out.println(message);
                                JOptionPane.showMessageDialog(null, ex.getMessage(), "錯誤 ", 0);
                            }
                        } else if (buttonText.equals(DECRYPT)) {
                            try {
                                String ciphertext = AESDecoder.aesDecrypt(text);
                                JOptionPane.showMessageDialog(null, ciphertext, SUCCESSTITLE, JOptionPane.PLAIN_MESSAGE);
                                setSysClipboardText(ciphertext);
                            } catch (Exception ex) {
                                String message = ex.getMessage();
                                System.out.println(message);
                                JOptionPane.showMessageDialog(null, ex.getMessage(), "錯誤 ", 0);
                            }
                        }
                        break;
                    }
                }
            }
        });
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                clearJTextField(contentTextField);
            }
        });

        cards.add(combinationPanel, "card1");//向卡片式布局面板中添加面板1
        CardLayout cl = (CardLayout) (cards.getLayout());
        cl.show(cards, "card1");
        mainWin.add(cards);

        /*設置窗體相關屬性*/
        mainWin.setVisible(true);// 窗體可見
        mainWin.setResizable(false);// 禁用最大化
        mainWin.setSize(new Dimension(480, 270));// 窗體寬高
        mainWin.setLocationRelativeTo(mainWin.getOwner());// 窗體位置居中當前屏幕
        mainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 關閉窗口程序停止
    }

    /**
     * 清空文本框內容
     *
     * @param contentTextField
     */
    private void clearJTextField(JTextField contentTextField) {
        contentTextField.setText("");
    }

    /**
     * 實現將字符串復制到剪切板
     *
     * @param writeMe
     */
    public static void setSysClipboardText(String writeMe) {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable tText = new StringSelection(writeMe);
        clip.setContents(tText, null);
    }
}

 

加解密部分代碼

這部分和命令行實現方式無異。

AESDecoder.java

package com.xgcd;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.SecureRandom;

public class AESDecoder {

    //密鑰 (需要前端和后端保持一致)
    public static final String KEY = "NARI@KD_123@Help";
    //算法
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * 隨機生成指定長度的字符串
     */
    public static String getRandomString(int length) { //length表示生成字符串的長度
        String base = "abcdef#ghi$jkl!mno&pqrstu%vwxyz0_@123456789";
        SecureRandom random = new SecureRandom();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * aes解密
     *
     * @param encrypt 內容
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String encrypt) throws Exception {
        return aesDecrypt(encrypt, KEY);
//        try {
//            return aesDecrypt(encrypt, KEY);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return e.getMessage();
//        }
    }

    /**
     * aes加密
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String content) throws Exception {
        return aesEncrypt(content, KEY);
//        try {
//            return aesEncrypt(content, KEY);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return e.getMessage();
//        }
    }

    /**
     * 將byte[]轉為各種進制的字符串
     *
     * @param bytes byte[]
     * @param radix 可以轉換進制的范圍,從Character.MIN_RADIX到Character.MAX_RADIX,超出范圍后變為10進制
     * @return 轉換后的字符串
     */
    public static String binary(byte[] bytes, int radix) {
        return new BigInteger(1, bytes).toString(radix);// 這里的1代表正數
    }

    /**
     * base 64 encode
     *
     * @param bytes 待編碼的byte[]
     * @return 編碼后的base 64 code
     */
    public static String base64Encode(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * base 64 decode
     *
     * @param base64Code 待解碼的base 64 code
     * @return 解碼后的byte[]
     * @throws Exception
     */
    public static byte[] base64Decode(String base64Code) throws Exception {
        return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
    }

    /**
     * AES加密
     *
     * @param content    待加密的內容
     * @param encryptKey 加密密鑰
     * @return 加密后的byte[]
     * @throws Exception
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

        return cipher.doFinal(content.getBytes("utf-8"));
    }

    /**
     * AES加密為base 64 code
     *
     * @param content    待加密的內容
     * @param encryptKey 加密密鑰
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    /**
     * AES解密
     *
     * @param encryptBytes 待解密的byte[]
     * @param decryptKey   解密密鑰
     * @return 解密后的String
     * @throws Exception
     */
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    /**
     * 將base 64 code AES解密
     *
     * @param encryptStr 待解密的base 64 code
     * @param decryptKey 解密密鑰
     * @return 解密后的string
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

    public static String decrypt(String encryptStr) {
        try {
            return aesDecrypt(encryptStr, KEY);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        String encryCont = "";
        try {
            System.out.println(encryCont = AESDecoder.aesEncrypt("Welcome@19"));
            System.out.println(AESDecoder.aesDecrypt(encryCont));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

項目打包

將項目打成可執行jar包,不再贅述。

GitHub代碼

https://github.com/xiguanchendian/Swing

 

感謝

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM