package com.xnh.atom.server;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import org.apache.commons.codec.binary.Base64;
public class EncryptionBase64Util {
public static Key DEFAULT_KEY = null;
public static final String DEFAULT_SECRET_KEY1 = "?:P)(OL><KI*&USDEWY^)DINDS*D$EDCXSW@!QAZ";
public static final String DEFAULT_SECRET_KEY2 = "!QAC@WSX#ART$RFV(UIN&YHN&UJM*IK<(OL>)P:?";
public static final String DEFAULT_SECRET_KEY = DEFAULT_SECRET_KEY1;
public static final String DES = "DES";
//public static final Base32 base32 = new Base32();
public static final Base64 base64 = new Base64();
static {
DEFAULT_KEY = obtainKey(DEFAULT_SECRET_KEY);
}
/**
* 获得key
**/
public static Key obtainKey(String key) {
if (key == null) {
return DEFAULT_KEY;
}
KeyGenerator generator = null;
try {
generator = KeyGenerator.getInstance(DES);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
generator.init(new SecureRandom(key.getBytes()));
Key key1 = generator.generateKey();
generator = null;
return key1;
}
/**
* 加密<br>
* String明文输入,String密文输出
*/
// public static String encode32(String key, String str) {
// return base32.encodeAsString(obtainEncode(key, str.getBytes())).replaceAll("=", "");
// }
public static String encode64(String key, String str) {
return new String(base64.encodeBase64(str.getBytes(),true));
}
/**
* 解密<br>
* 以String密文输入,String明文输出
*/
// public static String decode32(String key, String str) {
// return new String(obtainDecode(key, base32.decode(str)));
// }
public static String decode64(String key, String str) {
return new String(base64.decodeBase64(str.getBytes()));
}
/**
* 加密<br>
* 以byte[]明文输入,byte[]密文输出
*/
private static byte[] obtainEncode(String key, byte[] str) {
byte[] byteFina = null;
Cipher cipher;
try {
Key key1 = obtainKey(key);
cipher = Cipher.getInstance(DES);
cipher.init(Cipher.ENCRYPT_MODE, key1);
byteFina = cipher.doFinal(str);
} catch (Exception e) {
e.printStackTrace();
} finally {
cipher = null;
}
return byteFina;
}
/**
* 解密<br>
* 以byte[]密文输入,以byte[]明文输出
*/
private static byte[] obtainDecode(String key, byte[] str) {
Cipher cipher;
byte[] byteFina = null;
try {
Key key1 = obtainKey(key);
cipher = Cipher.getInstance(DES);
cipher.init(Cipher.DECRYPT_MODE, key1);
byteFina = cipher.doFinal(str);
} catch (Exception e) {
e.printStackTrace();
} finally {
cipher = null;
}
return byteFina;
}
/**
* 加密
* @param val
* @return
*/
public static String encrypt(String val){
String m = encode64(DEFAULT_SECRET_KEY2, val);
return m;
}
/**
* 解密
* @param val
* @return
*/
public static String decrypt(String val){
String n = decode64(DEFAULT_SECRET_KEY2, val);
return n;
}
}
09-05
639
10-11
981
11-29
2700