描述
项目前端需要对密码进行加密,防止页面明文暴露密码。 前端使用AES对称加密,后端解密,得到明文密码后再进行非对称加密,然后取出数据库中密码字段进行匹配校验
配置
需要引入依赖
<!--引入 AES/ECB/PKCS7Padding 支持-->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
代码
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import java.security.Security;
@Slf4j
public class AESUtil {
public static String encrypt(String content, String key) throws Exception {
return base64ToString(AES_ECB_Encrypt(content.getBytes(), key.getBytes()));
}
public static String decrypt(String content, String key) {
try {
byte[] base64 = stringToBase64(content);
byte[] bytes = AES_ECB_Decrypt(base64, key.getBytes());
String result = new String(bytes);
return result.replaceAll("\"","");
} catch (Exception e) {
log.info("AES解密出错!!!");
e.printStackTrace();
}
return null;
}
private static byte[] AES_ECB_Encrypt(byte[] content, byte[] keyBytes) {
try {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static byte[] AES_ECB_Decrypt(byte[] content, byte[] keyBytes) {
try {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] stringToBase64(String key) throws Exception {
return Base64.decodeBase64(key.getBytes());
}
public static String base64ToString(byte[] key) throws Exception {
return new Base64().encodeToString(key);
}
public static void main(String[] args) throws Exception {
String key = "5F6B2AK33DZE20A05E74C231B47AC8F6";
String content = "smallkinghjm_2022";
String end = encrypt(content, key);
System.out.println("加密:" + end);
String decrypt = decrypt("a9BN/Zu9fgRLK7631c6+2mwtWomnS9dyW0MYNVgXgjE=", key);
System.out.println("解密:"+decrypt);
}
}
前端JS
const AESEncrypt = (str, key) => {
let _key = key || '5F6B2AK33DZE20A05E74C231B47AC8F6'
const __key = CryptoJS.enc.Utf8.parse(_key)
const encrypt = CryptoJS.AES.encrypt(JSON.stringify(str), __key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
})
return encrypt.toString()
}
const AESDecrypt = (str, key) => {
let _key = key || '5F6B2AK33DZE20A05E74C231B47AC8F6'
const __key = CryptoJS.enc.Utf8.parse(_key)
const decrypt = CryptoJS.AES.decrypt(str, __key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
})
const _decrypt = JSON.parse(decrypt.toString(CryptoJS.enc.Utf8))
return _decrypt
}
|