第一篇随笔

 

  1 import java.io.IOException;
  2 import java.security.SecureRandom;
  3 
  4 import javax.crypto.Cipher;
  5 import javax.crypto.SecretKey;
  6 import javax.crypto.SecretKeyFactory;
  7 import javax.crypto.spec.DESKeySpec;
  8 
  9 import Decoder.BASE64Decoder;
 10 import Decoder.BASE64Encoder;
 11 
 12 public class DesUtil {
 13 
 14 private final static String DES = "DES";
 15 
 16 public static void main(String[] args) throws Exception {
 17 String data = "1";
 18 String key = "12345678";
 19 System.err.println(encrypt(data, key));
 20 System.err.println(decrypt(encrypt(data, key), key));
 21 
 22 }
 23 
 24 /**
 25 * Description 根据键值进行加密
 26 * @param data 
 27 * @param key 加密键byte数组
 28 * @return
 29 * @throws Exception
 30 */
 31 public static String encrypt(String data, String key) throws Exception {
 32 byte[] bt = encrypt(data.getBytes(), key.getBytes());
 33 String strs = new BASE64Encoder().encode(bt);
 34 return strs;
 35 }
 36 
 37 /**
 38 * Description 根据键值进行解密
 39 * @param data
 40 * @param key 加密键byte数组
 41 * @return
 42 * @throws IOException
 43 * @throws Exception
 44 */
 45 public static String decrypt(String data, String key) throws IOException,
 46 Exception {
 47 if (data == null)
 48 return null;
 49 BASE64Decoder decoder = new BASE64Decoder();
 50 byte[] buf = decoder.decodeBuffer(data);
 51 byte[] bt = decrypt(buf,key.getBytes());
 52 return new String(bt);
 53 }
 54 
 55 /**
 56 * Description 根据键值进行加密
 57 * @param data
 58 * @param key 加密键byte数组
 59 * @return
 60 * @throws Exception
 61 */
 62 private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
 63 // 生成一个可信任的随机数源
 64 SecureRandom sr = new SecureRandom();
 65 
 66 // 从原始密钥数据创建DESKeySpec对象
 67 DESKeySpec dks = new DESKeySpec(key);
 68 
 69 // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
 70 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
 71 SecretKey securekey = keyFactory.generateSecret(dks);
 72 
 73 // Cipher对象实际完成加密操作
 74 Cipher cipher = Cipher.getInstance(DES);
 75 
 76 // 用密钥初始化Cipher对象
 77 cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
 78 
 79 return cipher.doFinal(data);
 80 }
 81 
 82 
 83 /**
 84 * Description 根据键值进行解密
 85 * @param data
 86 * @param key 加密键byte数组
 87 * @return
 88 * @throws Exception
 89 */
 90 private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
 91 // 生成一个可信任的随机数源
 92 SecureRandom sr = new SecureRandom();
 93 
 94 // 从原始密钥数据创建DESKeySpec对象
 95 DESKeySpec dks = new DESKeySpec(key);
 96 
 97 // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
 98 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
 99 SecretKey securekey = keyFactory.generateSecret(dks);
100 
101 // Cipher对象实际完成解密操作
102 Cipher cipher = Cipher.getInstance(DES);
103 
104 // 用密钥初始化Cipher对象
105 cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
106 
107 return cipher.doFinal(data);
108 }
109 }

 

posted @ 2015-09-14 11:04  tang1jun  阅读(141)  评论(0)    收藏  举报