public class PbeEncrypter {
Cipher ecipher;
Cipher dcipher;
//盐
byte[] salt = { (byte) 0x29, (byte) 0xCB, (byte) 0xD7, (byte) 0x28, (byte) 0x56, (byte) 0x3D,(byte) 0xEE, (byte) 0x05 };
public PbeEncrypter(String parshkey) throws Exception {
//迭代次数
int iterationCount = 3;
KeySpec keySpec = new PBEKeySpec(parshkey.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
}
//加密方法
public String encrypt(String str) throws Exception {
str = new String(str.getBytes(), "UTF-8");
return Base64.encodeBase64String(ecipher.doFinal(str.getBytes()));
}
//解密方法
public String decrypt(String str) throws Exception {
return new String(dcipher.doFinal(Base64.decodeBase64(str)),"UTF-8");
}
//调用方法
public static void main(String[] args) throws Exception {
//key : 36CE91A3CD88512E0A15033325D80859
PbeEncrypter desEncrypter = new PbeEncrypter("98f3139d2e61042556d7e6d4a6818069de9f5b9a");
//str为加密前的参数字符串
String str = "12345678";
System.out.println(desEncrypter.encrypt(str));
System.out.println(desEncrypter.decrypt("0SVp7urHWduuyaPIneETrQ=="));
}
}