DES加密解密类-java

[java]  view plain  copy
  1. import <a href="http://lib.csdn.net/base/java" class='replace_word' title="Java 知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>.security.*;  
  2. import javax.crypto.Cipher;  
  3. import javax.crypto.SecretKey;  
  4. import javax.crypto.SecretKeyFactory;  
  5. import javax.crypto.spec.DESKeySpec;  
  6. /** 
  7.  * Copyright 2007 GuangZhou Cotel Co. Ltd. 
  8.  * All right reserved.     
  9.  * DES加密解密类.      
  10.  * @author <a href="mailto:xiexingxing1121@126.com" mce_href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  11.  * @version 1.0  
  12.  * Creation date: 2007-7-31 - 上午11:59:28 
  13.  */  
  14. public class Des {  
  15.     /** 加密、解密key. */  
  16.     private static final String PASSWORD_CRYPT_KEY = "kEHrDooxWHCWtfeSxvDvgqZq";  
  17.     /** 加密<a href="http://lib.csdn.net/base/datastructure" class='replace_word' title="算法与数据结构知识库" target='_blank' style='color:#df3434; font-weight:bold;'>算法</a>,可用 DES,DESede,Blowfish. */  
  18.     private final static String ALGORITHM = "DES";  
  19.     public static void main(String[] args) throws Exception {  
  20.         String md5Password = "202cb962ac59075b964b07152d234b70";  
  21.         String str = Des.encrypt(md5Password);  
  22.         System.out.println("str: " + str);  
  23.         str = Des.decrypt(str);  
  24.         System.out.println("str: " + str);  
  25.     }  
  26.       
  27.     /** 
  28.      * 对数据进行DES加密. 
  29.      * @param data 待进行DES加密的数据 
  30.      * @return 返回经过DES加密后的数据 
  31.      * @throws Exception 
  32.      * @author <a href="mailto:xiexingxing1121@126.com" mce_href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  33.      * Creation date: 2007-7-31 - 下午12:06:24 
  34.      */  
  35.     public final static String decrypt(String data) throws Exception {  
  36.         return new String(decrypt(hex2byte(data.getBytes()),  
  37.                 PASSWORD_CRYPT_KEY.getBytes()));  
  38.     }  
  39.     /** 
  40.      * 对用DES加密过的数据进行解密. 
  41.      * @param data DES加密数据 
  42.      * @return 返回解密后的数据 
  43.      * @throws Exception 
  44.      * @author <a href="mailto:xiexingxing1121@126.com" mce_href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  45.      * Creation date: 2007-7-31 - 下午12:07:54 
  46.      */  
  47.     public final static String encrypt(String data) throws Exception  {  
  48.         return byte2hex(encrypt(data.getBytes(), PASSWORD_CRYPT_KEY  
  49.                 .getBytes()));  
  50.     }  
  51.       
  52.     /** 
  53.      * 用指定的key对数据进行DES加密. 
  54.      * @param data 待加密的数据 
  55.      * @param key DES加密的key 
  56.      * @return 返回DES加密后的数据 
  57.      * @throws Exception 
  58.      * @author <a href="mailto:xiexingxing1121@126.com" mce_href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  59.      * Creation date: 2007-7-31 - 下午12:09:03 
  60.      */  
  61.     private static byte[] encrypt(byte[] data, byte[] key) throws Exception {  
  62.         // DES算法要求有一个可信任的随机数源  
  63.         SecureRandom sr = new SecureRandom();  
  64.         // 从原始密匙数据创建DESKeySpec对象  
  65.         DESKeySpec dks = new DESKeySpec(key);  
  66.         // 创建一个密匙工厂,然后用它把DESKeySpec转换成  
  67.         // 一个SecretKey对象  
  68.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);  
  69.         SecretKey securekey = keyFactory.generateSecret(dks);  
  70.         // Cipher对象实际完成加密操作  
  71.         Cipher cipher = Cipher.getInstance(ALGORITHM);  
  72.         // 用密匙初始化Cipher对象  
  73.         cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);  
  74.         // 现在,获取数据并加密  
  75.         // 正式执行加密操作  
  76.         return cipher.doFinal(data);  
  77.     }  
  78.     /** 
  79.      * 用指定的key对数据进行DES解密. 
  80.      * @param data 待解密的数据 
  81.      * @param key DES解密的key 
  82.      * @return 返回DES解密后的数据 
  83.      * @throws Exception 
  84.      * @author <a href="mailto:xiexingxing1121@126.com" mce_href="mailto:xiexingxing1121@126.com">AmigoXie</a> 
  85.      * Creation date: 2007-7-31 - 下午12:10:34 
  86.      */  
  87.     private static byte[] decrypt(byte[] data, byte[] key) throws Exception {  
  88.         // DES算法要求有一个可信任的随机数源  
  89.         SecureRandom sr = new SecureRandom();  
  90.         // 从原始密匙数据创建一个DESKeySpec对象  
  91.         DESKeySpec dks = new DESKeySpec(key);  
  92.         // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成  
  93.         // 一个SecretKey对象  
  94.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);  
  95.         SecretKey securekey = keyFactory.generateSecret(dks);  
  96.         // Cipher对象实际完成解密操作  
  97.         Cipher cipher = Cipher.getInstance(ALGORITHM);  
  98.         // 用密匙初始化Cipher对象  
  99.         cipher.init(Cipher.DECRYPT_MODE, securekey, sr);  
  100.         // 现在,获取数据并解密  
  101.         // 正式执行解密操作  
  102.         return cipher.doFinal(data);  
  103.     }  
  104.     public static byte[] hex2byte(byte[] b) {  
  105.         if ((b.length % 2) != 0)  
  106.             throw new IllegalArgumentException("长度不是偶数");  
  107.         byte[] b2 = new byte[b.length / 2];  
  108.         for (int n = 0; n < b.length; n += 2) {  
  109.             String item = new String(b, n, 2);  
  110.             b2[n / 2] = (byte) Integer.parseInt(item, 16);  
  111.         }  
  112.         return b2;  
  113.     }  
  114.     public static String byte2hex(byte[] b) {  
  115.         String hs = "";  
  116.         String stmp = "";  
  117.         for (int n = 0; n < b.length; n++) {  
  118.             stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));  
  119.             if (stmp.length() == 1)  
  120.                 hs = hs + "0" + stmp;  
  121.             else  
  122.                 hs = hs + stmp;  
  123.         }  
  124.         return hs.toUpperCase();  
  125.     }  
  126. }  
 

