前端 JS 使用 RAS 加密密码,后端 Java 解密(适配 JDK6)
首先,需要安装 Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files,以支持 AES-256 加解密。
前端 JS 加密密码:
// 密码明文
var password = '123456';
// 生成随机盐值
var salt = CryptoJS.lib.WordArray.random(16);
// 生成密钥
var key = CryptoJS.PBKDF2(password, salt, {
keySize: 256 / 32,
iterations: 1000
});
// 生成向量
var iv = CryptoJS.lib.WordArray.random(16);
// 加密
var ciphertext = CryptoJS.AES.encrypt('hello world', key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
});
// 生成加密结果
var result = {
salt: CryptoJS.enc.Hex.stringify(salt),
iv: CryptoJS.enc.Hex.stringify(iv),
ciphertext: ciphertext.toString()
};
// 发送加密结果到后端
console.log(result);
后端解密:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.KeySpec;
public class AESUtil {
public static String decrypt(String ciphertext, String salt, String iv, String password) {
try {
byte[] ciphertextBytes = hexStringToByteArray(ciphertext);
byte[] saltBytes = hexStringToByteArray(salt);
byte[] ivBytes = hexStringToByteArray(iv);
// 生成密钥
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), saltBytes, 1000, 256);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = secretKeyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
// 解密
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
byte[] plaintextBytes = cipher.doFinal(ciphertextBytes);
return new String(plaintextBytes, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static byte[] hexStringToByteArray(String hexString) {
int length = hexString.length();
byte[] bytes = new byte[length / 2];
for (int i = 0; i < length; i += 2) {
bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ Character.digit(hexString.charAt(i+1), 16));
}
return bytes;
}
}
使用方式:
String ciphertext = "U2FsdGVkX19wvXzj1q+L3f88Z3C8L4/pQDkGqJv0kBk=";
String salt = "a5c8d545b1dbd1f6a0ef4d7f5e1d61c6";
String iv = "a7ac9b3b9c13e3f9a09efdb2e3d3e0f7";
String password = "123456";
String plaintext = AESUtil.decrypt(ciphertext, salt, iv, password);
System.out.println(plaintext);
原文地址: https://www.cveoy.top/t/topic/oe10 著作权归作者所有。请勿转载和采集!