前端js加密数据,后端java解密数据的一个解决方案以及代码演示(极简版)
一、前端JS加密(极简版)
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<script>
function simpleEncrypt(data, key) {
// 直接使用ECB模式(无需IV)
return CryptoJS.AES.encrypt(data, key).toString();
}
// 示例
const key = "simplekey1234567"; // 16位密钥(128位)
const encrypted = simpleEncrypt("Hello World", key);
console.log("加密结果:", encrypted); // 输出Base64字符串
</script>
二、后端Java解密(极简版)
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class SimpleDecryptor {
public static String decrypt(String encryptedData, String key) throws Exception {
byte[] keyBytes = key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
return new String(cipher.doFinal(decodedData));
}
// 测试
public static void main(String[] args) throws Exception {
String key = "simplekey1234567";
String encryptedData = "前端生成的加密字符串";
System.out.println(decrypt(encryptedData, key));
}
}
三、核心特点
-
极简实现:
- 前端仅需 3 行加密代码
- 后端仅需 5 行解密代码
- ECB模式省略了IV处理
-
使用要求:
- 密钥长度:16字符(128位)
- 前后端统一使用 AES/ECB/PKCS5Padding 模式