des和md5的使用和区别

1.DES算法的入口参数有三个:Key、Data、Mode。其中Key为7个字节共56位,是DES算法的工作密钥;Data为8个字节64位,是要被加密或被解密的数据;Mode为DES的工作方式,有两种:加密或解密。des是可逆的,利用七位的密钥进行解密。

[java]  view plain  copy
  1. <span style="font-family:Comic Sans MS;"><span style="font-size:12px;">package com.sica.des;  
  2.   
  3. import com.google.common.base.Strings;  
  4. import sun.misc.BASE64Decoder;  
  5. import sun.misc.BASE64Encoder;  
  6.   
  7. import javax.crypto.Cipher;  
  8. import javax.crypto.KeyGenerator;  
  9. import javax.crypto.SecretKey;  
  10. import javax.crypto.SecretKeyFactory;  
  11. import javax.crypto.spec.DESKeySpec;  
  12. import java.security.InvalidKeyException;  
  13. import java.security.Key;  
  14. import java.security.NoSuchAlgorithmException;  
  15. import java.security.SecureRandom;  
  16. import java.security.spec.InvalidKeySpecException;  
  17.   
  18. /** 
  19.  * Created by xiang.li on 2015/2/28. 
  20.  * DES 加解密工具类 
  21.  * 
  22.  * <pre> 
  23.  * 支持 DES、DESede(TripleDES,就是3DES)、AES、Blowfish、RC2、RC4(ARCFOUR) 
  24.  * DES                  key size must be equal to 56 
  25.  * DESede(TripleDES)    key size must be equal to 112 or 168 
  26.  * AES                  key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available 
  27.  * Blowfish             key size must be multiple of 8, and can only range from 32 to 448 (inclusive) 
  28.  * RC2                  key size must be between 40 and 1024 bits 
  29.  * RC4(ARCFOUR)         key size must be between 40 and 1024 bits 
  30.  * 具体内容 需要关注 JDK Document http://.../docs/technotes/guides/security/SunProviders.html 
  31.  * </pre> 
  32.  */  
  33. public class DES {  
  34.     /** 
  35.      * 定义加密方式 
  36.      */  
  37.     private final static String KEY_DES = "DES";  
  38.     private final static String KEY_AES = "AES";    // 测试  
  39.   
  40.     /** 
  41.      * 全局数组 
  42.      */  
  43.     private final static String[] hexDigits = { "0""1""2""3""4""5",  
  44.             "6""7""8""9""a""b""c""d""e""f" };  
  45.   
  46.     /** 
  47.      * 初始化密钥 
  48.      * @return 
  49.      */  
  50.     public static String init() {  
  51.         return init(null);  
  52.     }  
  53.   
  54.     /** 
  55.      * 初始化密钥 
  56.      * @param seed 初始化参数 
  57.      * @return 
  58.      */  
  59.     public static String init(String seed) {  
  60.         SecureRandom secure = null;  
  61.         String str = "";  
  62.         try {  
  63.             if (null != secure) {  
  64.                 // 带参数的初始化  
  65.                 secure = new SecureRandom(decryptBase64(seed));  
  66.             } else {  
  67.                 // 不带参数的初始化  
  68.                 secure = new SecureRandom();  
  69.             }  
  70.   
  71.             KeyGenerator generator = KeyGenerator.getInstance(KEY_DES);  
  72.             generator.init(secure);  
  73.   
  74.             SecretKey key = generator.generateKey();  
  75.             str = encryptBase64(key.getEncoded());  
  76.         } catch (Exception e) {  
  77.             e.printStackTrace();  
  78.         }  
  79.         return str;  
  80.     }  
  81.   
  82.     /** 
  83.      * 转换密钥 
  84.      * @param key 密钥的字节数组 
  85.      * @return 
  86.      */  
  87.     private static Key byteToKey(byte[] key) {  
  88.         SecretKey secretKey = null;  
  89.         try {  
  90.             DESKeySpec dks = new DESKeySpec(key);  
  91.             SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_DES);  
  92.             secretKey = factory.generateSecret(dks);  
  93.   
  94.             // 当使用其他对称加密算法时,如AES、Blowfish等算法时,用下述代码替换上述三行代码  
  95. //            secretKey = new SecretKeySpec(key, KEY_DES);  
  96.         } catch (InvalidKeyException e) {  
  97.             e.printStackTrace();  
  98.         } catch (NoSuchAlgorithmException e) {  
  99.             e.printStackTrace();  
  100.         } catch (InvalidKeySpecException e) {  
  101.             e.printStackTrace();  
  102.         }  
  103.         return secretKey;  
  104.     }  
  105.   
  106.     /** 
  107.      * DES 解密 
  108.      * @param data 需要解密的字符串 
  109.      * @param key 密钥 
  110.      * @return 
  111.      */  
  112.     public static String decryptDES(String data, String key) {  
  113.         // 验证传入的字符串  
  114.         if (Strings.isNullOrEmpty(data)) {  
  115.             return "";  
  116.         }  
  117.         // 调用解密方法完成解密  
  118.         byte[] bytes = decryptDES(hexString2Bytes(data), key);  
  119.         // 将得到的字节数组变成字符串返回  
  120.         return new String(bytes);  
  121.     }  
  122.   
  123.     /** 
  124.      * DES 解密 
  125.      * @param data 需要解密的字节数组 
  126.      * @param key 密钥 
  127.      * @return 
  128.      */  
  129.     public static byte[] decryptDES(byte[] data, String key) {  
  130.         byte[] bytes = null;  
  131.         try {  
  132.             Key k = byteToKey(decryptBase64(key));  
  133.             Cipher cipher = Cipher.getInstance(KEY_DES);  
  134.             cipher.init(Cipher.DECRYPT_MODE, k);  
  135.             bytes = cipher.doFinal(data);  
  136.         } catch (Exception e) {  
  137.             e.printStackTrace();  
  138.         }  
  139.         return bytes;  
  140.     }  
  141.   
  142.     /** 
  143.      * DES 加密 
  144.      * @param data 需要加密的字符串 
  145.      * @param key 密钥 
  146.      * @return 
  147.      */  
  148.     public static String encryptDES(String data, String key) {  
  149.         // 验证传入的字符串  
  150.         if (Strings.isNullOrEmpty(data)) {  
  151.             return "";  
  152.         }  
  153.         // 调用加密方法完成加密  
  154.         byte[] bytes = encryptDES(data.getBytes(), key);  
  155.         // 将得到的字节数组变成字符串返回  
  156.         return byteArrayToHexString(bytes);  
  157.     }  
  158.   
  159.     /** 
  160.      * DES 加密 
  161.      * @param data 需要加密的字节数组 
  162.      * @param key 密钥 
  163.      * @return 
  164.      */  
  165.     public static byte[] encryptDES(byte[] data, String key) {  
  166.         byte[] bytes = null;  
  167.         try {  
  168.             Key k = byteToKey(decryptBase64(key));  
  169.             Cipher cipher = Cipher.getInstance(KEY_DES);  
  170.             cipher.init(Cipher.ENCRYPT_MODE, k);  
  171.             bytes = cipher.doFinal(data);  
  172.         } catch (Exception e) {  
  173.             e.printStackTrace();  
  174.         }  
  175.         return bytes;  
  176.     }  
  177.   
  178.   
  179.     /** 
  180.      * BASE64 解密 
  181.      * @param key 需要解密的字符串 
  182.      * @return 字节数组 
  183.      * @throws Exception 
  184.      */  
  185.     public static byte[] decryptBase64(String key) throws Exception {  
  186.         return (new BASE64Decoder()).decodeBuffer(key);  
  187.     }  
  188.   
  189.     /** 
  190.      * BASE64 加密 
  191.      * @param key 需要加密的字节数组 
  192.      * @return 字符串 
  193.      * @throws Exception 
  194.      */  
  195.     public static String encryptBase64(byte[] key) throws Exception {  
  196.         return (new BASE64Encoder()).encodeBuffer(key);  
  197.     }  
  198.   
  199.     /** 
  200.      * 将一个字节转化成十六进制形式的字符串 
  201.      * @param b 字节数组 
  202.      * @return 字符串 
  203.      */  
  204.     private static String byteToHexString(byte b) {  
  205.         int ret = b;  
  206.         //System.out.println("ret = " + ret);  
  207.         if (ret < 0) {  
  208.             ret += 256;  
  209.         }  
  210.         int m = ret / 16;  
  211.         int n = ret % 16;  
  212.         return hexDigits[m] + hexDigits[n];  
  213.     }  
  214.   
  215.     /** 
  216.      * 转换字节数组为十六进制字符串 
  217.      * @param bytes 字节数组 
  218.      * @return 十六进制字符串 
  219.      */  
  220.     private static String byteArrayToHexString(byte[] bytes) {  
  221.         StringBuffer sb = new StringBuffer();  
  222.         for (int i = 0; i < bytes.length; i++) {  
  223.             sb.append(byteToHexString(bytes[i]));  
  224.         }  
  225.         return sb.toString();  
  226.     }  
  227.   
  228.   
  229.     /** 
  230.      * 转换十六进制字符串为字节数组 
  231.      * @param hexstr 十六进制字符串 
  232.      * @return 
  233.      */  
  234.     public static byte[] hexString2Bytes(String hexstr) {  
  235.         byte[] b = new byte[hexstr.length() / 2];  
  236.         int j = 0;  
  237.         for (int i = 0; i < b.length; i++) {  
  238.             char c0 = hexstr.charAt(j++);  
  239.             char c1 = hexstr.charAt(j++);  
  240.             b[i] = (byte) ((parse(c0) << 4) | parse(c1));  
  241.         }  
  242.         return b;  
  243.     }  
  244.   
  245.     /** 
  246.      * 转换字符类型数据为整型数据 
  247.      * @param c 字符 
  248.      * @return 
  249.      */  
  250.     private static int parse(char c) {  
  251.         if (c >= 'a')  
  252.             return (c - 'a' + 10) & 0x0f;  
  253.         if (c >= 'A')  
  254.             return (c - 'A' + 10) & 0x0f;  
  255.         return (c - '0') & 0x0f;  
  256.     }  
  257.   
  258.     /** 
  259.      * 测试方法 
  260.      * @param args 
  261.      */  
  262.     public static void main(String[] args) {  
  263.         String key = DES.init();  
  264.         System.out.println("DES密钥:\n" + key);  
  265.   
  266.         String word = "123";  
  267.           
  268.   
  269.         String encWord = encryptDES(word, key);  
  270.   
  271.         System.out.println(word + "\n加密后:\n" + encWord);  
  272.         System.out.println(word + "\n解密后:\n" + decryptDES(encWord, key));  
  273.     }  
  274. }</span><span style="font-size: 14px;">  
  275. </span></span>  

