js端加密 java后端解密
本加密方法是AES可逆加密。适用于前端加密密码,后端解密密码。保证数据安全等方案。
要引入的js库文件:https://download.csdn.net/download/qq_38973042/10430478
//js前端获取要加密字段 进行加密
var loginPwd = $("#loginpwd_id").val();
loginPwd = encrypt(loginPwd);
//加密方法
function encrypt(word){
var key = CryptoJS.enc.Utf8.parse("abcdefghabcdefgh"); //定义加密的密钥 密钥前端和后端必须一致 且为16位
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();
}
//解密方法
function decrypt(word){
var key = CryptoJS.enc.Utf8.parse("abcdefghabcdefgh"); //定义加密的密钥 密钥前后一致 为16位
var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
//Java后端AES加密和解密
//工具类
package com.bjucloud.mall.common.utils; 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 EncryptUtils { private static final String KEY = "d7b85f6e214abcda"; 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 String(decryptBytes).toString(); } public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception { return aesDecryptByBytes(base64Decode(encryptStr), decryptKey); } public static void main(String[] args) { try { String bb = EncryptUtils.aesEncrypt("123456","abcdefghabcdefgh"); System.out.println(bb); String aa = EncryptUtils.aesDecrypt("Sy93OjPDF5vwNrkTfL9AyA==","abcdefghabcdefgh"); System.out.println(aa); } catch (Exception e) { e.printStackTrace(); } } }