我是靠谱客的博主 自由柠檬,最近开发中收集的这篇文章主要介绍前后端加密解密前后端加密解密,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

前后端加密解密

前端AES加密参数,RSA加密AES密钥

RSA公钥私钥

//RSA公钥私钥
public static void main(String[] args) {
        //RSA公钥,前端页面保存
        String rsaPublicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJuKaCkL12seqGwO/Vri8ZkBGqPqGn/uyZ6AW3e+8fSxDs6KDf69X4po4xhOMpFto/qZM2OmiCTcULsIlM/4+wcCAwEAAQ==";
        //RSA私钥,后端保存
        String rsaPrivateKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAm4poKQvXax6obA79WuLxmQEao+oaf+7JnoBbd77x9LEOzooN/r1fimjjGE4ykW2j+pkzY6aIJNxQuwiUz/j7BwIDAQABAkAe95d1VJ42/YuauAFJLxXa2JVtPRa5kdkibXvIg4O4q5YD0aQkMrYjw0Wl+JxsfJWxBbNTMqx6TCc2oK2uXUfBAiEA/VXGRQBj4dIjNUrXdvUQl/mD838AukNfNTcHL1C4sbUCIQCdLUY4AYLh47jb7JNoyx4QSgCaSKt2CxIIJ7c6MfgfSwIgWYeLt20I35C9IqNdfEvlXmAu8snKfwk6R3s4Dc+wRhUCIBU/GH3bnnCgks2PxkFlK5QyHLC+YAcd6fsWO0tvk8XPAiEAly64JQEHxTXErTeOwMFEqa31pgksOnbAnLG64EAUoa0=";
    }

