1 package entity; 2 3 import javax.crypto.Cipher; 4 import javax.crypto.SecretKey; 5 import javax.crypto.SecretKeyFactory; 6 import javax.crypto.spec.DESKeySpec; 7 import javax.crypto.spec.IvParameterSpec; 8 9 public class Des { 10 private byte[] desKey; 11 12 13 //解密数据 14 public static String decrypt(String message,String key) throws Exception { 15 16 byte[] bytesrc =convertHexString(message); 17 Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); 18 DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8")); 19 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 20 SecretKey secretKey = keyFactory.generateSecret(desKeySpec); 21 IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8")); 22 23 cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); 24 25 byte[] retByte = cipher.doFinal(bytesrc); 26 return new String(retByte); 27 } 28 29 public static byte[] encrypt(String message, String key) 30 throws Exception { 31 Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); 32 33 DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8")); 34 35 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 36 SecretKey secretKey = keyFactory.generateSecret(desKeySpec); 37 IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8")); 38 cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv); 39 40 return cipher.doFinal(message.getBytes("UTF-8")); 41 } 42 43 public static byte[] convertHexString(String ss) 44 { 45 byte digest[] = new byte[ss.length() / 2]; 46 for(int i = 0; i < digest.length; i++) 47 { 48 String byteString = ss.substring(2 * i, 2 * i + 2); 49 int byteValue = Integer.parseInt(byteString, 16); 50 digest[i] = (byte)byteValue; 51 } 52 53 return digest; 54 } 55 56 public static String toHexString(byte b[]) { 57 StringBuffer hexString = new StringBuffer(); 58 for (int i = 0; i < b.length; i++) { 59 String plainText = Integer.toHexString(0xff & b[i]); 60 if (plainText.length() < 2) 61 plainText = "0" + plainText; 62 hexString.append(plainText); 63 } 64 65 return hexString.toString(); 66 } 67 68 69 public static void main(String[] args) throws Exception { 70 String key = "12345678"; 71 String value="test1234"; 72 String jiami=java.net.URLEncoder.encode(value, "utf-8").toLowerCase(); 73 74 System.out.println("加密数据:"+jiami); 75 String a=toHexString(encrypt(jiami, key)).toUpperCase(); 76 System.out.println("加密后的数据为:"+a); 77 78 79 String b=java.net.URLDecoder.decode(decrypt(a,key), "utf-8") ; 80 System.out.println("解密后的数据:"+b); 81 82 } 83 84 85 86 }
原文:http://www.cnblogs.com/819158327fan/p/5060618.html