引入JS (crypto-js.js)(AES.js)
crypto-js.js 链接: https://pan.baidu.com/s/1QFeIBnXh0pbfsQ2GC6MfAw 提取码: jqc6
AES.js
(function(window, undefined){
window.AES = {
encrypt : function(params){
var encrypt = CryptoJS.AES.encrypt(params, CryptoJS.enc.Utf8.parse(aseKey), {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString();
return encrypt;
},
decrypt : function (params){
var decrypt = CryptoJS.AES.decrypt(params, CryptoJS.enc.Utf8.parse(aseKey), {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString(CryptoJS.enc.Utf8);
return decrypt;
}
};
})(window);
声名密匙:此处密匙不是固定,由个人生成,前台后台都可以
var aseKey="497E50CCF9D9431D";
前台调用:
var pwd= AES.encrypt($('#password').val());
后台调用:
此处的方法setAseKeyCook 就是从后台生成一个aseKey,保持前后台的密匙一致才能加密解密
try {
String decrypt = EncryptUtil.aesDecrypt(password, setAseKeyCook());
}
catch (Exception e) {
e.printStackTrace();
return errMsg("密码加密异常");
}
工具类:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
public class EncryptUtil {
private static final String KEY = "abcdefgabcdefg12";
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
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 S