前端加密工具类

  1. aes.min.js 提取码:oqdq

  2. jsencrypt.min.js 提取码:3kh3

  3. encryptUtil.js 提取码:rxtd

    // RSA公钥
    var rsaPublicKey = RSA公钥;
    // AES密钥(加密前)
    var aesKey;
    // AES密钥(加密后)
    var aesKeyEncrypt;
    //项目地址
    var address = 'http://localhost:9001/';
    /**
      * aes加密
      *@param word:需要加密的内容
      *@returns {*} :返回加密的内容
      */
    function encryptFun(word) {
        //初始化AES密钥
        aesKey = get32RandomNum();
    
        //加密AES密钥
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey(rsaPublicKey);
        aesKeyEncrypt = encrypt.encrypt(aesKey);
        // console.log("加密后AES密钥 ===> " + aesKeyEncrypt);
    
        //AES加密密钥
        var key = CryptoJS.enc.Utf8.parse(aesKey);
        //AES加密内容
        var srcs =CryptoJS.enc.Utf8.parse(word);
        AES加密
        var encrypted =CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding:CryptoJS.pad.Pkcs7 });
        //返回
        return encrypted.toString();
    }
    
    /**
     * 加密参数
     * @param data
     * @returns {string}
     */
    function getEncryptData(data) {
        return JSON.stringify({"data":encryptFun(JSON.stringify(data))});
    }
    
    /**
     * 获取32位随机码
     * @returns {string}
     */
    function get32RandomNum(){
        var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
        var nums="";
        for(var i=0;i<32;i++){
            var id = parseInt(Math.random()*61);
            nums+=chars[id];
        }
        return nums;
    }
    
    /**
     * ajax请求封装
     * @param url POST请求地址
     * @param data 未加密的请求参数JSON
     * @param success 成功回调
     * @returns {string}
     */
    function encryptAjaxPost(url,data,success) {
        $.ajax({
            url: url,
            contentType: "application/json; charset=utf-8",
            data:getEncryptData(data),
            type: "post",
            async:false,
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("token", aesKeyEncrypt);
                // console.log("aesKeyEncrypt====>" + aesKeyEncrypt);
    
                var authorization = localStorage.getItem("Authorization");
                if (!(authorization || verifyWhiteList(url))){
                    location.href = address;
                }
                XMLHttpRequest.setRequestHeader("Authorization", authorization);
                // XMLHttpRequest.setRequestHeader("Authorization", localStorage.getItem("Authorization"));
                // console.log("Authorization====>" + localStorage.getItem("Authorization"));
            },
            success: function(data) {
                if(data.code == 401){
                    location.href = address;
                }else{
                    success(data);
                }
                // console.info(data);
                // if(data.code == '200'){
                //     var token = data.data.token;
                //     localStorage.setItem("Authorization",data.data.token);
                // }else {
                //     alert(data.message);
                // }
            },
            error : function() {
                console.info("错误");
            }
        });
    }
    
    /**
     * 封装没有参数的GET请求
     * @param url 请求路径
     * @param success 成功回调
     */
    function ajaxGetNoParam(url,success){
        $.ajax({
            url: url,
            type: "get",
            async:false,
            beforeSend: function (XMLHttpRequest) {
                // XMLHttpRequest.setRequestHeader("token", aesKeyEncrypt);
                var authorization = localStorage.getItem("Authorization");
                if (!(authorization || verifyWhiteList(url))){
                    location.href = address;
                }
                XMLHttpRequest.setRequestHeader("Authorization", authorization);
            },
            success: function(data) {
                if(data.code == 401){
                    location.href = address;
                }else{
                    success(data);
                }
            },
            error : function() {
                console.info("错误");
            }
        });
    }
    
    /**
     * 判断url是否在验证白名单中
     * @param url
     */
    function verifyWhiteList(url) {
        var whiteList = ["/login"];
        for (var i = 0;i < whiteList.length;i++){
            if(url.indexOf(whiteList[i]) != -1){
                return true;
            }
        }
        return false;
    }
    
    /**
     * rsa加密
     */
    function rasEncrypt() {
        var publicKey = "替换为Java后台生成的公钥";
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey(publicKey);
        // 这里输出加密后的字符串
        console.log(encrypt.encrypt("你好asd1"));
    }
    
    /**
      * aes加密
      *@param word:需要加密的内容
      *@returns {*} :返回加密的内容
      */
    function encrypt(word) {
        varkey = CryptoJS.enc.Utf8.parse("abcdefgabcdefg12");
        var srcs =CryptoJS.enc.Utf8.parse(word);
        var encrypted =CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding:CryptoJS.pad.Pkcs7 });
        return encrypted.toString();
    }
    
    /**
      * aes解密
      * @param word
      * @returns {*}
      */
    function decrypt(word) {
        var key =CryptoJS.enc.Utf8.parse("abcdefgabcdefg12");
        var decrypt =CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding:CryptoJS.pad.Pkcs7 });
        returnCryptoJS.enc.Utf8.stringify(decrypt).toString();
    }
    
  4. 前端请求

    $(".tpl-login-btn").click(function () {
                    var username = $("#username").prop("value");
                    var password = $("#password").prop("value");
                    var data = {"userName" : username,"passWord" : password};
                    encryptAjaxPost("/login",data,function(data) {
                        console.info(data);
                        if(data.code == '200'){
                            var token = data.data.token;
                            localStorage.setItem("Authorization",data.data.token);
                            location.href = "/pageView/index";
                            // ajaxGetNoParam("/pageView/index",function (data) {
                            //     console.info("成功");
                            //     // $("#htmlAll").html(data);
                            //
                            // })
                        }else {
                            alert(data.message);
                        }
                    });
                });
    

后端解密

创建过滤器解密参数

注:使用过滤器需要在启动类上加扫描注解指定过滤器路径

