學習python的時候,看到很多會對參數進行加密,于是好奇心驅使下,讓我去了解了下AES加密如何在java中實現。
首先
npm install crypto-js
然后在你的方法中,給你們前端源碼看看,因為我用的ruoyi框架做的實驗,請求可能不是axios發送的請求
<template><div id="app"><div>index2222222</div></div>
</template><script>
import * as echarts from "echarts";
import {listCar} from "@/api/shopcar/car";
import {listSchool, qryName, qryScore} from "@/api/shool/school";
export default {data() {return {// 遮罩層loading: true,// 選中數組ids: [],// 非單個禁用single: true,// 非多個禁用multiple: true,// 顯示搜索條件showSearch: true,// 總條數total: 0,// 【請填寫功能名稱】表格數據carList: [],//測試數組demoList:[],// 彈出層標題title: "",// 是否顯示彈出層open: false,// 查詢參數queryParams: {pageNum: 1,pageSize: 10,spuId: null,spuName: null,skuId: null,skuInfo: null,num: null,tenantId: null,tenantName: null,userId: null,username: null,isSelect: null,addPrice: null,price: null,},// 表單參數form: {},// 表單校驗rules: {}}},created() {},//鉤子函數mounted() {this.qryScore();this.jiami();},methods: {jiami(){// 引入crypto-js庫const CryptoJS = require('crypto-js');
// 定義密鑰const key = CryptoJS.enc.Utf8.parse('1234567890123456'); // 密鑰長度為16字節
// 定義待加密的文件內容const fileContent = 'Hello, World!';
// 加密文件內容const encrypted = CryptoJS.AES.encrypt(fileContent, key, {mode: CryptoJS.mode.ECB, // 加密模式為ECBpadding: CryptoJS.pad.Pkcs7 // 填充方式為Pkcs7});
// 打印加密后的內容console.log('加密后的內容:', encrypted.toString());
// 解密文件內容const decrypted = CryptoJS.AES.decrypt(encrypted, key, {mode: CryptoJS.mode.ECB, // 加密模式為ECBpadding: CryptoJS.pad.Pkcs7 // 填充方式為Pkcs7});
// 打印解密后的內容console.log('解密后的內容:', decrypted.toString(CryptoJS.enc.Utf8));},qryScore() {this.loading = true;qryScore().then(response => {console.log(1234)console.log(response)this.draw(response)});},draw(data) {// 初始化echarts實例let myChart = echarts.init(document.getElementById('myChart'))console.log(this.$echarts)myChart.setOption( {title: {text: 'ECharts 入門示例'},tooltip: {},xAxis: {data: data.name},yAxis: {},series: [{name: '銷量',type: 'bar',data: data.grade}]});}}
}
</script><style>
#app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px;
}
</style>
實現結果
主要代碼
// 引入crypto-js庫
const CryptoJS = require('crypto-js');// 定義密鑰
const key = CryptoJS.enc.Utf8.parse('1234567890123456'); // 密鑰長度為16字節// 定義待加密的文件內容
const fileContent = 'Hello, World!';// 加密文件內容
const encrypted = CryptoJS.AES.encrypt(fileContent, key, {mode: CryptoJS.mode.ECB, // 加密模式為ECBpadding: CryptoJS.pad.Pkcs7 // 填充方式為Pkcs7
});// 打印加密后的內容
console.log('加密后的內容:', encrypted.toString());// 解密文件內容
const decrypted = CryptoJS.AES.decrypt(encrypted, key, {mode: CryptoJS.mode.ECB, // 加密模式為ECBpadding: CryptoJS.pad.Pkcs7 // 填充方式為Pkcs7
});// 打印解密后的內容
console.log('解密后的內容:', decrypted.toString(CryptoJS.enc.Utf8));
然后我們對請求加密。
后端我是參照這個文章寫的,他是真正的大牛,感覺他的文章都寫的好有用,雖然自己看不懂。
AES+自定義密鑰實現加密解密(前端+后端)_crypto aes加密 自定義密鑰-CSDN博客
先生成我們要的秘鑰,然后把我們前端改了就行,我是在spring環境中,記得要在上面文件修改下,因為他好像不是spring環境下的配置。
成功了哈,我根據大佬文件改了改放在spring框架下也能用了,那么大致思路就有了,前端加密,后端解密就行了。
后端解密
大致思路有了,前端根據后端的秘鑰進行加密發送,后端解密即可,偷個小懶我就不寫了。
我把根據大佬修改后適配于spring環境下的配置文件寫在下面了,因為我發現很多文章都只是個類并不適配于spring環境,還要單獨修改,所以我改了那么一點點,弄出了工具類,大家粘貼復制即可。
package com.ruoyi.web.controller.utils;import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;/*** AES 加密工具類*/
@Component
public class AesUtil {// 加密算法RSApublic static final String KEY_ALGORITHM = "AES";//編碼方式public static final String CODE_TYPE = "UTF-8";//填充類型 AES/ECB/PKCS5Padding AES/ECB/ISO10126Paddingpublic static final String AES_TYPE = "AES/ECB/PKCS5Padding";/*** 自定義內容加鹽,生成AES秘鑰*/public String generateAESKey(){return DigestUtils.md5Hex(getSalt(6)).substring(8, 24);}/*** 隨機生成加鹽類*/public String getSalt(int n){char[] chars = ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +"1234567890!@#$%^&*()_+").toCharArray();StringBuilder stringBuilder = new StringBuilder();SecureRandom random = new SecureRandom();for(int i = 0; i < n; i++){stringBuilder.append(chars[random.nextInt(chars.length)]);}return stringBuilder.toString();}/*** 加密* @param clearText 明文* @param aesKey AES秘鑰* @return 加密串*/public String encryptAes(String clearText, String aesKey) {try {SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(), KEY_ALGORITHM);Cipher cipher = Cipher.getInstance(AES_TYPE);cipher.init(Cipher.ENCRYPT_MODE, key);byte[] encryptedData = cipher.doFinal(clearText.getBytes(CODE_TYPE));return new BASE64Encoder().encode(encryptedData);} catch (Exception e) {throw new RuntimeException("加密失敗", e);}}/*** 解密* @param encryptText 密文* @param aesKey AES秘鑰* @return 解密串*/public String decryptAes(String encryptText, String aesKey) {try {byte[] byteMi = new BASE64Decoder().decodeBuffer(encryptText);SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(), KEY_ALGORITHM);Cipher cipher = Cipher.getInstance(AES_TYPE);cipher.init(Cipher.DECRYPT_MODE, key);byte[] decryptedData = cipher.doFinal(byteMi);return new String(decryptedData, CODE_TYPE);} catch (Exception e) {throw new RuntimeException("解密失敗", e);}}// public static void main(String[] args) {
// String aesKey = generateAESKey();
// String json = "中文,abc,!@#";
// //加密
// System.out.println("字符串:" + json);
// String encrypt = encryptAes(json, aesKey);
// System.out.println(encrypt);
// System.out.println("加密后字符串:" + encrypt);
// //私鑰解密
// System.out.println("解密后字符串:" + decryptAes(encrypt, aesKey));
// }}