Java and js implement front-end encryption and back-end decryption, and back-end encryption and front-end decryption (Base64)

Table of contents

1. Front-end encryption and back-end decryption

2. Back-end encryption and front-end decryption


When the front-end and back-end data are transmitted, the transmission of private data (such as user name and password) is often involved. At this time, we need to encrypt and decrypt the private data

1. Front-end encryption and back-end decryption

        1.1 Front-end jquery implementation

<script src="js/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {

        var data = "您好+";
        while (data.indexOf("+") > -1) {
            data = data.replace("+", "%2B");
        }
        data = btoa(encodeURI(data));
        console.log("编码后" + data);    //编码后JUU2JTgyJUE4JUU1JUE1JUJEJTI1MkI=
        $.post("/test/testPost", {"data":data},function (data) {

        })
    })
</script>

        1.2 Backend

  @PostMapping("/testPost")
    @ResponseBody
    public int testPost(String data) throws UnsupportedEncodingException {
        System.out.println("解码前" + data);   //解码前JUU2JTgyJUE4JUU1JUE1JUJEJTI1MkI=
        //1.开始解码
        Base64 base64 = new Base64();
        String decode = URLDecoder.decode(new String(base64.decode(data), "utf-8"), "utf-8");
        System.out.println("解码后" + decode);  //解码后您好%2B
        //2.将%2B换回+
        String decodeVo = decode.replace("%2B","+");
        System.out.println("完全解码" + decodeVo);    //完全解码您好+
        return 1;
    }

2. Back-end encryption and front-end decryption

        2.1 Backend encryption

    @GetMapping("/testGet")
    @ResponseBody
    public String testGet(){
        String data = "您好+";
        data = Base64.encodeBase64String(data.getBytes(StandardCharsets.UTF_8));
        System.out.println("编码后" + data);   //编码后5oKo5aW9Kw==
        return data;
    }

        2.2 Front-end decryption (need to introduce Base64.js)  

        Click to extract Base64.js

        Extraction code: cccc

         $.get("/test/testGet",{},function (result) {
            console.log("解码前" + result);   //解码前5oKo5aW9Kw==
            result = Base64.decode(result);
            console.log("解码后" + result);   //解码后您好+
        });

Guess you like

Origin blog.csdn.net/m0_63393739/article/details/126765484