使用AES,前端加密,后端解密,spring工具类了

学习python的时候,看到很多会对参数进行加密,于是好奇心驱使下,让我去了解了下AES加密如何在java中实现。

首先

npm install crypto-js

然后在你的方法中,给你们前端源码看看,因为我用的ruoyi框架做的实验,请求可能不是axios发送的请求

 
  1. <template>

  2. <div id="app">

  3. <div>index2222222</div>

  4. </div>

  5. </template>

  6. <script>

  7. import * as echarts from "echarts";

  8. import {listCar} from "@/api/shopcar/car";

  9. import {listSchool, qryName, qryScore} from "@/api/shool/school";

  10. export default {

  11. data() {

  12. return {

  13. // 遮罩层

  14. loading: true,

  15. // 选中数组

  16. ids: [],

  17. // 非单个禁用

  18. single: true,

  19. // 非多个禁用

  20. multiple: true,

  21. // 显示搜索条件

  22. showSearch: true,

  23. // 总条数

  24. total: 0,

  25. // 【请填写功能名称】表格数据

  26. carList: [],

  27. //测试数组

  28. demoList:[],

  29. // 弹出层标题

  30. title: "",

  31. // 是否显示弹出层

  32. open: false,

  33. // 查询参数

  34. queryParams: {

  35. pageNum: 1,

  36. pageSize: 10,

  37. spuId: null,

  38. spuName: null,

  39. skuId: null,

  40. skuInfo: null,

  41. num: null,

  42. tenantId: null,

  43. tenantName: null,

  44. userId: null,

  45. username: null,

  46. isSelect: null,

  47. addPrice: null,

  48. price: null,

  49. },

  50. // 表单参数

  51. form: {},

  52. // 表单校验

  53. rules: {

  54. }

  55. }

  56. },

  57. created() {

  58. },

  59. //钩子函数

  60. mounted() {

  61. this.qryScore();

  62. this.jiami();

  63. },

  64. methods: {

  65. jiami(){

  66. // 引入crypto-js库

  67. const CryptoJS = require('crypto-js');

  68. // 定义密钥

  69. const key = CryptoJS.enc.Utf8.parse('1234567890123456'); // 密钥长度为16字节

  70. // 定义待加密的文件内容

  71. const fileContent = 'Hello, World!';

  72. // 加密文件内容

  73. const encrypted = CryptoJS.AES.encrypt(fileContent, key, {

  74. mode: CryptoJS.mode.ECB, // 加密模式为ECB

  75. padding: CryptoJS.pad.Pkcs7 // 填充方式为Pkcs7

  76. });

  77. // 打印加密后的内容

  78. console.log('加密后的内容:', encrypted.toString());

  79. // 解密文件内容

  80. const decrypted = CryptoJS.AES.decrypt(encrypted, key, {

  81. mode: CryptoJS.mode.ECB, // 加密模式为ECB

  82. padding: CryptoJS.pad.Pkcs7 // 填充方式为Pkcs7

  83. });

  84. // 打印解密后的内容

  85. console.log('解密后的内容:', decrypted.toString(CryptoJS.enc.Utf8));

  86. },

  87. qryScore() {

  88. this.loading = true;

  89. qryScore().then(response => {

  90. console.log(1234)

  91. console.log(response)

  92. this.draw(response)

  93. });

  94. },

  95. draw(data) {

  96. // 初始化echarts实例

  97. let myChart = echarts.init(document.getElementById('myChart'))

  98. console.log(this.$echarts)

  99. myChart.setOption( {

  100. title: {

  101. text: 'ECharts 入门示例'

  102. },

  103. tooltip: {},

  104. xAxis: {

  105. data: data.name

  106. },

  107. yAxis: {},

  108. series: [

  109. {

  110. name: '销量',

  111. type: 'bar',

  112. data: data.grade

  113. }

  114. ]

  115. });

  116. }

  117. }

  118. }

  119. </script>

  120. <style>

  121. #app {

  122. font-family: Avenir, Helvetica, Arial, sans-serif;

  123. -webkit-font-smoothing: antialiased;

  124. -moz-osx-font-smoothing: grayscale;

  125. text-align: center;

  126. color: #2c3e50;

  127. margin-top: 60px;

  128. }

  129. </style>

实现结果

主要代码

 
  1. // 引入crypto-js库

  2. const CryptoJS = require('crypto-js');

  3. // 定义密钥

  4. const key = CryptoJS.enc.Utf8.parse('1234567890123456'); // 密钥长度为16字节

  5. // 定义待加密的文件内容

  6. const fileContent = 'Hello, World!';

  7. // 加密文件内容

  8. const encrypted = CryptoJS.AES.encrypt(fileContent, key, {

  9. mode: CryptoJS.mode.ECB, // 加密模式为ECB

  10. padding: CryptoJS.pad.Pkcs7 // 填充方式为Pkcs7

  11. });

  12. // 打印加密后的内容

  13. console.log('加密后的内容:', encrypted.toString());

  14. // 解密文件内容

  15. const decrypted = CryptoJS.AES.decrypt(encrypted, key, {

  16. mode: CryptoJS.mode.ECB, // 加密模式为ECB

  17. padding: CryptoJS.pad.Pkcs7 // 填充方式为Pkcs7

  18. });

  19. // 打印解密后的内容

  20. console.log('解密后的内容:', decrypted.toString(CryptoJS.enc.Utf8));

