在工作中经常遇到密码明文传输这个问题,为了让密码安全些会让加密,现在有个比较方便的AES加密(前端密钥可能存在泄露风险,应该放到配置项中):
一、前端加密
1、首先引入前端需要用到的js:crypto-js,下载地址:
CryptoJS-v4.1.1
https://www.aliyundrive.com/s/bXP6M8ZxVAD
点击链接保存,或者复制本段内容,打开「阿里云盘」APP ,无需下载极速在线查看,视频原画倍速播放。
2、将 crypto-js 文件放到要引用的路径
3、以下是要引用到的js
<script src="../static/ajax/libs/captcha/crypto-js.min.js" th:src="@{/ajax/libs/captcha/crypto-js.min.js}"></script>
<script src="../static/ajax/libs/captcha/ase.min.js" th:src="@{/ajax/libs/captcha/ase.min.js}"></script>
4、在注册按钮的点击事件中,设置 key 值和 iv 值,这是加密的设置字段,定义要进行加密的密码 encryptedPwd
function register() {var password = $.common.trim($("input[name='password']").val());//AES加密var key = "ABCDEFGHIJKL_key";var iv = "ABCDEFGHIJKLM_iv";var encryptedPwd = aesMinEncrypt(key,iv,password);$.ajax({type: "post",url: ctx + "register",data: {"password": encryptedPwd,......}success: function (res) {}});
}function aesMinEncrypt(key, iv, word){var _word = CryptoJS.enc.Utf8.parse(word),_key = CryptoJS.enc.Utf8.parse(key),_iv = CryptoJS.enc.Utf8.parse(iv);var encrypted = CryptoJS.AES.encrypt(_word, _key, {iv: _iv,mode: CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7});return encrypted.toString();
}
二、后端解密
后端解密需要用到一个工具类:AESUtils,里面是解密方法代码如下:
1、添加AESUtils工具类
package com.wuye.common.utils;import cn.jpush.api.utils.StringUtils;
import sun.misc.BASE64Decoder;import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;/*** TODO** @author CSD* @date 2022-07-28 14:16*/
public class AESUtils {//密钥 (需要前端和后端保持一致)十六位作为密钥private static final String KEY = "ABCDEFGHIJKL_key";//密钥偏移量 (需要前端和后端保持一致)十六位作为密钥偏移量private static final String IV = "ABCDEFGHIJKLM_iv";//算法private static final String ALGORITHMSTR = "AES/CBC/PKCS5Padding";/*** base 64 decode* @param base64Code 待解码的base 64 code* @return 解码后的byte[]* @throws Exception*/public static byte[] base64Decode(String base64Code) throws Exception{return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);}/*** AES解密* @param encryptBytes 待解密的byte[]* @return 解密后的String* @throws Exception*/public static String aesDecryptByBytes(byte[] encryptBytes) throws Exception {Cipher cipher = Cipher.getInstance(ALGORITHMSTR);byte[] temp = IV.getBytes("UTF-8");IvParameterSpec iv = new IvParameterSpec(temp);cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES"), iv);byte[] decryptBytes = cipher.doFinal(encryptBytes);System.out.print(new String(decryptBytes));return new String(decryptBytes);}/*** 将base 64 code AES解密* @param encryptStr 待解密的base 64 code* @return 解密后的string* @throws Exception*/public static String aesDecrypt(String encryptStr) throws Exception {return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr));}//测试一下public static void main(String[] args) throws Exception {String str = "Q uus tQvLdwtGSldhrtKQ==";str = str.replace(" ", "+");System.out.println(str);aesDecrypt(str);}
}
2、在注册方法对 password 进行解密完成加解密操作
String decrypassword = AESUtils.aesDecrypt(password);