@SpringBootApplication
@ServletComponentScan(basePackages="com.course.ymx.jwt.security")
public class JwtApplication {
    public static void main(String[] args) {
        SpringApplication.run(JwtApplication.class, args);
    }
}
  1. 过滤器:CustomizeParamsFilter.java

    @Order(2)
    @WebFilter(filterName = "paramsFilter", urlPatterns = "/*", asyncSupported = true)
    public class CustomizeParamsFilter implements Filter {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(CustomizeParamsFilter.class);
    
        @Override
        public void init(FilterConfig filterConfig) {
            LOGGER.debug("Filter initialized");
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            //参数处理
            HandleParamsDecryptHttpServletRequest handleParamsHttpServletRequest = new HandleParamsDecryptHttpServletRequest((HttpServletRequest) servletRequest);
            filterChain.doFilter(handleParamsHttpServletRequest, servletResponse);
        }
    
        @Override
        public void destroy() {
            LOGGER.debug("Filter destroy");
        }
    }
    
  2. 参数处理:HandleParamsDecryptHttpServletRequest.java

    package com.second.boss.estate.security;
    
    import com.alibaba.fastjson.JSONObject;
    import com.second.boss.estate.utils.RSA_EntryptUtil;
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import javax.servlet.ReadListener;
    import javax.servlet.ServletInputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletRequestWrapper;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Enumeration;
    
    public class HandleParamsDecryptHttpServletRequest extends HttpServletRequestWrapper {
    
        private Logger logger = LoggerFactory.getLogger(HandleParamsDecryptHttpServletRequest.class);
        private byte[] bytes;
    
        /**
         * 功能描述: <br>
         * 〈POST请求的RequestBody替换〉
         * @author ymx
         * @date 2019/12/11
         */
        public HandleParamsDecryptHttpServletRequest(HttpServletRequest request) {
    
            super(request);
    
            try (BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
                 ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = bis.read(buffer)) > 0) {
                    baos.write(buffer, 0, len);
                }
                bytes = baos.toByteArray();
                String body = new String(bytes);
                if (!StringUtils.isEmpty(body)) {
                    JSONObject jsonBody = JSONObject.parseObject(body);
                    if (null != jsonBody) {
                        String aesKey = super.getHeader("token");
                        String dataEncrypt = jsonBody.getString("data");
                        String data = null;
                        JSONObject json = null;
                        try {
                            if (StringUtils.isNotBlank(dataEncrypt) && StringUtils.isNotBlank(aesKey)) {
                                data = RSA_EntryptUtil.decryptionRsaAndAes(dataEncrypt, aesKey);
                            }
                            json = null;
                            if (StringUtils.isNotBlank(data)) {
                                json = JSONObject.parseObject(data);
                            }
                        } catch (Exception e) {
                            json = null;
                        }
                        if (json != null) {
                            body = json.toJSONString();
                        }
                        bytes = body.getBytes();
                    }
                }
    
                logger.info("body: {}", body);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 功能描述: <br>
         * 〈POST请求的RequestBody替换〉
         * @author ymx
         * @date 2019/12/11
         */
        @Override
        public BufferedReader getReader() {
            return new BufferedReader(new InputStreamReader(this.getInputStream()));
        }
    
        /**
         * 功能描述: <br>
         * 〈GET 请求替换〉
         * @author ymx
         * @date 2019/12/11
         */
        @Override
        public Enumeration<String> getParameterNames() {
            Enumeration<String> enumeration = super.getParameterNames();
            ArrayList<String> list = Collections.list(enumeration);
            return Collections.enumeration(list);
        }
    
        /**
         * 功能描述: <br>
         * 〈GET 请求替换〉
         * @author ymx
         * @date 2019/12/11
         */
        @Override
        public String getParameter(String name) {
    //        if ("schoolName".equals(name)) {
                return schoolName;
            }
            return super.getParameter(name);
        }
    
        /**
         * 功能描述: <br>
         * 〈GET 请求替换〉
         * @author ymx
         * @date 2019/12/11
         */
        @Override
        public String[] getParameterValues(String name) {
    //        if ("schoolName".equals(name)) {
    //            return new String[]{schoolName};
    //        }
            return super.getParameterValues(name);
        }
    
        /**
         * 功能描述: <br>
         * 〈POST请求的RequestBody替换〉
         * @author ymx
         * @date 2019/12/11
         */
        @Override
        public ServletInputStream getInputStream() {
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            return new ServletInputStream() {
                @Override
                public boolean isFinished() {
                    return false;
                }
    
                @Override
                public boolean isReady() {
                    return false;
                }
    
                @Override
                public void setReadListener(ReadListener readListener) {
    
                }
    
                @Override
                public int read() {
                    return byteArrayInputStream.read();
                }
            };
        }
    }
    