然后我们对请求加密。

后端我是参照这个文章写的,他是真正的大牛,感觉他的文章都写的好有用,虽然自己看不懂。

AES+自定义密钥实现加密解密(前端+后端)_crypto aes加密 自定义密钥-CSDN博客

先生成我们要的秘钥,然后把我们前端改了就行,我是在spring环境中,记得要在上面文件修改下,因为他好像不是spring环境下的配置。

成功了哈,我根据大佬文件改了改放在spring框架下也能用了,那么大致思路就有了,前端加密,后端解密就行了。

后端解密

大致思路有了,前端根据后端的秘钥进行加密发送,后端解密即可,偷个小懒我就不写了。

我把根据大佬修改后适配于spring环境下的配置文件写在下面了,因为我发现很多文章都只是个类并不适配于spring环境,还要单独修改,所以我改了那么一点点,弄出了工具类,大家粘贴复制即可。

 
  1. package com.ruoyi.web.controller.utils;

  2. import org.apache.commons.codec.binary.Hex;

  3. import org.apache.commons.codec.digest.DigestUtils;

  4. import org.springframework.stereotype.Component;

  5. import sun.misc.BASE64Decoder;

  6. import sun.misc.BASE64Encoder;

  7. import javax.crypto.Cipher;

  8. import javax.crypto.KeyGenerator;

  9. import javax.crypto.spec.SecretKeySpec;

  10. import java.nio.charset.StandardCharsets;

  11. import java.security.SecureRandom;

  12. /**

  13. * AES 加密工具类

  14. */

  15. @Component

  16. public class AesUtil {

  17. // 加密算法RSA

  18. public static final String KEY_ALGORITHM = "AES";

  19. //编码方式

  20. public static final String CODE_TYPE = "UTF-8";

  21. //填充类型 AES/ECB/PKCS5Padding AES/ECB/ISO10126Padding

  22. public static final String AES_TYPE = "AES/ECB/PKCS5Padding";

  23. /**

  24. * 自定义内容加盐,生成AES秘钥

  25. */

  26. public String generateAESKey(){

  27. return DigestUtils.md5Hex(getSalt(6)).substring(8, 24);

  28. }

  29. /**

  30. * 随机生成加盐类

  31. */

  32. public String getSalt(int n){

  33. char[] chars = ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +

  34. "1234567890!@#$%^&*()_+").toCharArray();

  35. StringBuilder stringBuilder = new StringBuilder();

  36. SecureRandom random = new SecureRandom();

  37. for(int i = 0; i < n; i++){

  38. stringBuilder.append(chars[random.nextInt(chars.length)]);

  39. }

  40. return stringBuilder.toString();

  41. }

  42. /**

  43. * 加密

  44. * @param clearText 明文

  45. * @param aesKey AES秘钥

  46. * @return 加密串

  47. */

  48. public String encryptAes(String clearText, String aesKey) {

  49. try {

  50. SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(), KEY_ALGORITHM);

  51. Cipher cipher = Cipher.getInstance(AES_TYPE);

  52. cipher.init(Cipher.ENCRYPT_MODE, key);

  53. byte[] encryptedData = cipher.doFinal(clearText.getBytes(CODE_TYPE));

  54. return new BASE64Encoder().encode(encryptedData);

  55. } catch (Exception e) {

  56. throw new RuntimeException("加密失败", e);

  57. }

  58. }

  59. /**

  60. * 解密

  61. * @param encryptText 密文

  62. * @param aesKey AES秘钥

  63. * @return 解密串

  64. */

  65. public String decryptAes(String encryptText, String aesKey) {

  66. try {

  67. byte[] byteMi = new BASE64Decoder().decodeBuffer(encryptText);

  68. SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(), KEY_ALGORITHM);

  69. Cipher cipher = Cipher.getInstance(AES_TYPE);

  70. cipher.init(Cipher.DECRYPT_MODE, key);

  71. byte[] decryptedData = cipher.doFinal(byteMi);

  72. return new String(decryptedData, CODE_TYPE);

  73. } catch (Exception e) {

  74. throw new RuntimeException("解密失败", e);

  75. }

  76. }

  77. // public static void main(String[] args) {

  78. // String aesKey = generateAESKey();

  79. // String json = "中文,abc,!@#";

  80. // //加密

  81. // System.out.println("字符串:" + json);

  82. // String encrypt = encryptAes(json, aesKey);

  83. // System.out.println(encrypt);

  84. // System.out.println("加密后字符串:" + encrypt);

  85. // //私钥解密

  86. // System.out.println("解密后字符串:" + decryptAes(encrypt, aesKey));

  87. // }

  88. }

  • 13
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值