1 package com.pff.pff; 2 3 import java.security.SecureRandom; 4 5 import javax.crypto.Cipher; 6 import javax.crypto.KeyGenerator; 7 import javax.crypto.SecretKey; 8 import javax.crypto.SecretKeyFactory; 9 import javax.crypto.spec.DESKeySpec; 10 11 import org.apache.commons.codec.binary.Hex; 12 13 public class Des { 14 15 private static String test = "pff"; 16 17 public static void main(String[] args) { 18 testDes(); 19 } 20 21 public static void testDes() { 22 try { 23 // 生成秘钥 24 KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); 25 keyGenerator.init(new SecureRandom()); 26 SecretKey generateKey = keyGenerator.generateKey(); 27 byte[] encoded = generateKey.getEncoded(); 28 // 秘钥转换 29 DESKeySpec desKeySpec = new DESKeySpec(encoded); 30 SecretKeyFactory instance = SecretKeyFactory.getInstance("DES"); 31 SecretKey generateSecret = instance.generateSecret(desKeySpec); 32 // DES加密过程 33 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5padding"); 34 cipher.init(Cipher.ENCRYPT_MODE, generateSecret); 35 byte[] result = cipher.doFinal(test.getBytes()); 36 System.out.println("DES加密过程结果= " + Hex.encodeHexString(result)); 37 // 解密过程 38 cipher.init(Cipher.DECRYPT_MODE, generateSecret); 39 byte[] result2 = cipher.doFinal(result); 40 System.out.println("DES解密过程结果= " + new String(result2)); 41 } catch (Exception e) { 42 e.printStackTrace(); 43 } 44 } 45 46 }