加密工具类

  1. RSA加密工具类:RSA_EntryptUtil.java

    package com.second.boss.estate.utils;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import java.io.UnsupportedEncodingException;
    import java.security.*;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.Base64;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Objects;
    
    public class RSA_EntryptUtil {
        //日志对象
        private static final Logger logger = LoggerFactory.getLogger(RSA_EntryptUtil.class);
        //加密方式
        public static final String KEY_ALGORITHM = "RSA";
        /**
         * 貌似默认是RSA/NONE/PKCS1Padding,未验证
         */
        public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
        public static final String PUBLIC_KEY = "publicKey";
        public static final String PRIVATE_KEY = "privateKey";
        //字符集
        private static final String CHARSET = "UTF-8";
        private static Map<String, byte[]> keyMap;
    
        /**
         * RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024
         */
        public static final int KEY_SIZE = 2048;
    
        static {
            generateKeyBytes();
        }
    
        public static void main(String[] args) throws UnsupportedEncodingException {
            // 加密
            PublicKey publicKey = restorePublicKey(keyMap.get(PUBLIC_KEY));
            byte[] encodedText = encodeBytes(publicKey, "123456".getBytes(CHARSET));
            logger.info("RSA 加密结果:【{}】", Base64.getEncoder().encodeToString(encodedText));
    
            // 解密
            PrivateKey privateKey = restorePrivateKey(keyMap.get(PRIVATE_KEY));
            byte[] decodetext = decodeBytes(privateKey,encodedText);
            logger.info("RSA 解密结果:【{}】", new String(decodetext));
    
            String encryptString = encryptString("我是谁2312313", PUBLIC_KEY);
            logger.info("RSA 加密结果:【{}】", encryptString);
    
            String decryptString = decryptString(encryptString, PRIVATE_KEY);
            logger.info("RSA 解密结果:【{}】", decryptString);
            
            //可以生成公钥私钥,并打印
            //jdkRSA();
        }
    
        /**
         * 给AES密钥解密,再调用AES解密
         * @param encodedText 密文
         * @param aesKeyEncrypt 加密后的AES密钥
         * @return
         */
        public static String decryptionRsaAndAes(String encodedText,String aesKeyEncrypt){
            // 解密
            byte[] decode = Base64.getDecoder().decode("后端私钥");
            PrivateKey privateKey = restorePrivateKey(decode);
            byte[] decodetext = decodeBytes(privateKey, Base64.getDecoder().decode(aesKeyEncrypt));
            //解密后aes密钥
            String aesKey = new String(decodetext);
            String data = AES_DES_EntryptUtil.decryptStringBySecret(encodedText,aesKey);
            return data;
        }
    
        /**
         * 功能描述: <br>
         * 〈生成密钥对。注意这里是生成密钥对KeyPair,再由密钥对获取公私钥〉
         *
         * @author Blare
         * @date 2019/12/11
         */
        public static Map<String, byte[]> generateKeyBytes() {
    
            if (null == keyMap) {
                try {
                    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
                    keyPairGenerator.initialize(KEY_SIZE);
                    KeyPair keyPair = keyPairGenerator.generateKeyPair();
                    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
                    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    
                    keyMap = new HashMap<>();
                    keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
                    keyMap.put(PRIVATE_KEY, privateKey.getEncoded());
                    return keyMap;
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        /**
         * 功能描述: <br>
         * 〈还原公钥,X509EncodedKeySpec 用于构建公钥的规范〉
         *
         * @author Blare
         * @date 2019/12/11
         */
        public static PublicKey restorePublicKey(byte[] keyBytes) {
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
            try {
                KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
                return factory.generatePublic(x509EncodedKeySpec);
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * 功能描述: <br>
         * 〈还原私钥,PKCS8EncodedKeySpec 用于构建私钥的规范〉
         *
         * @author Blare
         * @date 2019/12/11
         */
        public static PrivateKey restorePrivateKey(byte[] keyBytes) {
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
            try {
                KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
                return factory.generatePrivate(pkcs8EncodedKeySpec);
            } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
                e.printStackTrace();
            }
            return null;
        }
        
           /**
        * 功能描述: <br>
        * 〈加密〉
        *
        * @author Blare
        * @date 2019/12/11
        */
       public static byte[] encodeBytes(PublicKey key, byte[] plainText) {
    
           try {
               Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
               cipher.init(Cipher.ENCRYPT_MODE, key);
               return cipher.doFinal(plainText);
           } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
               e.printStackTrace();
           }
           return null;
    
       }
    
       /**
        * 功能描述: <br>
        * 〈解密〉
        *
        * @author Blare
        * @date 2019/12/11
        */
       public static byte[] decodeBytes(PrivateKey key, byte[] encodedText) {
    
           try {
               Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
               cipher.init(Cipher.DECRYPT_MODE, key);
               return cipher.doFinal(encodedText);
           } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
               e.printStackTrace();
           }
           return null;
    
       }
    
       /**
        * 功能描述: <br>
        * 〈字符串加密〉
        *
        * @author Blare
        * @date 2019/12/11
        */
       public static String encryptString(String source, String publicKey) {
           try {
               if (null != keyMap) {
                   PublicKey pk = restorePublicKey(keyMap.get(publicKey));
                   byte[] sourceBytes = source.getBytes(CHARSET);
                   byte[] encryptBytes = encodeBytes(pk, sourceBytes);
                   return Base64.getEncoder().encodeToString(encryptBytes);
               }
           } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
           }
           return null;
       }
    
       /**
        * 功能描述: <br>
        * 〈字符串解密〉
        *
        * @author Blare
        * @date 2019/12/11
        */
       public static String decryptString(String source, String privateKey) {
           if (null != keyMap) {
               PrivateKey pk = restorePrivateKey(keyMap.get(privateKey));
               byte[] sourceBytes = Base64.getDecoder().decode(source);
               byte[] encryptBytes = decodeBytes(pk, sourceBytes);
               return null == encryptBytes ? null : new String(encryptBytes);
           }
           return null;
       }
    
       public static void jdkRSA() {
           try {
               // 1.初始化发送方密钥
               KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
               keyPairGenerator.initialize(512);
               KeyPair keyPair = keyPairGenerator.generateKeyPair();
               RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
               RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
               System.out.println("Public Key:" + Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded()));
               System.out.println("Private Key:" + Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded()));
    
               // 2.私钥加密、公钥解密 ---- 加密
               PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
               KeyFactory keyFactory = KeyFactory.getInstance("RSA");
               PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
               Cipher cipher = Cipher.getInstance("RSA");
               cipher.init(Cipher.ENCRYPT_MODE, privateKey);
               byte[] result = cipher.doFinal("rsa test".getBytes());
               System.out.println("私钥加密、公钥解密 ---- 加密:" + Base64.getEncoder().encodeToString(result));
    
               // 3.私钥加密、公钥解密 ---- 解密
               X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
               keyFactory = KeyFactory.getInstance("RSA");
               PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
               cipher = Cipher.getInstance("RSA");
               cipher.init(Cipher.DECRYPT_MODE, publicKey);
               result = cipher.doFinal(result);
               System.out.println("私钥加密、公钥解密 ---- 解密:" + new String(result));
    
               // 4.公钥加密、私钥解密 ---- 加密
               X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
               KeyFactory keyFactory2 = KeyFactory.getInstance("RSA");
               PublicKey publicKey2 = keyFactory2.generatePublic(x509EncodedKeySpec2);
               Cipher cipher2 = Cipher.getInstance("RSA");
               cipher2.init(Cipher.ENCRYPT_MODE, publicKey2);
               byte[] result2 = cipher2.doFinal("rsa test".getBytes());
               System.out.println("公钥加密、私钥解密 ---- 加密:" + Base64.getEncoder().encodeToString(result2));
    
               // 5.私钥解密、公钥加密 ---- 解密
               PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
               KeyFactory keyFactory5 = KeyFactory.getInstance("RSA");
               PrivateKey privateKey5 = keyFactory5.generatePrivate(pkcs8EncodedKeySpec5);
               Cipher cipher5 = Cipher.getInstance("RSA");
               cipher5.init(Cipher.DECRYPT_MODE, privateKey5);
               byte[] result5 = cipher5.doFinal(result2);
               System.out.println("公钥加密、私钥解密 ---- 解密:" + new String(result5));
    
           } catch (Exception e) {
               e.printStackTrace();
           }
       }
    
       /**
        * 将二进制转换成16进制
        *
        * @param buf
        * @return
        */
       public static String parseByte2HexStr(byte buf[]) {
           StringBuffer sb = new StringBuffer();
           for (int i = 0; i < buf.length; 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
        */
       public static byte[] parseHexStr2Byte(String hexStr) {
           if (hexStr.length() < 1) {
               return null;
           }
           byte[] result = new byte[hexStr.length() / 2];
           for (int i = 0; i < hexStr.length() / 2; 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;
       }
    }
    
  2. AES解密类:AES_DES_EntryptUtil.java

        package com.second.boss.estate.utils;
    
        import org.apache.commons.codec.binary.Hex;
        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
    
        import javax.crypto.*;
        import javax.crypto.spec.DESKeySpec;
        import javax.crypto.spec.SecretKeySpec;
        import java.io.UnsupportedEncodingException;
        import java.security.InvalidKeyException;
        import java.security.Key;
        import java.security.NoSuchAlgorithmException;
        import java.security.SecureRandom;
        import java.security.spec.InvalidKeySpecException;
        import java.util.Base64;
        import java.util.Objects;
    
        /**
         * 〈一句话功能简述〉<br>
         * 〈AES和DES对称加密解密算法实现〉
         *
         * @author ymx
         * @create 2019/12/11
         * @since 1.0.0
         */
        public class AES_DES_EntryptUtil {
    
            //日志对象
            private static final Logger logger = LoggerFactory.getLogger(AES_DES_EntryptUtil.class);
            //DES算法要有一个随机数源,因为Random是根据时间戳生成的有限随机数,比较容易破解,所以在这里使用SecureRandom
            private static SecureRandom secureRandom = new SecureRandom();
            //自定义密钥
            private static final String DEFAULT_SECRET = "wandersgroup2020";
            //字符集
            private static final String CHARSET = "UTF-8";
    
            public static void main(String[] args) {
                desTestencrypt("我是谁2312313".getBytes());
                String encrypt = encryptString("我是谁2312313", SYMMETRY_ENCRYPT.AES);
                logger.info(encrypt);
                String decrypt = decryptString(Objects.requireNonNull("3egzvTepb6UdNGPq31H3Vw=="), SYMMETRY_ENCRYPT.AES);
                logger.info(decrypt);
            }
    
            /**
             * 功能描述: <br>
             * 〈字符串解密〉<密钥参数>
             *
             * @author Blare
             * @date 2019/12/11
             */
            public static String decryptStringBySecret(String source, String secret) {
                try {
                    byte[] sourceBytes = Base64.getDecoder().decode(source);
                    byte[] secretBytes = secret.getBytes(CHARSET);
                    byte[] encryptBytes = decrypt(sourceBytes, secretBytes, SYMMETRY_ENCRYPT.AES);
                    return new String(encryptBytes, CHARSET);
                } catch (InvalidKeyException | NoSuchAlgorithmException | UnsupportedEncodingException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeySpecException e) {
                    e.printStackTrace();
                }
                return null;
            }
    
            /**
             * 功能描述: <br>
             * 〈字符串加密〉
             *
             * @author Blare
             * @date 2019/12/11
             */
            public static String encryptString(String source, SYMMETRY_ENCRYPT encryptType) {
                try {
                    byte[] sourceBytes = source.getBytes(CHARSET);
                    byte[] secretBytes = DEFAULT_SECRET.getBytes(CHARSET);
                    byte[] encryptBytes = encrypt(sourceBytes, secretBytes, encryptType);
                    return Base64.getEncoder().encodeToString(encryptBytes);
                } catch (InvalidKeyException | NoSuchAlgorithmException | UnsupportedEncodingException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeySpecException e) {
                    e.printStackTrace();
                }
                return null;
            }
    
            /**
             * 功能描述: <br>
             * 〈字符串解密〉
             *
             * @author Blare
             * @date 2019/12/11
             */
            public static String decryptString(String source, SYMMETRY_ENCRYPT encryptType) {
                try {
                    byte[] sourceBytes = Base64.getDecoder().decode(source);
                    byte[] secretBytes = DEFAULT_SECRET.getBytes(CHARSET);
                    byte[] encryptBytes = decrypt(sourceBytes, secretBytes, encryptType);
                    return new String(encryptBytes, CHARSET);
                } catch (InvalidKeyException | NoSuchAlgorithmException | UnsupportedEncodingException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeySpecException e) {
                    e.printStackTrace();
                }
                return null;
            }
    
            /**
             * 功能描述: <br>
             * 〈使用原始密钥数据转换为SecretKey对象〉
             *
             * @author Blare
             * @date 2019/12/11
             */
            private static SecretKey getSecretKey(byte[] keyBytes, String type) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
                if ("DES".equals(type)) {
                    // 创建一个密匙工厂
                    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(type);
                    // 创建一个DESKeySpec对象
                    DESKeySpec dks = new DESKeySpec(keyBytes);
                    // 将DESKeySpec对象转换成SecretKey对象
                    return keyFactory.generateSecret(dks);
                }
    
                return new SecretKeySpec(keyBytes, type);
            }
    
            /**
             * 功能描述: <br>
             * 〈DES加密〉
             *
             * @author Blare
             * @date 2019/12/11
             */
            private static byte[] encrypt(byte[] contentArray, byte[] keyArray, SYMMETRY_ENCRYPT encryptType) throws InvalidKeyException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, InvalidKeySpecException {
                return symmetryDE(contentArray, keyArray, Cipher.ENCRYPT_MODE, encryptType);
            }
    
            /**
             * 功能描述: <br>
             * 〈DES解密〉
             *
             * @author Blare
             * @date 2019/12/11
             */
            private static byte[] decrypt(byte[] encryptArray, byte[] keyArray, SYMMETRY_ENCRYPT encryptType) throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
                return symmetryDE(encryptArray, keyArray, Cipher.DECRYPT_MODE, encryptType);
            }
    
            /**
             * 功能描述: <br>
             * 〈Cipher 加密解密操作〉
             *
             * @author Blare
             * @date 2019/12/11
             */
            private static byte[] symmetryDE(byte[] contentArray, byte[] keyArray, int mode, SYMMETRY_ENCRYPT encryptType) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {
                //获取密钥对象
                SecretKey secretKey = getSecretKey(keyArray, encryptType.getType());
                //获取真正执行加/解密操作的Cipher
                Cipher cipher = Cipher.getInstance(encryptType.getEncrypt());
                //用密匙初始化Cipher对象
                cipher.init(mode, secretKey, secureRandom);
                //执行加/解密操作
                return cipher.doFinal(contentArray);
            }
    
            /**
             * 功能描述: <br>
             * 〈加密解密〉
             *
             * @author Blare
             * @date 2019/12/11
             */
            public static void desTestencrypt(byte[] src) {
    
                try {
                    //生成key
                    KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
                    keyGenerator.init(56);
                    SecretKey secretKey = keyGenerator.generateKey();
                    byte[] encoded = secretKey.getEncoded();
                    logger.info("密钥【{}】", Hex.encodeHexString(encoded));
                    //key转换
                    Key key = new SecretKeySpec(encoded, "DES");
                    logger.info("生成的key:【{}】", key);
                    //加密
                    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
                    cipher.init(Cipher.ENCRYPT_MODE, key);
                    byte[] bytes = cipher.doFinal(src);
                    logger.info("JDK自带DES加密结果:【{}】", Hex.encodeHexString(bytes));
                    logger.info("JDK自带DES加密结果:【{}】", Base64.getEncoder().encodeToString(bytes));
                    cipher.init(Cipher.DECRYPT_MODE, key);
                    bytes = cipher.doFinal(bytes);
                    logger.info("JDK自带DES解密结果:【{}】", new String(bytes));
                } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
                    e.printStackTrace();
                }
            }
    
            /**
             * 功能描述: <br>
             * 〈加密方式〉
             *
             * @author Blare
             * @date 2019/12/11
             */
            enum SYMMETRY_ENCRYPT {
                AES("AES", "AES/ECB/PKCS5Padding"),
                DES("DES", "DES/ECB/PKCS5Padding");
    
                SYMMETRY_ENCRYPT(String type, String encrypt) {
                    this.type = type;
                    this.encrypt = encrypt;
                }
    
                private String type;
                private String encrypt;
    
                public String getType() {
                    return type;
                }
    
                public String getEncrypt() {
                    return encrypt;
                }
            }
        }
    

结构

  1. 过滤器位置,如下:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LP0TwsOU-1609149258468)(springboot+jwtimg1579242886.png)]

lidKeyException | BadPaddingException | IllegalBlockSizeException e) {
e.printStackTrace();
}
}

       /**
        * 功能描述: <br>
        * 〈加密方式〉
        *
        * @author Blare
        * @date 2019/12/11
        */
       enum SYMMETRY_ENCRYPT {
           AES("AES", "AES/ECB/PKCS5Padding"),
           DES("DES", "DES/ECB/PKCS5Padding");

           SYMMETRY_ENCRYPT(String type, String encrypt) {
               this.type = type;
               this.encrypt = encrypt;
           }

           private String type;
           private String encrypt;

           public String getType() {
               return type;
           }

           public String getEncrypt() {
               return encrypt;
           }
       }
   }



#### 结构

1. 过滤器位置,如下:

[外链图片转存中...(img-LP0TwsOU-1609149258468)]

最后

以上就是自由柠檬为你收集整理的前后端加密解密前后端加密解密的全部内容,希望文章能够帮你解决前后端加密解密前后端加密解密所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部