秘钥类:
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Decoder;
public class Key
{
private static String encryptKey = "7EV/Zzutjzg=";
public static SecretKey loadKey()
throws Exception
{
BASE64Decoder d = new BASE64Decoder();
byte[] b = d.decodeBuffer(encryptKey);
DESKeySpec dks = new DESKeySpec(b);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
return keyFactory.generateSecret(dks);
}
}
加密解密类:
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Properties;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import org.springframework.beans.factory.FactoryBean;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class DBEncrypt
implements FactoryBean
{
private Properties properties;
public Object getObject()
throws Exception
{
return getProperties();
}
public Class getObjectType() {
return Properties.class;
}
public boolean isSingleton() {
return true;
}
public Properties getProperties() {
return this.properties;
}
public void setProperties(Properties inProperties) {
this.properties = inProperties;
String originalUsername = this.properties.getProperty("user");
String originalPassword = this.properties.getProperty("password");
if (originalUsername != null) {
String newUsername = deEncryptUsername(originalUsername);
this.properties.put("user", newUsername);
}
if (originalPassword != null) {
String newPassword = deEncryptPassword(originalPassword);
this.properties.put("password", newPassword);
}
}
private String deEncryptUsername(String originalUsername) {
return dCode(originalUsername.getBytes());
}
private String deEncryptPassword(String originalPassword) {
return dCode(originalPassword.getBytes());
}
public String eCode(String needEncrypt) {
byte[] result = (byte[])null;
try {
Cipher enCipher = Cipher.getInstance("DES");
SecretKey key = Key.loadKey();
enCipher.init(1, key);
result = enCipher.doFinal(needEncrypt.getBytes());
BASE64Encoder b = new BASE64Encoder();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.encode(result, bos);
result = bos.toByteArray();
} catch (Exception e) {
throw new IllegalStateException("System doesn't support DES algorithm.");
}
return new String(result);
}
public String dCode(byte[] result) {
String s = null;
try {
Cipher deCipher = Cipher.getInstance("DES");
deCipher.init(2, Key.loadKey());
BASE64Decoder d = new BASE64Decoder();
result = d.decodeBuffer(new String(result));
byte[] strByte = deCipher.doFinal(result);
s = new String(strByte);
} catch (Exception e) {
throw new IllegalStateException("System doesn't support DES algorithm.");
}
return s;
}
public static void main(String[] args)
{
String s = "test";
DBEncrypt p = new DBEncrypt();
String afterE = p.eCode(s);
System.out.println(afterE);
System.out.println(p.dCode(afterE.getBytes()));
}
}