前端密码加密十六位十六进制数作为密钥偏移量,后端Java解码,前端使用CryptoJS,亲测可用 ,注意事项注意事项key和iv都是十六位
注意事项key和iv都是十六位
注意事项key和iv都是十六位
注意事项key和iv都是十六位
前端需要安装CryptoJs,不懂的可以执行百度,google都行,非常简单,一行命令
安装命令:
npm install crypto-js
增加一个js文件 编写加解密代码
//引入刚刚安装的crypto-js
import CryptoJS from '../node_modules/crypto-js/crypto-js.js';
//十六位十六进制数作为密钥
const securityKey = CryptoJS.enc.Utf8.parse("****************");
//十六位十六进制数作为密钥偏移量
const securityIv = CryptoJS.enc.Utf8.parse('****************');
// 解密方法
function decrypt(content,key,iv) {
return CryptoJS.AES.decrypt(content, key, {
mode: CryptoJS.mode.CBC,
iv: iv,
padding: CryptoJS.pad.Pkcs7
}).toString(CryptoJS.enc.Utf8);
}
// 加密方法
function encrypt(content,key,iv) {
const newContent = CryptoJS.enc.Utf8.parse(content);
return CryptoJS.AES.encrypt(newContent, key, {
mode: CryptoJS.mode.CBC,
iv: iv,
padding: CryptoJS.pad.Pkcs7
}).toString();
}
export default {
decrypt,
encrypt,
securityKey,
securityIv
}
java 后台加解密
package com.fast.cloud.common.core.util;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Encoder;
import java.nio.charset.StandardCharsets;
/**
* @author
* AES工具类
*/
public class AESUtil {
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 content 待解密的
* @return 解密后的String
* @throws Exception Exception
*/
public static String aesDecrypt(String content,String key,String iv) throws Exception {
if (StringUtils.isNotBlank(content)){
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
byte[] temp = iv.getBytes(StandardCharsets.UTF_8);
IvParameterSpec ivParameterSpec = new IvParameterSpec(temp);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"), ivParameterSpec);
byte[] decryptBytes = cipher.doFinal(base64Decode(content));
return new String(decryptBytes);
}
return null;
}
/**
* AES加密
* @param content 待加密的
* @return 加密后的String
* @throws Exception Exception
*/
public static String aesEncrypt(String content,String key,String iv) throws Exception {
if (StringUtils.isNotBlank(content)){
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
byte[] temp = iv.getBytes(StandardCharsets.UTF_8);
IvParameterSpec ivParameterSpec = new IvParameterSpec(temp);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"), ivParameterSpec);
byte[] encryptBytes = cipher.doFinal(content.getBytes());
return base64Encoder(encryptBytes);
}
return null;
}
/**
* base 64 加码
*/
public static String base64Encoder(byte[] base64Code){
return new BASE64Encoder().encodeBuffer(base64Code);
}
}
key 和iv都是16位哦