Chinaunix首页 | 论坛 | 博客
  • 博客访问: 130565
  • 博文数量: 30
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 338
  • 用 户 组: 普通用户
  • 注册时间: 2014-02-19 17:33
文章分类
文章存档

2017年(2)

2014年(28)

我的朋友

分类: Java

2014-02-24 09:55:32

JAVA实现DES加密

DES算法为密码体制中的对称密码体制,又被成为 ,是1972年美国 公司研制的对称密码体制加密算法。其密钥长度为56位,明文按64位进行分组,将分组后的明文组和56位的密钥按位替代或交换的方法形成密文组的加密方法。


DES加密算法特点:分组比较短、密钥太短、密码生命周期短、运算速度较慢。

DES工作的基本原理是,其入口参数有三个:key、data、mode。 key为加密解密使用的 ,data为加密解密的数据,mode为其工作模式。当模式为加密模式时,明文按照64

DES加密算法 DES加密算法

位进行分组,形成明文组,key用于对数据加密,当模式为解密模式时,key用于对数据解密。实际运用中,密钥只用到了64位中的56位,这样才具有高的安全性。

DES( Data Encryption Standard)算法,于1977年得到美国政府的正式许可,是一种用56位密钥来加密64位数据的方法。虽然56位密钥的DES算法已经风光不在,而 且常有用Des加密的明文被破译的报道,但是了解一下昔日美国的标准加密算法总是有益的,而且目前DES算法得到了广泛的应用,在某些场合,仍然发挥着余 热。

 

 


