Java PBEParameterSpec 测试
其他 Java 数据加密解密
package com.xu.mysql;
import java.security.Key;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
public class PBE {
private final static String KEY_PBE = "PBEWITHMD5andDES";
private final static int SALT_COUNT = 100;
public static void main(String[] args) {
String str = "hello world !!!";
String key = "qwert";
byte[] salt = init();
byte[] encData = encrypt(str.getBytes(), key, salt);
byte[] decData = decrypt(encData, key, salt);
System.out.println("加密前:" + str);
System.out.println("加密后:" + new String(encData));
System.out.println("解密后:" + new String(decData));
}
public static byte[] init() {
byte[] salt = new byte[8];
Random random = new Random();
random.nextBytes(salt);
return salt;
}
public static Key getKey(String key) {
SecretKey secret = null;
try {
PBEKeySpec keySpec = new PBEKeySpec(key.toCharArray());
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_PBE);
secret = factory.generateSecret(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
return secret;
}
public static byte[] encrypt(byte[] data, String key, byte[] salt) {
byte[] v = null;
try {
Key k = getKey(key);
PBEParameterSpec spec = new PBEParameterSpec(salt, SALT_COUNT);
Cipher cipher = Cipher.getInstance(KEY_PBE);
cipher.init(Cipher.ENCRYPT_MODE, k, spec);
v = cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
public static byte[] decrypt(byte[] data, String key, byte[] salt) {
byte[] bytes = null;
try {
Key k = getKey(key);
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, SALT_COUNT);
Cipher cipher = Cipher.getInstance(KEY_PBE);
cipher.init(Cipher.DECRYPT_MODE, k, parameterSpec);
bytes = cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return bytes;
}
}
|