国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

uni-app和springboot完成前端后端對(duì)稱加密解密流程

這篇具有很好參考價(jià)值的文章主要介紹了uni-app和springboot完成前端后端對(duì)稱加密解密流程。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

概述

  • 使用對(duì)稱加密的方式實(shí)現(xiàn)。
  • 前端基于crypto-js。
  • uni-app框架中是在uni.request的基礎(chǔ)上,在攔截器中處理的。
  • springboot在Filter中完成解密工作。

uni-app

  1. 項(xiàng)目中引入crypto-js。
npm install crypto-js
  1. 加密方法
const SECRET_KEY = CryptoJS.enc.Utf8.parse("1234123412341234");

function encrypt (msg) {
	const dataHex = CryptoJS.enc.Utf8.parse(msg);
	const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
	  mode: CryptoJS.mode.ECB,
	  padding: CryptoJS.pad.Pkcs7
	});
	return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}
  1. 解密方法
function decrypt(msg) {
	const encryptedHexStr = CryptoJS.enc.Hex.parse(msg);
	const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
	const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
	    mode: CryptoJS.mode.ECB,
	    padding: CryptoJS.pad.Pkcs7
	});
	return decrypt.toString(CryptoJS.enc.Utf8);
}
  1. request攔截器
uni.addInterceptor('request', {
  invoke(args) {
	let plaintext = JSON.stringify(args.data);
	plaintext = encodeURIComponent(plaintext);
	const textArray = [];
	while(plaintext.length > 15) {
		textArray.push(plaintext.substring(0, 16));
		plaintext = plaintext.substring(16);
	}
	textArray.push(plaintext);
	
	const encryptParamArray = [];
	textArray.forEach(item => {
		encryptParamArray.push(btoa(encrypt(item)));
	})
	
	args.data = {"encryptParams": encryptParamArray};
  },
  success(args) {
  }, 
  fail(err) {
  }, 
  complete(res) {
  }
});
備注
  • 使用encodeURIComponent方法是為了處理 字符“+”,這個(gè)對(duì)應(yīng)java解密的時(shí)候存在問題。
  • 該模式默認(rèn)解密長度出限制在16個(gè)字符中,所以需要將待加密的信息分解成單個(gè)字符長度小于16的字符組成數(shù)組。

Springboot

  1. DecryptFilter,解密攔截器
import cn.hutool.json.JSONUtil;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpMethod;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@WebFilter(urlPatterns = "/*") // 過濾所有請(qǐng)求
public class DecryptFilter implements Filter {

