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

 

感谢

 

posted @ 2020-02-29 16:33  习惯沉淀  阅读(921)  评论(0编辑  收藏  举报