2. MD5是校验码,不是加密的。

MD5就像是文件的身份证一样,保证文件的完整和安全性。


因为一个文件只会产生唯一的 MD5码 ,如果有病毒写入,是人为修改,这个码就会变,这样就可以给人以警示。
在实践中常常会用到的MD5校验加密一般运用场景:用户密码,请求参数,文件校验
package com.pb;
 
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
 
/*
  * 验证MD5
  * 1.初始化MessageDigest信息摘要对象
  * 2.传入需要计算的字符串更新摘要信息
  * 3.计算信息摘要
  * 4.将byte[] 转换为找度为32位的16进制字符串
  */
public class MD5 {
   /*
    * 生成md5 有传入参数字符串
    */
   public void generateMD5(String input){
     
     try {
       //1.初始化MessageDigest信息摘要对象,并指定为MD5不分大小写都可以
       MessageDigest md=MessageDigest.getInstance( "md5" );
        //2.传入需要计算的字符串更新摘要信息,传入的为字节数组byte[],
       //将字符串转换为字节数组使用getBytes()方法完成
       //指定时其字符编码 为utf-8
       md.update(input.getBytes( "utf-8" ));
        //3.计算信息摘要digest()方法
       //返回值为字节数组
       byte [] hashCode=md.digest();
        //4.将byte[] 转换为找度为32位的16进制字符串
         //声明StringBuffer对象来存放最后的值
       StringBuffer sb= new StringBuffer();
       //遍历字节数组
       for ( byte b:hashCode){
         //对数组内容转化为16进制,
         sb.append(Character.forDigit(b>> 4 & 0xf , 16 ));
         //换2次为32位的16进制
         sb.append(Character.forDigit(b& 0xf , 16 ));
       }
       System.out.println( "加密后的结果是:" +sb.toString());
     } catch (NoSuchAlgorithmException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     } catch (UnsupportedEncodingException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
 
   public static void main(String[] args) {
     //声明加密MD5类的对象
     MD5 md5= new MD5();
     //使用Scanner来输入一个字符
     Scanner scanner= new Scanner(System.in);
     System.out.println( "请输入要加密的内容:" );
     String input = scanner.nextLine();
     //调用加密方法
     md5.generateMD5(input);
 
   }
   
}



  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值