前后端AES加解密信息交互示例(Java)
后端测试
1、导包
<!-- codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
</dependency>
2、工具类
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AesUtil {
private static String KEY = "1234567890123456"; // 密钥,长度必须是 16
private static String IV = "qwertyuiopasdfgh"; // 偏移量,长度必须是 16
/**
* 加密返回的数据转换成 String 类型
*
* @param content 明文
* @return
* @throws Exception
*/
public static String encrypt(String content) throws Exception {
return base64ToString(AES_CBC_Encrypt(content.getBytes("UTF-8"), KEY.getBytes(), IV.getBytes()));
}
/**
* 将解密返回的数据转换成 String 类型
*
* @param content Base64编码的密文
* @return
* @throws Exception
*/
public static String decrypt(String content) throws Exception {
return new String(AES_CBC_Decrypt(stringToBase64(content), KEY.getBytes(), IV.getBytes()));
}
private static byte[] AES_CBC_Encrypt(byte[] content, byte[] keyBytes, byte[] iv) {
try {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
private static byte[] AES_CBC_Decrypt(byte[] content, byte[] keyBytes, byte[] iv) {
try {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
/**
* 字符串装换成 Base64
*/
public static byte[] stringToBase64(String key) throws Exception {
return Base64.decodeBase64(key.getBytes());
}
/**
* Base64装换成字符串
*/
public static String base64ToString(byte[] key) throws Exception {
return new Base64().encodeToString(key);
}
}
3、测试类
@Test
public void test() throws Exception {
AesUtil aesUtil = new AesUtil();
//jNySGrh34NTgmfJMysmezUwrvWdTsmyZsyTah13+LeWnjJ2g84l6rb1hxsXkbedqNFU9k4dJ6Y7qarA4NmWjzQ==
String content = "username:123456789,password:123,code:中文检测";
//加密
String encrypted = aesUtil.encrypt(content);
//解密
String decrypted = aesUtil.decrypt(encrypted);
System.out.println("加密前:" + content);
System.out.println("加密后:" + encrypted);
System.out.println("解密后:" + decrypted);
}
4、前端交互
import com.bancj.demo1.entity.AjaxResult;
import com.bancj.demo1.utils.AesUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
* Demo
*/
@Controller
@RequestMapping("/api")
public class AesController {
/**
* 将前端发送的信息解密,进行加工后再加密返回给前端
*
* @param content 信息
* @return
*/
@PostMapping("/decrypt")
@ResponseBody
public AjaxResult getInfo(String content) throws Exception {
System.out.println("接收到的值:" + content);
AjaxResult ajaxResult = new AjaxResult();
AesUtil aesUtil = new AesUtil();
//解密
try {
String decrypted = aesUtil.decrypt(content);
System.out.println("解密后的结果:" + decrypted);
decrypted = "服务器经过解密,你传的内容是:" + decrypted;
decrypted = aesUtil.encrypt(decrypted);
System.out.println("----------------------------------------------------");
ajaxResult.setObj(decrypted);
ajaxResult.success("解密成功!");
} catch (Exception e) {
ajaxResult.setObj("填入的信息是无法解密的内容!");
ajaxResult.error("内容无法解析!");
}
return ajaxResult;
}
}
前端测试
1、测试页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>加解密测试页面</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="layui/css/layui.css" media="all">
</head>
<body>
<div style="padding: 20px; background-color: #F2F2F2;">
<div class="layui-row layui-col-space15">
<div class="layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">加密测试</div>
<div class="layui-card-body">
<div class="layui-form-item">
<label class="layui-form-label">加密前内容</label>
<div class="layui-input-block">
<input type="text" id="unLockInfo" autocomplete="off" placeholder="请输入要加密的内容" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="submit" class="layui-btn" lay-submit="" lay-filter="lock1">立即加密</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">加密后内容</label>
<div class="layui-input-block">
<textarea placeholder="" class="layui-textarea" id="lockInfo"></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="layui-col-md6">
<div class="layui-card">
<div class="layui-card-header">解密测试</div>
<div class="layui-card-body">
<div class="layui-form-item">
<label class="layui-form-label">加密后内容</label>
<div class="layui-input-block">
<input type="text" id="lockInfo2" autocomplete="off" placeholder="请输入要解密的内容" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="submit" class="layui-btn" lay-submit="" lay-filter="unLock1">立即解密</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">解密后内容</label>
<div class="layui-input-block">
<textarea placeholder="" class="layui-textarea" id="unLockInfo2"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="padding: 20px; background-color: #F2F2F2;">
<div class="layui-row layui-col-space15">
<div class="layui-col-md12">
<div class="layui-card">
<div class="layui-card-header">后端交互加解密</div>
<div class="layui-card-body">
<div class="layui-form-item">
<label class="layui-form-label">要加密内容</label>
<div class="layui-input-block">
<input type="text" id="unLockInfo3" autocomplete="off" placeholder="请输入内容" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="submit" class="layui-btn" lay-submit="" lay-filter="lock2">进行加密</button>
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">加密后内容</label>
<div class="layui-input-block">
<textarea placeholder="" class="layui-textarea" id="lockInfo3"></textarea>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="submit" class="layui-btn" lay-submit="" lay-filter="send">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">后端返回</label>
<div class="layui-input-block">
<textarea placeholder="" class="layui-textarea" id="lockInfo4"></textarea>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="submit" class="layui-btn" lay-submit="" lay-filter="unLock2">进行解密</button>
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">解密后内容</label>
<div class="layui-input-block">
<textarea placeholder="" class="layui-textarea" id="unLockInfo4"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../layui/layui.js" charset="utf-8"></script>
<script>
layui.use(['form', 'layedit', 'laydate','layer'], function(){
var table = layui.table, form = layui.form, laydate = layui.laydate, layer = layui.layer;
var $ = layui.jquery;
var key = '1234567890123456'; // 密钥 长度16
var iv = 'qwertyuiopasdfgh'; // 偏移量 长度16
//左上角的加密功能
form.on("submit(lock1)", function (data) {
var unLockInfo = $("#unLockInfo").val();
var encrypted = encodeAesString(unLockInfo, key, iv);
$("#lockInfo").val(encrypted);
});
//右上角的解密功能
form.on("submit(unLock1)", function (data) {
var lockInfo2 = $("#lockInfo2").val();
var decryptedStr = decodeAesString(lockInfo2, key, iv);
$("#unLockInfo2").val(decryptedStr);
});
//下方的加密功能
form.on("submit(lock2)", function (data) {
var unLockInfo3 = $("#unLockInfo3").val();
var encrypted = encodeAesString(unLockInfo3, key, iv);
$("#lockInfo3").val(encrypted);
});
//下方的发送功能
form.on("submit(send)", function (data) {
var lockInfo3 = $("#lockInfo3").val();
$.ajax({
async: true,
url: "http://localhost:8080/api/decrypt",
type: "post",
dataType: "json",
data: {content:lockInfo3},
success: function (data) {//这里的success指成功接收后台返回的数据
if (data.result) {//如果data.result为true
layer.msg(data.info);//弹出data.info里面包含的内容提示
$("#lockInfo4").val(data.obj);
} else {
layer.msg(data.info);//弹出data.info里面包含的内容提示
}
}
});
});
//下方的解密功能
form.on("submit(unLock2)", function (data) {
var lockInfo4 = $("#lockInfo4").val();
var decryptedStr = decodeAesString(lockInfo4, key, iv);
$("#unLockInfo4").val(decryptedStr);
});
});
//加密功能
function encodeAesString(data, key, iv) {
var key = CryptoJS.enc.Utf8.parse(key);
var iv = CryptoJS.enc.Utf8.parse(iv);
var encrypted = CryptoJS.AES.encrypt(data, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return encrypted;
}
// 解密功能
function decodeAesString(encrypted, key, iv) {
var key = CryptoJS.enc.Utf8.parse(key);
var iv = CryptoJS.enc.Utf8.parse(iv);
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
</script>
<script src="js/aes.js"></script>
<script src="js/crypto-js.js"></script>
</body>
</html>
此处还需引进aes.js和crypto-js.js,由于篇幅过长就不展示了,可以自行去Git下载完整示例。
2、实际效果
示例下载地址
码云下载地址:https://gitee.com/LHQG/CSDN_show_Demo1.git
CSDN下载地址:https://download.csdn.net/download/qq_41997234/12549109
项目访问地址
http://localhost:8080
以上内容为个人学习及工作笔记,代码均已运行通过,仅供学习参考。如有错误和改进的地方,欢迎指正。