    private String word;
    public DecryptFilter(String word) {
        this.word = word;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

        if (HttpMethod.OPTIONS.matches(httpRequest.getMethod())) {
            filterChain.doFilter(httpRequest, servletResponse);
            return;
        }
        String encryptedData = "";
        if (httpRequest.getHeader("Content-Type").contains("x-www-form-urlencoded")) {
            // 獲取請(qǐng)求參數(shù)或請(qǐng)求體中的加密數(shù)據(jù)
            encryptedData = httpRequest.getParameter("encryptParams");

        } else if (httpRequest.getHeader("Content-Type").contains("json")) {

            StringBuilder stringBuilder = new StringBuilder();
            try (InputStream inputStream = httpRequest.getInputStream();
                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            }

            encryptedData = JSONUtil.parseObj(stringBuilder.toString()).get("encryptParams").toString();
            encryptedData = encryptedData.replaceAll("[\\[\\]\"]", "");
        }

        String[] ciphertextArray = encryptedData.split(",");

        // 解密操作,例如使用AES解密
        String decryptedData = "";
        try {
            decryptedData = decrypt(ciphertextArray);
        } catch (Exception e) {
            throw new RuntimeException("解密失??!", e);
        }

        // 重構(gòu)ServletRequest,將解密后的數(shù)據(jù)設(shè)置到新的ServletRequest中
        ServletRequest modifiedRequest = new BodyRewritingRequestWrapper(httpRequest, decryptedData);

        // 繼續(xù)執(zhí)行過濾器鏈
        filterChain.doFilter(modifiedRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

    private String decrypt(String[] encryptedTextArray) throws Exception {
        StringBuilder paramsJson = new StringBuilder("");

        // 創(chuàng)建解密器
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        byte[] keyBytes = word.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);

        for (String ciphertext : encryptedTextArray) {
            byte[] decode = java.util.Base64.getDecoder().decode(ciphertext);
            byte[] encryptedBytes = Base64.decodeBase64(decode);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            paramsJson.append(new String(decryptedBytes, StandardCharsets.UTF_8));
        }

        return URLDecoder.decode(paramsJson.toString(), "UTF-8");
    }
}
  1. BodyRewritingRequestWrapper,重寫的ServletRequest對(duì)相關(guān)
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class BodyRewritingRequestWrapper extends HttpServletRequestWrapper {
    private String body;

    private JSONObject map;

    public BodyRewritingRequestWrapper(HttpServletRequest request, String body) {
        super(request);
        this.body = body;
        this.map = JSONUtil.parseObj(body);
    }

    @Override
    public String getParameter(String name) {
        if (map.containsKey(name)) {
            return map.get(name).toString();
        }

        return super.getParameter(name);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> originalParameters = super.getParameterMap();
        Map<String, String[]> rewriteMap = new HashMap<>(originalParameters);
        map.forEach((key, value) -> rewriteMap.put(key, new String[]{value.toString()}));
        return rewriteMap;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        return new ServletInputStream() {
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}
  1. 注冊(cè)攔截器
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class WebConfig {

    @Value("${decrypt.word}")
    private String word;

    @Bean
    public FilterRegistrationBean<DecryptFilter> myFilterRegistration() {
        FilterRegistrationBean<DecryptFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new DecryptFilter(word));
        registration.addUrlPatterns("/*");
        registration.setName("decryptFilter");
        registration.setOrder(1);  // 設(shè)置過濾器的順序,根據(jù)實(shí)際需求設(shè)置
        return registration;
    }
}

文章來源地址http://www.zghlxwxcb.cn/news/detail-637083.html

到了這里,關(guān)于uni-app和springboot完成前端后端對(duì)稱加密解密流程的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 后端C# .net 前端uni-app 集成SignalR做即時(shí)通訊

    后端C# .net 前端uni-app 集成SignalR做即時(shí)通訊

    ????????后端集成SignalR比較簡(jiǎn)單,首先要在解決方案中依賴幾個(gè)SignalR的庫,SignalR的庫就是做即時(shí)通訊的主要庫,我們建立連接、收發(fā)信息都需要用這個(gè)庫來進(jìn)行。 ????????除了這幾個(gè)庫以外,還要還有幾個(gè)依賴庫要一并依賴進(jìn)來。 ? ? ? ? Owin庫的作用主要是為了在

    2024年04月17日
    瀏覽(22)
  • 微信小程序外賣跑腿點(diǎn)餐(訂餐)系統(tǒng)(uni-app+SpringBoot后端+Vue管理端技術(shù)實(shí)現(xiàn))

    微信小程序外賣跑腿點(diǎn)餐(訂餐)系統(tǒng)(uni-app+SpringBoot后端+Vue管理端技術(shù)實(shí)現(xiàn))

    自從計(jì)算機(jī)發(fā)展開始,計(jì)算機(jī)軟硬件相關(guān)技術(shù)的發(fā)展速度越來越快,在信息化高速發(fā)展的今天,計(jì)算機(jī)應(yīng)用技術(shù)似乎已經(jīng)應(yīng)用到了各個(gè)領(lǐng)域。 在餐飲行業(yè),除了外賣以外就是到店里就餐,在店里就餐如果需要等待點(diǎn)餐的話,用戶的體驗(yàn)度就會(huì)急劇下降,很多餐飲店也開始開發(fā)

    2024年04月11日
    瀏覽(19)
  • SpringBoot+Vue 后端輸出加密,前端請(qǐng)求統(tǒng)一解密

    針對(duì)客戶對(duì)數(shù)據(jù)交互過程中的加密要求,防止直接的數(shù)據(jù)爬取,對(duì)前后端數(shù)據(jù)請(qǐng)求時(shí)的返回?cái)?shù)據(jù)進(jìn)行數(shù)據(jù)的加密。實(shí)用性嘛,也就那樣了,代碼可直接適配Ruoyi SpringBoot+vue項(xiàng)目,具體加密方式和處理僅供參考! 前端 request.js des.js 后端java

    2024年02月09日
    瀏覽(29)
  • uni-app:請(qǐng)求后端數(shù)據(jù)uni.request

    uni-app:請(qǐng)求后端數(shù)據(jù)uni.request

    ?完整代碼: 核心 使用的方法 uni.request({...}); ?與接口相連接的路徑 注:這里標(biāo)紅的部分為全局變量 例如: url:\\\'https://域名/api/Produce/select_employee\\\'(表示在使用該域名下的api中的Produce文件的select_employee方法) url: getApp().globalData.position + \\\'Produce/select_employee\\\', 傳入數(shù)據(jù)到后端?

    2024年02月16日
    瀏覽(31)
  • uni-app 小程序使用騰訊地圖完成搜索功能

    uni-app 小程序使用騰訊地圖完成搜索功能

    前言 使用uni-app開發(fā)小程序時(shí)候使用騰訊地圖原生SDK是,要把原生寫法轉(zhuǎn)成vue寫法在這記錄一下。 我們需要注意的是使用高德地圖時(shí)我們不僅要引入SDK,還要再uni-app中配置允許使用。 由于uni-app內(nèi)置地圖就是騰訊,所以獲取位置的api,uni.getLocation坐標(biāo)不用轉(zhuǎn)換,直接使用。

    2024年02月08日
    瀏覽(89)
  • springboot工程集成前端編譯包,用于uni-app webView工程,解決其需獨(dú)立部署帶來的麻煩,場(chǎng)景如頁面->畫布->圖片->pdf
  • 三分鐘完成小程序 uni-app、網(wǎng)站接入chatgpt實(shí)現(xiàn)聊天效果

    三分鐘完成小程序 uni-app、網(wǎng)站接入chatgpt實(shí)現(xiàn)聊天效果

    1.實(shí)現(xiàn)后臺(tái)接口 注冊(cè)laf云開發(fā)賬號(hào) https://laf.dev/ 注冊(cè)一個(gè)應(yīng)用后進(jìn)入這個(gè)頁面: 下載依賴 chatgpt 配置apiKey 寫send函數(shù) 配置你的apiKey 2.uni-app小程序代碼中 //封裝cloud 發(fā)送消息方法 微信小程序中使用 3.實(shí)現(xiàn)效果 在這里插入圖片描述

    2024年02月11日
    瀏覽(92)
  • uni-app -- - - - 小程序如何向后端發(fā)送Form Data格式的數(shù)據(jù)

    uni-app -- - - - 小程序如何向后端發(fā)送Form Data格式的數(shù)據(jù)

    接口請(qǐng) 求方式 傳參方式 ,肯定不是一成不變的,當(dāng)遇到如題需求的時(shí)候,要知道, 小程序是沒有FormData對(duì)象 的,那么該怎么操作呢??? 直接上代碼: 效果如圖: 如上所示,這樣寫起來功能實(shí)現(xiàn)了,但是看起來這代碼太不美觀了 效果如圖: 參考文章: 使用wx.request發(fā)送

    2024年02月08日
    瀏覽(15)
  • 前端-vscode中開發(fā)uni-app

    前端-vscode中開發(fā)uni-app

    node -v npm install @vue/ cli@4.5.15 -g 指定版本號(hào):4.5.15 在自己電腦目錄下創(chuàng)建項(xiàng)目: demo02是自己項(xiàng)目名字 在D/AllCode/vs_vue2_uniapp目錄下執(zhí)行一下命令: vue create -p dcloudio/uni-preset-vue demo02 要想在vscode執(zhí)行npm命令 我們打開pages.json和manifest.json,發(fā)現(xiàn)會(huì)報(bào)紅,這是因?yàn)樵趈son中是不能寫注

    2024年01月18日
    瀏覽(47)
  • UNI-APP 人臉識(shí)別分析及實(shí)現(xiàn)(前端)

    實(shí)現(xiàn)流程: 1、打開攝像頭——自動(dòng)讀取照片——傳輸給后端——后端交由第三發(fā)或自主開發(fā)來識(shí)別——返回結(jié)果(相識(shí)度比) 2、打開攝像頭——自動(dòng)讀取視頻——傳輸給后端——后端通過解析視頻,截取圖片交由第三發(fā)或自主開發(fā)來識(shí)別——返回結(jié)果(相識(shí)度比) 通過分

    2023年04月08日
    瀏覽(29)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包