DES
public static String encrypt(String data, String _key) {
Key secretKey = generateKey(_key);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(data.getBytes("UTF-8"));
return new String(encoder.encode(bytes));
}
public static String decrypt(String data, String _key) {
Key secretKey = generateKey(_key);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
BASE64Decoder decoder = new BASE64Decoder();
byte[] result = cipher.doFinal(decoder.decodeBuffer(data));
return new String(result, "UTF-8");
}
其中密钥生成器
private static Key generateKey(final String key) throws Exception {
DESKeySpec dks = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
return keyFactory.generateSecret(dks);
}
此处提供基于Java 8的Base64工具类:性能好,推荐
private static final Base64.Decoder decoder = Base64.getDecoder();
private static final Base64.Encoder encoder = Base64.getEncoder();
public static String encode(byte[] bytes) { return encoder.encodeToString(bytes); }
public static byte[] decode(String str) { return decoder.decode(str); }