62,635
社区成员




import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class DESCrypt {
private static final char[] HEX_CHAR = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
'E', 'F'
};
public static String encrypt(String text, String key) {
try {
DESKeySpec ks = new DESKeySpec("12345678".getBytes("ASCII"));
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(ks);
Cipher cip = Cipher.getInstance("DES/CBC/PKCS5Padding");
IvParameterSpec iv2 = new IvParameterSpec("12345678".getBytes("ASCII"));
cip.init(Cipher.ENCRYPT_MODE, sk, iv2);
byte[] bytes = cip.doFinal(text.getBytes("UTF-8"));
return toHexString(bytes);
} catch (Exception ex) {
return "EnStrError"; // 还是直接抛异常好
}
}
public static String decrypt(String text, String key) {
try {
DESKeySpec ks = new DESKeySpec("12345678".getBytes("ASCII"));
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(ks);
Cipher cip = Cipher.getInstance("DES/CBC/PKCS5Padding");
IvParameterSpec iv2 = new IvParameterSpec("12345678".getBytes("ASCII"));
cip.init(Cipher.DECRYPT_MODE, sk, iv2);
byte[] bytes = new byte[text.length() >> 1];
for (int i = 0, pos = 0; i < bytes.length; i++, pos += 2) {
bytes[i] = (byte)Integer.parseInt(text.substring(pos, pos+2), 16);
}
byte[] decrypt = cip.doFinal(bytes);
return new String(decrypt, "UTF-8");
} catch (Exception ex) {
return "DeStrError";
}
}
private static String toHexString(byte[] bytes) {
int len = bytes.length << 1;
char[] chars = new char[len];
for (int i = 0, pos = 0; i < bytes.length; i++, pos += 2) {
int unsignedByte = bytes[i] & 0xFF;
chars[pos] = HEX_CHAR[unsignedByte >> 4];
chars[pos + 1] = HEX_CHAR[unsignedByte & 0xF];
}
return new String(chars);
}
public static void main(String[] args) throws Exception {
String[] tests = new String[] {
"abcd",
"1234567890",
"Hello World!",
"你好,世界!"
};
for (String test : tests) {
System.out.println(test);
String encrypt = encrypt(test, "");
System.out.println(encrypt);
String decrypt = decrypt(encrypt, "");
System.out.println(decrypt);
}
System.out.println(encrypt("abcd", ""));
System.out.println(encrypt("Hello World!", ""));
System.out.println(encrypt("你好,世界!", ""));
}
}