public final class DesUtils {
private static final String DES = "DES";
private static final String KEY = "4YztMHI7PsT4rLZN_adorechen";
private DesUtils() {}
private static byte[] encrypt(byte[] src, byte[] key) throws Exception {
return encryptAndDecrypt(src, key, Cipher.ENCRYPT_MODE);
}
private static byte[] decrypt(byte[] src, byte[] key) throws Exception {
return encryptAndDecrypt(src, key, Cipher.DECRYPT_MODE);
}
private static byte[] encryptAndDecrypt(byte[] src, byte[] key, int mode) throws Exception {
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(DES);
cipher.init(mode, secretKey, sr);
return cipher.doFinal(src);
}
private static String byte2hex(byte[] b) {
String hs = "";
String temp = "";
for (int n = 0; n < b.length; n++) {
temp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (temp.length() == 1)
hs = hs + "0" + temp;
else
hs = hs + temp;
}
return hs.toUpperCase();
}
private static byte[] hex2byte(byte[] b) {
if ((b.length % 2) != 0)
throw new IllegalArgumentException("length not even");
byte[] b2 = new byte[b.length / 2];
for (int n = 0; n < b.length; n += 2) {
String item = new String(b, n, 2);
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
}
private static String decode(String src, String key) {
String decryptStr = "";
try {
byte[] decrypt = decrypt(hex2byte(src.getBytes()), key.getBytes());
decryptStr = new String(decrypt);
} catch (Exception e) {
e.printStackTrace();
}
return decryptStr;
}
private static String encode(String src, String key){
byte[] bytes = null;
String encryptStr = "";
try {
bytes = encrypt(src.getBytes(), key.getBytes());
} catch (Exception ex) {
ex.printStackTrace();
}
if (bytes != null)
encryptStr = byte2hex(bytes);
return encryptStr;
}
/**
* 解密
*/
public static String decode(String src) {
return decode(src, KEY);
}
/**
* 加密
*/
public static String encode(String src) {
return encode(src, KEY);
}
}
测试类:
public static void main(String[] args) {
String ss = "uu123@#$";
String encodeSS = encode(ss);
System.out.println(encodeSS);
String decodeSS = decode(encodeSS);
System.out.println(decodeSS);
}
result:
6EA84873A948B299936006D75B7CA819
uu123@#$
本文详细介绍了一种使用Java实现的DES加密解密方法,包括关键代码片段和一个测试类,展示了如何对字符串进行加密和解密的过程。通过具体实例,验证了加密解密功能的正确性。
7915

被折叠的 条评论
为什么被折叠?



