import java.security.*;
import java.security.cert.X509Certificate;
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Encrypt
{
private String password;
public Encrypt(String password)
{
this.password=pass
word;
}
public byte[] encode(String info)
{
if(info==null)
return "";
try
{
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
byte[] salt = {
(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
};
int count = 2;
// 生成pbe算法所需的参数对象,两个参数详见 RSA的 PKCS #5 标准
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
// 生成一个加密器
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
// 初始化加密器
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
// 明文
byte[] cleartext = info.getBytes();
// 加密
byte[] ciphertext = pbeCipher.doFinal(cleartext);
//返回密文
return new String(ciphertext);
}
catch (Exception e)
{
System.out.println(e);
};
return "";
}
public byte[] decode(String info)
{
if(info==null)
return "";
try
{
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
byte[] salt = {
(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
};
int count = 20;
// 生成pbe算法所需的参数对象,两个参数详见 RSA的 PKCS #5 标准
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
// 生成一个加密器
Cipher pbeCipher = Cipher
.getInstance("PBEWithMD5AndDES");
// 初始化加密器
pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
// 密文
byte[] ciphertext = info.getBytes();
// 解密
byte[] cleartext = pbeCipher.doFinal(ciphertext);
//返回明文
return new String(ciphertext);
}
catch (Exception e)
{
System.out.println(e);
};
return "";
}
}