1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex;
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec;
public class DESUtils {
public static String encrypt(String key, String data) throws Exception { Cipher cipher = initCipher(key, Cipher.ENCRYPT_MODE); byte[] encryptedByte = cipher.doFinal(data.getBytes()); return Base64.encodeBase64String(encryptedByte); }
public static String decrypt(String key, String data) throws Exception { Cipher cipher = initCipher(key, Cipher.DECRYPT_MODE); byte[] decryptedByte = cipher.doFinal(Base64.decodeBase64(data)); return new String(decryptedByte); }
private static Cipher initCipher(String key, int encryptMode) throws Exception { Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(encryptMode, new SecretKeySpec(key.getBytes(), "DES")); return cipher; }
public static void main(String[] args) throws Exception { String key = "12345678"; String value = "HelloWorld";
System.out.println("key hex: " + Hex.encodeHexString(key.getBytes()));
String encrypt = encrypt(key, value); System.out.println("encrypt: " + encrypt); String decrypt = decrypt(key, encrypt); System.out.println("decrypt: " + decrypt); }
}
|