SpringBoot前后端数据传输加密

采用的算法为AES算法

1. 编写加密工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.pibigstar.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

/**
* 前后端数据传输加密工具类
* @author pibigstar
*
*/
public class AesEncryptUtils {
//可配置到Constant中,并读取配置文件注入
private static final String KEY = "abcdef0123456789";

//参数分别代表 算法名称/加密模式/数据填充方式
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

/**
* 加密
* @param content 加密的字符串
* @param encryptKey key值
* @return
* @throws Exception
*/
public static String encrypt(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
byte[] b = cipher.doFinal(content.getBytes("utf-8"));
return Base64.encodeBase64String(b);
}

/**
* 解密
* @param encryptStr 解密的字符串
* @param decryptKey 解密的key值
* @return
* @throws Exception
*/
public static String decrypt(String encryptStr, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
byte[] encryptBytes = Base64.decodeBase64(encryptStr);
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes);
}

public static String encrypt(String content) throws Exception {
return encrypt(content, KEY);
}
public static String decrypt(String encryptStr) throws Exception {
return decrypt(encryptStr, KEY);
}


public static void main(String[] args) throws Exception {
String content = "派大星";
System.out.println("加密前:" + content);

String encrypt = encrypt(content, KEY);
System.out.println("加密后:" + encrypt);

String decrypt = decrypt(encrypt, KEY);
System.out.println("解密后:" + decrypt);
}
}

2. 前端

js 文件下载:https://pan.baidu.com/s/11LnXUnsMtGW5C8sycf2SDQ

导入 js 文件

1
2
3
<script type="text/javascript" src = "js/aes.js"></script>
<script type="text/javascript" src = "js/pad-zeropadding.js"></script>
<script type="text/javascript" src = "js/security.js"></script>

发送数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function sendData() {
alert("发送的数据:"+Encrypt(JSON.stringify({name:"派大星"})));
$.ajax({
type: "POST",
url:"/save",
data:Encrypt(JSON.stringify({name:"派大星"})),
dataType:'json',
contentType: "application/json",
success: function(resData) {
alert("返回的数据:"+resData);
alert("解密之后:"+Decrypt(resData));
alert("解密之后转json对象:"+JSON.parse(Decrypt(resData)).name);
}
});
}
-------------本文结束感谢您的阅读-------------