一.前台加密,需要引入crypto-js.js库:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jsencrypt的使用</title>
<script src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="js/crypto-js.js" ></script>
<script>
var key = CryptoJS.enc.Utf8.parse('abcdefgabcdefg12');//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
function Encrypt(word){
var srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key,{mode:CryptoJS.mode.ECB,padding:CryptoJS.pad.Pkcs7});
return encrypted.toString();
}
var content = Encrypt("123")
$.ajax({
type:"get",
url:"http://192.168.56.1:8100/aesDecrypt?content="+content,
async:true
});
</script>
</head>
</body>
</html>
二.后端解密:
@RestController
public class SystemController {
private static final String KEY = "abcdefgabcdefg12";
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
@RequestMapping("/aesDecrypt")// 访问接口
public void aesDecrypt(@RequestParam("content") String content) throws Exception {
String decrypt = aesDecrypt(content, KEY);
System.out.println("解密后:" + decrypt);
}
public static String base64Encode(byte[] bytes){
return Base64.encodeBase64String(bytes);
}
public static byte[] base64Decode(String base64Code) throws Exception{
return new BASE64Decoder().decodeBuffer(base64Code);
}
public static byte[] aesEncryptToBytes(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"));
return cipher.doFinal(content.getBytes("utf-8"));
}
public static String aesEncrypt(String content, String encryptKey) throws Exception {
return base64Encode(aesEncryptToBytes(content, encryptKey));
}
public static String aesDecryptByBytes(byte[] encryptBytes, 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[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes);
}
public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
return aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
}
}
js(CryptoJs)前端加密和后端解密
最新推荐文章于 2024-05-13 03:55:19 发布