本文转自:http://www.blogjava.net/amigoxie/archive/2007/07/31/133544.html

 

另一个例子:

[java]  view plain  copy
  1. /** 
  2.  * @author    李国庆 
  3.  * @company   leemenz (C) copyright 
  4.  * @time      Nov 1, 2006  10:18:41 AM 
  5.  * @version   1.0.0.0 
  6.  * @package   com.des 
  7.  */  
  8. package com.des;  
  9.    
  10. import java.security.*;  
  11. import javax.crypto.*;  
  12.    
  13. public class DESPlus {  
  14.  private static String strDefaultKey = "national";  
  15.    
  16.  private Cipher encryptCipher = null;  
  17.    
  18.  private Cipher decryptCipher = null;  
  19.    
  20.  /** 
  21.   * 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[] 
  22.   * hexStr2ByteArr(String strIn) 互为可逆的转换过程 
  23.   * 
  24.   * @param arrB 
  25.   *            需要转换的byte数组 
  26.   * @return 转换后的字符串 
  27.   * @throws Exception 
  28.   *             本方法不处理任何异常,所有异常全部抛出 
  29.   */  
  30.  public static String byteArr2HexStr(byte[] arrB) throws Exception {  
  31.   int iLen = arrB.length;  
  32.   // 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍  
  33.   StringBuffer sb = new StringBuffer(iLen * 2);  
  34.   for (int i = 0; i < iLen; i++) {  
  35.    int intTmp = arrB<i>;  
  36.    // 把负数转换为正数  
  37.    while (intTmp < 0) {  
  38.     intTmp = intTmp + 256;  
  39.    }  
  40.    // 小于0F的数需要在前面补0  
  41.    if (intTmp < 16) {  
  42.     sb.append("0");  
  43.    }  
  44.    sb.append(Integer.toString(intTmp, 16));  
  45.   }  
  46.   return sb.toString();  
  47.  }  
  48.    
  49.  /** 
  50.   * 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB) 
  51.   * 互为可逆的转换过程 
  52.   * 
  53.   * @param strIn 
  54.   *            需要转换的字符串 
  55.   * @return 转换后的byte数组 
  56.   * @throws Exception 
  57.   *             本方法不处理任何异常,所有异常全部抛出 
  58.   * @author <a href="mailto:leo841001@163.com" mce_href="mailto:leo841001@163.com">LiGuoQing</a> 
  59.   */  
  60.  public static byte[] hexStr2ByteArr(String strIn) throws Exception {  
  61.   byte[] arrB = strIn.getBytes();  
  62.   int iLen = arrB.length;  
  63.    
  64.   // 两个字符表示一个字节,所以字节数组长度是字符串长度除以2  
  65.   byte[] arrOut = new byte[iLen / 2];  
  66.   for (int i = 0; i < iLen; i = i + 2) {  
  67.    String strTmp = new String(arrB, i, 2);  
  68.    arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);  
  69.   }  
  70.   return arrOut;  
  71.  }  
  72.    
  73.  /** 
  74.   * 默认构造方法,使用默认密钥 
  75.   * 
  76.   * @throws Exception 
  77.   */  
  78.  public DESPlus() throws Exception {  
  79.   this(strDefaultKey);  
  80.  }  
  81.    
  82.  /** 
  83.   * 指定密钥构造方法 
  84.   * 
  85.   * @param strKey 
  86.   *            指定的密钥 
  87.   * @throws Exception 
  88.   */  
  89.  public DESPlus(String strKey) throws Exception {  
  90.   Security.addProvider(new com.sun.crypto.provider.SunJCE());  
  91.   Key key = getKey(strKey.getBytes());  
  92.    
  93.   encryptCipher = Cipher.getInstance("DES");  
  94.   encryptCipher.init(Cipher.ENCRYPT_MODE, key);  
  95.    
  96.   decryptCipher = Cipher.getInstance("DES");  
  97.   decryptCipher.init(Cipher.DECRYPT_MODE, key);  
  98.  }  
  99.    
  100.  /** 
  101.   * 加密字节数组 
  102.   * 
  103.   * @param arrB 
  104.   *            需加密的字节数组 
  105.   * @return 加密后的字节数组 
  106.   * @throws Exception 
  107.   */  
  108.  public byte[] encrypt(byte[] arrB) throws Exception {  
  109.   return encryptCipher.doFinal(arrB);  
  110.  }  
  111.    
  112.  /** 
  113.   * 加密字符串 
  114.   * 
  115.   * @param strIn 
  116.   *            需加密的字符串 
  117.   * @return 加密后的字符串 
  118.   * @throws Exception 
  119.   */  
  120.  public String encrypt(String strIn) throws Exception {  
  121.   return byteArr2HexStr(encrypt(strIn.getBytes()));  
  122.  }  
  123.    
  124.  /** 
  125.   * 解密字节数组 
  126.   * 
  127.   * @param arrB 
  128.   *            需解密的字节数组 
  129.   * @return 解密后的字节数组 
  130.   * @throws Exception 
  131.   */  
  132.  public byte[] decrypt(byte[] arrB) throws Exception {  
  133.   return decryptCipher.doFinal(arrB);  
  134.  }  
  135.    
  136.  /** 
  137.   * 解密字符串 
  138.   * 
  139.   * @param strIn 
  140.   *            需解密的字符串 
  141.   * @return 解密后的字符串 
  142.   * @throws Exception 
  143.   */  
  144.  public String decrypt(String strIn) throws Exception {  
  145.   return new String(decrypt(hexStr2ByteArr(strIn)));  
  146.  }  
  147.    
  148.  /** 
  149.   * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位 
  150.   * 
  151.   * @param arrBTmp 
  152.   *            构成该字符串的字节数组 
  153.   * @return 生成的密钥 
  154.   * @throws java.lang.Exception 
  155.   */  
  156.  private Key getKey(byte[] arrBTmp) throws Exception {  
  157.   // 创建一个空的8位字节数组(默认值为0)  
  158.   byte[] arrB = new byte[8];  
  159.    
  160.   // 将原始字节数组转换为8位  
  161.   for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {  
  162.    arrB<i> = arrBTmp<i>;  
  163.   }  
  164.    
  165.   // 生成密钥  
  166.   Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");  
  167.    
  168.   return key;  
  169.  }  
  170. }  
  171.    
  172. <a href="http://lib.csdn.net/base/softwaretest" class='replace_word' title="软件测试知识库" target='_blank' style='color:#df3434; font-weight:bold;'>测试</a>程序  Test.java  
  173.    
  174. /** 
  175.  * @author    李国庆 
  176.  * @company   leemenz (C) copyright 
  177.  * @time      Nov 1, 2006  10:24:06 AM 
  178.  * @version   1.0.0.0 
  179.  * @package   com.des 
  180.  */  
  181. package com.des;  
  182.    
  183. /** 
  184.  * @author Administrator 
  185.  * 
  186.  */  
  187. public class Test {  
  188.    
  189.  /** 
  190.   * @param args 
  191.   */  
  192.  public static void main(String[] args) {  
  193.   // TODO Auto-generated method stub  
  194.   try {  
  195.    String test = "Hellow Word!";  
  196.    //DESPlus des = new DESPlus();//默认密钥  
  197.    DESPlus des = new DESPlus("leemenz");//自定义密钥  
  198.    System.out.println("加密前的字符:"+test);  
  199.    System.out.println("加密后的字符:"+des.encrypt(test));  
  200.    System.out.println("解密后的字符:"+des.decrypt(des.encrypt(test)));  
  201.   } catch (Exception e) {  
  202.    // TODO: handle exception  
  203.    e.printStackTrace();  
  204.   }  
  205.  }  
  206. }  
 

此篇转载自:http://www.icnote.com/des-encrypt/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值