[c-sharp] view plaincopy
  1. package  test;  
  2.    
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.security.Key;  
  8. import java.security.SecureRandom;  
  9.    
  10. import javax.crypto.Cipher;  
  11. import javax.crypto.CipherInputStream;  
  12. import javax.crypto.CipherOutputStream;  
  13. import javax.crypto.KeyGenerator;  
  14.    
  15. import sun.misc.BASE64Decoder;  
  16. import sun.misc.BASE64Encoder;  
  17.    
  18. public class DESUtil {  
  19.    
  20.     Key key ;  
  21.    
  22.     public DESUtil() {  
  23.    
  24.     }  
  25.    
  26.     public DESUtil(String str) {  
  27.        setKey(str); // 生成密匙  
  28.     }  
  29.    
  30.     public Key getKey() {  
  31.        return key ;  
  32.     }  
  33.    
  34.     public void setKey(Key key) {  
  35.        this . key = key;  
  36.     }  
  37.    
  38.     /** 
  39.       * 根据参数生成 KEY 
  40.       */  
  41.     public void setKey(String strKey) {  
  42.        try {  
  43.            KeyGenerator _generator = KeyGenerator.getInstance ( "DES" );  
  44.            _generator.init( new SecureRandom(strKey.getBytes()));  
  45.            this . key = _generator.generateKey();  
  46.            _generator = null ;  
  47.        } catch (Exception e) {  
  48.            throw new RuntimeException(  
  49.                   "Error initializing SqlMap class. Cause: " + e);  
  50.        }  
  51.     }  
  52.    
  53.     /** 
  54.       * 加密 String 明文输入 ,String 密文输出 
  55.       */  
  56.     public String encryptStr(String strMing) {  
  57.        byte [] byteMi = null ;  
  58.        byte [] byteMing = null ;  
  59.        String strMi = "" ;  
  60.        BASE64Encoder base64en = new BASE64Encoder();  
  61.        try {  
  62.            byteMing = strMing.getBytes( "UTF8" );  
  63.            byteMi = this .encryptByte(byteMing);  
  64.            strMi = base64en.encode(byteMi);  
  65.        } catch (Exception e) {  
  66.            throw new RuntimeException(  
  67.                   "Error initializing SqlMap class. Cause: " + e);  
  68.        } finally {  
  69.            base64en = null ;  
  70.            byteMing = null ;  
  71.            byteMi = null ;  
  72.        }  
  73.        return strMi;  
  74.     }  
  75.    
  76.     /** 
  77.       * 解密 以 String 密文输入 ,String 明文输出 
  78.       * 
  79.       * @param strMi 
  80.       * @return 
  81.       */  
  82.     public String decryptStr(String strMi) {  
  83.        BASE64Decoder base64De = new BASE64Decoder();  
  84.        byte [] byteMing = null ;  
  85.        byte [] byteMi = null ;  
  86.        String strMing = "" ;  
  87.        try {  
  88.            byteMi = base64De.decodeBuffer(strMi);  
  89.            byteMing = this .decryptByte(byteMi);  
  90.            strMing = new String(byteMing, "UTF8" );  
  91.        } catch (Exception e) {  
  92.            throw new RuntimeException(  
  93.                   "Error initializing SqlMap class. Cause: " + e);  
  94.        } finally {  
  95.            base64De = null ;  
  96.            byteMing = null ;  
  97.            byteMi = null ;  
  98.        }  
  99.        return strMing;  
  100.     }  
  101.    
  102.     /** 
  103.       * 加密以 byte[] 明文输入 ,byte[] 密文输出 
  104.       * 
  105.       * @param byteS 
  106.       * @return 
  107.       */  
  108.     private byte [] encryptByte( byte [] byteS) {  
  109.        byte [] byteFina = null ;  
  110.        Cipher cipher;  
  111.        try {  
  112.            cipher = Cipher.getInstance ( "DES" );  
  113.            cipher.init(Cipher. ENCRYPT_MODE , key );  
  114.            byteFina = cipher.doFinal(byteS);  
  115.        } catch (Exception e) {  
  116.            throw new RuntimeException(  
  117.                   "Error initializing SqlMap class. Cause: " + e);  
  118.        } finally {  
  119.            cipher = null ;  
  120.        }  
  121.        return byteFina;  
  122.     }  
  123.    
  124.     /** 
  125.       * 解密以 byte[] 密文输入 , 以 byte[] 明文输出 
  126.       * 
  127.       * @param byteD 
  128.       * @return 
  129.       */  
  130.     private byte [] decryptByte( byte [] byteD) {  
  131.        Cipher cipher;  
  132.        byte [] byteFina = null ;  
  133.        try {  
  134.            cipher = Cipher.getInstance ( "DES" );  
  135.            cipher.init(Cipher. DECRYPT_MODE , key );  
  136.            byteFina = cipher.doFinal(byteD);  
  137.        } catch (Exception e) {  
  138.            throw new RuntimeException(  
  139.                   "Error initializing SqlMap class. Cause: " + e);  
  140.        } finally {  
  141.            cipher = null ;  
  142.        }  
  143.        return byteFina;  
  144.     }  
  145.    
  146.     /** 
  147.       * 文件 file 进行加密并保存目标文件 destFile 中 
  148.       * 
  149.       * @param file 
  150.       *             要加密的文件 如 c:/test/srcFile.txt 
  151.       * @param destFile 
  152.       *             加密后存放的文件名 如 c:/ 加密后文件 .txt 
  153.       */  
  154.     public void encryptFile(String file, String destFile) throws Exception {  
  155.        Cipher cipher = Cipher.getInstance ( "DES" );  
  156.        // cipher.init(Cipher.ENCRYPT_MODE, getKey());  
  157.        cipher.init(Cipher. ENCRYPT_MODE , this . key );  
  158.        InputStream is = new FileInputStream(file);  
  159.        OutputStream out = new FileOutputStream(destFile);  
  160.        CipherInputStream cis = new CipherInputStream(is, cipher);  
  161.        byte [] buffer = new byte [1024];  
  162.        int r;  
  163.        while ((r = cis.read(buffer)) > 0) {  
  164.            out.write(buffer, 0, r);  
  165.        }  
  166.        cis.close();  
  167.        is.close();  
  168.        out.close();  
  169.     }  
  170.    
  171.     /** 
  172.       * 文件采用 DES 算法解密文件 
  173.       * 
  174.       * @param file 
  175.       *             已加密的文件 如 c:/ 加密后文件 .txt * 
  176.       * @param destFile 
  177.       *             解密后存放的文件名 如 c:/ test/ 解密后文件 .txt 
  178.       */  
  179.     public void decryptFile(String file, String dest) throws Exception {  
  180.        Cipher cipher = Cipher.getInstance ( "DES" );  
  181.        cipher.init(Cipher. DECRYPT_MODE , this . key );  
  182.        InputStream is = new FileInputStream(file);  
  183.        OutputStream out = new FileOutputStream(dest);  
  184.        CipherOutputStream cos = new CipherOutputStream(out, cipher);  
  185.        byte [] buffer = new byte [1024];  
  186.        int r;  
  187.        while ((r = is.read(buffer)) >= 0) {  
  188.            cos.write(buffer, 0, r);  
  189.        }  
  190.        cos.close();  
  191.        out.close();  
  192.        is.close();  
  193.     }  
  194.    
  195.     public static void main(String[] args) throws Exception {  
  196.        DESUtil des = new DESUtil( "1234567" );  
  197.        // DES 加密文件  
  198.        // des.encryptFile("G:/test.doc", "G:/ 加密 test.doc");  
  199.        // DES 解密文件  
  200.        // des.decryptFile("G:/ 加密 test.doc", "G:/ 解密 test.doc");  
  201.        String str1 = " 要加密的字符串 test" ;  
  202.        // DES 加密字符串  
  203.        String str2 = des.encryptStr(str1);  
  204.        // DES 解密字符串  
  205.        String deStr = des.decryptStr(str2);  
  206.        System. out .println( " 加密前: " + str1);  
  207.        System. out .println( " 加密后: " + str2);  
  208.        System. out .println( " 解密后: " + deStr);  
  209.     }  
  210. }  


