DES
加密与解密工具类
public class DesUtil<BASE64Encoder> {
private SecretKey key = null;
private static String algorithm = "AES";
private static DesUtil desUtil = null;
public DesUtil() {
}
public static DesUtil getInstance(String strKey) {
desUtil = new DesUtil();
desUtil.createKey(strKey);
return desUtil;
}
public void createKey(String strKey) {
try {
KeyGenerator kg = KeyGenerator.getInstance(DesUtil.algorithm);
byte[] bt = strKey.getBytes("UTF-8");
SecureRandom sr = new SecureRandom(bt);
kg.init(sr);
this.setKey(kg.generateKey());
} catch (Exception e) {
}
}
public String getEnCodeString(String dataStr) {
byte[] miwen = null;
byte[] mingwen = null;
Cipher cipher;
String result = "";
try {
mingwen = dataStr.getBytes("UTF-8");
cipher = Cipher.getInstance(DesUtil.algorithm);
cipher.init(Cipher.ENCRYPT_MODE, this.getKey());
miwen = cipher.doFinal(mingwen);
result = Base64.encode(miwen);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public String getDecodeString(String codeStr) {
byte[] miwen = null;
byte[] mingwen = null;
String resultData = "";
Cipher cipher;
try {
miwen = Base64.decode(codeStr);
cipher = Cipher.getInstance(DesUtil.algorithm);
cipher.init(Cipher.DECRYPT_MODE, this.getKey());
mingwen = cipher.doFinal(miwen);
resultData = new String(mingwen, "UTF-8");
} catch (Exception e) {
return "密钥不正确或其他原因导致异常,无法解密!";
}
return resultData;
}
public String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
if (n < b.length - 1)
hs = hs + ":";
}
return hs.toUpperCase();
}
public SecretKey getKey() {
return key;
}
public void setKey(SecretKey key) {
this.key = key;
}
@Contract(pure = true)
public static String getAlgorithm() {
return algorithm;
}
public static void setAlgorithm(String algorithm) {
DesUtil.algorithm = algorithm;
}
public static void main(String[] args) {
System.out.println(DesUtil.getInstance("lushuaiyin").getEnCodeString("hello"));
System.out.println(DesUtil.getInstance("lushuaiyin").getDecodeString("LDewGAZkmWHeYFjBz56ylw=="));
System.out.println(DesUtil.getInstance("suolong").getEnCodeString("hello"));
System.out.println(DesUtil.getInstance("suolong").getDecodeString("/RLowOJ+Fr3KdMcdJeNatg=="));
System.out.println(DesUtil.getInstance("suolong").getDecodeString("LDewGAZkmWHeYFjBz56ylw=="));
}
}