java的MD5加密、解密

  1. import java.security.*;   
  2. import java.security.spec.*;   
  3.   
  4. class MD5_test {   
  5.  public final static String MD5(String s) {   
  6.   char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',   
  7.     'a', 'b', 'c', 'd', 'e', 'f' };   
  8.   try {   
  9.    byte[] strTemp = s.getBytes();   
  10.    MessageDigest mdTemp = MessageDigest.getInstance("MD5");   
  11.    mdTemp.update(strTemp);   
  12.    byte[] md = mdTemp.digest();   
  13.    int j = md.length;   
  14.    char str[] = new char[j * 2];   
  15.    int k = 0;   
  16.    for (int i = 0; i < j; i++) {   
  17.     byte byte0 = md[i];   
  18.     str[k++] = hexDigits[byte0 >>> 4 & 0xf];   
  19.     str[k++] = hexDigits[byte0 & 0xf];   
  20.    }   
  21.    return new String(str);   
  22.   } catch (Exception e) {   
  23.    return null;   
  24.   }   
  25.  }   
  26.   
  27.  public static void main(String[] args) {   
  28.   // MD5_Test aa = new MD5_Test();   
  29.   System.out.print(MD5_test.MD5("b"));   
  30.  }   
  31. }  

 

加密,解密

  1. import java.security.MessageDigest;   
  2.   
  3.   
  4. public class MD5andKL {   
  •  // MD5加码。32位   
  •  public static String MD5(String inStr) {   
  •   MessageDigest md5 = null;   
  •   try {   
  •    md5 = MessageDigest.getInstance("MD5");   
  •   } catch (Exception e) {   
  •    System.out.println(e.toString());   
  •    e.printStackTrace();   
  •    return "";   
  •   }   
  •   char[] charArray = inStr.toCharArray();   
  •   byte[] byteArray = new byte[charArray.length];   
  •   
  •   for (int i = 0; i < charArray.length; i++)   
  •    byteArray[i] = (byte) charArray[i];   
  •   
  •   byte[] md5Bytes = md5.digest(byteArray);   
  •   
  •   StringBuffer hexValue = new StringBuffer();   
  •   
  •   for (int i = 0; i < md5Bytes.length; i++) {   
  •    int val = ((int) md5Bytes[i]) & 0xff;   
  •    if (val < 16)   
  •     hexValue.append("0");   
  •    hexValue.append(Integer.toHexString(val));   
  •   }   
  •   
  •   return hexValue.toString();   
  •  }   
  •   
  •  // 可逆的加密算法   
  •  public static String KL(String inStr) {   
  •   // String s = new String(inStr);   
  •   char[] a = inStr.toCharArray();   
  •   for (int i = 0; i < a.length; i++) {   
  •    a[i] = (char) (a[i] ^ 't');   
  •   }   
  •   String s = new String(a);   
  •   return s;   
  •  }   
  •   
  •  // 加密后解密   
  •  public static String JM(String inStr) {   
  •   char[] a = inStr.toCharArray();   
  •   for (int i = 0; i < a.length; i++) {   
  •    a[i] = (char) (a[i] ^ 't');   
  •   }   
  •   String k = new String(a);   
  •   return k;   
  •  }   
  •     
  •  // 测试主函数   
  •  public static void main(String args[]) {   
  •   String s = new String("a");   
  •   System.out.println("原始:" + s);   
  •   System.out.println("MD5后:" + MD5(s));   
  •   System.out.println("MD5后再加密:" + KL(MD5(s)));   
  •   System.out.println("解密为MD5后的:" + JM(KL(MD5(s))));   
  •  }   
  • }  

  • 阅读(4107) | 评论(0) | 转发(0) |
    给主人留下些什么吧!~~