Java常用的加密解密類(對稱加密類)


Java常用的加密解密類

原文轉載至:http://blog.csdn.net/wyc_cs/article/details/8793198

原創 2013年04月12日 14:33:35
最近做一個項目,想到以前所有的項目在用戶注冊與登錄及所有涉及用戶自身隱私的信息進行提交到后台時都沒有進行加密處理,甚至直接以明文方式在網絡上傳輸,同時直接以明文的方式存到數據庫中。所以想到需要先進行加密處理之后再進行網絡傳輸,最后將加密后的數據存到數據庫中,這樣也可以增強系統的安全性。

對於加密與解密是一個很復雜的學科,如果想了解更深入的加密解密知識可以參考其它資料,本文只講解一部分加密解密的使用方式。

常用的加密解密可以分為:信息摘要算法:MD5,SHA(也就是單向加密理論上無法解密)、對稱加密算法 :DES,3DES,AES、非對稱加密算法:RSA,DSA

本文只講解單向加密和對稱加密,關於非對稱加密在以后的時間里進行添加。直接上代碼,親測可以運行:

 

[java]  view plain  copy
 
  1. import java.security.MessageDigest;  
  2. import java.security.NoSuchAlgorithmException;  
  3.   
  4. import javax.crypto.Cipher;  
  5. import javax.crypto.KeyGenerator;  
  6. import javax.crypto.SecretKey;  
  7. import javax.crypto.spec.SecretKeySpec;  
  8. /** 
  9.  * 加密解密工具類 
  10.  */  
  11. public class EncryptUtils {  
  12.     /** 
  13.      * 進行MD5加密 
  14.      *  
  15.      * @param info 要加密的信息 
  16.      * @return String 加密后的字符串 
  17.      */  
  18.     public String encryptToMD5(String info) {  
  19.         byte[] digesta = null;  
  20.         try {  
  21.             // 得到一個md5的消息摘要  
  22.             MessageDigest alga = MessageDigest.getInstance("MD5");  
  23.             // 添加要進行計算摘要的信息  
  24.             alga.update(info.getBytes());  
  25.             // 得到該摘要  
  26.             digesta = alga.digest();  
  27.         } catch (NoSuchAlgorithmException e) {  
  28.             e.printStackTrace();  
  29.         }  
  30.         // 將摘要轉為字符串  
  31.         String rs = byte2hex(digesta);  
  32.         return rs;  
  33.     }  
  34.   
  35.     /** 
  36.      * 進行SHA加密 
  37.      *  
  38.      * @param info 要加密的信息 
  39.      * @return String 加密后的字符串 
  40.      */  
  41.     public String encryptToSHA(String info) {  
  42.         byte[] digesta = null;  
  43.         try {  
  44.             // 得到一個SHA-1的消息摘要  
  45.             MessageDigest alga = MessageDigest.getInstance("SHA-1");  
  46.             // 添加要進行計算摘要的信息  
  47.             alga.update(info.getBytes());  
  48.             // 得到該摘要  
  49.             digesta = alga.digest();  
  50.         } catch (NoSuchAlgorithmException e) {  
  51.             e.printStackTrace();  
  52.         }  
  53.         // 將摘要轉為字符串  
  54.         String rs = byte2hex(digesta);  
  55.         return rs;  
  56.     }  
  57.       
  58.   
  59.     /** 
  60.      * 根據一定的算法得到相應的key 
  61.      * @param src 
  62.      * @return 
  63.      */  
  64.     public String getKey(String algorithm,String src){  
  65.         if(algorithm.equals("AES")){  
  66.             return src.substring(0, 16);  
  67.         }else if(algorithm.equals("DES")){  
  68.             return src.substring(0, 8);  
  69.         }else{  
  70.             return null;  
  71.         }  
  72.     }  
  73.     /** 
  74.      * 得到AES加密的key 
  75.      * @param src 
  76.      * @return 
  77.      */  
  78.     public String getAESKey(String src){  
  79.         return this.getKey("AES", src);  
  80.     }  
  81.     /** 
  82.      * 得到DES加密的key 
  83.      * @param src 
  84.      * @return 
  85.      */  
  86.     public String getDESKey(String src){  
  87.         return this.getKey("DES", src);  
  88.     }  
  89.     /** 
  90.      * 創建密匙 
  91.      *  
  92.      * @param algorithm 加密算法,可用 AES,DES,DESede,Blowfish 
  93.      * @return SecretKey 秘密(對稱)密鑰 
  94.      */  
  95.     public SecretKey createSecretKey(String algorithm) {  
  96.         // 聲明KeyGenerator對象  
  97.         KeyGenerator keygen;  
  98.         // 聲明 密鑰對象  
  99.         SecretKey deskey = null;  
  100.         try {  
  101.             // 返回生成指定算法的秘密密鑰的 KeyGenerator 對象  
  102.             keygen = KeyGenerator.getInstance(algorithm);  
  103.             // 生成一個密鑰  
  104.             deskey = keygen.generateKey();  
  105.         } catch (NoSuchAlgorithmException e) {  
  106.             e.printStackTrace();  
  107.         }  
  108.         // 返回密匙  
  109.         return deskey;  
  110.     }  
  111.   
  112.     /** 
  113.      * 創建一個AES的密鑰 
  114.      * @return 
  115.      */  
  116.     public SecretKey createSecretAESKey() {  
  117.         return createSecretKey("AES");  
  118.     }  
  119.   
  120.     /** 
  121.      * 創建一個DES的密鑰 
  122.      * @return 
  123.      */  
  124.     public SecretKey createSecretDESKey() {  
  125.         return createSecretKey("DES");  
  126.     }  
  127.   
  128.     /** 
  129.      * 根據相應的加密算法、密鑰、源文件進行加密,返回加密后的文件 
  130.      * @param Algorithm 加密算法:DES,AES 
  131.      * @param key 
  132.      * @param info 
  133.      * @return 
  134.      */  
  135.     public String encrypt(String Algorithm, SecretKey key, String info) {  
  136.         // 定義要生成的密文  
  137.         byte[] cipherByte = null;  
  138.         try {  
  139.             // 得到加密/解密器  
  140.             Cipher c1 = Cipher.getInstance(Algorithm);  
  141.             // 用指定的密鑰和模式初始化Cipher對象  
  142.             // 參數:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)  
  143.             c1.init(Cipher.ENCRYPT_MODE, key);  
  144.             // 對要加密的內容進行編碼處理,  
  145.             cipherByte = c1.doFinal(info.getBytes());  
  146.         } catch (Exception e) {  
  147.             e.printStackTrace();  
  148.         }  
  149.         // 返回密文的十六進制形式  
  150.         return byte2hex(cipherByte);  
  151.     }  
  152.   
  153.     /** 
  154.      * 根據相應的解密算法、密鑰和需要解密的文本進行解密,返回解密后的文本內容 
  155.      * @param Algorithm 
  156.      * @param key 
  157.      * @param sInfo 
  158.      * @return 
  159.      */  
  160.     public String decrypt(String Algorithm, SecretKey key, String sInfo) {  
  161.         byte[] cipherByte = null;  
  162.         try {  
  163.             // 得到加密/解密器  
  164.             Cipher c1 = Cipher.getInstance(Algorithm);  
  165.             // 用指定的密鑰和模式初始化Cipher對象  
  166.             c1.init(Cipher.DECRYPT_MODE, key);  
  167.             // 對要解密的內容進行編碼處理  
  168.             cipherByte = c1.doFinal(hex2byte(sInfo));  
  169.         } catch (Exception e) {  
  170.             e.printStackTrace();  
  171.         }  
  172.         return new String(cipherByte);  
  173.     }  
  174.   
  175.     /** 
  176.      * 根據相應的解密算法、指定的密鑰和需要解密的文本進行解密,返回解密后的文本內容 
  177.      * @param Algorithm 加密算法:DES,AES 
  178.      * @param key 這個key可以由用戶自己指定 注意AES的長度為16位,DES的長度為8位 
  179.      * @param sInfo 
  180.      * @return 
  181.      */  
  182.     public static String decrypt(String Algorithm, String sSrc, String sKey) throws Exception {  
  183.         try {  
  184.             // 判斷Key是否正確  
  185.             if (sKey == null) {  
  186.                 throw new Exception("Key為空null");  
  187.             }  
  188.             // 判斷采用AES加解密方式的Key是否為16位  
  189.             if (Algorithm.equals("AES") && sKey.length() != 16) {  
  190.                 throw new Exception("Key長度不是16位");  
  191.             }  
  192.             // 判斷采用DES加解密方式的Key是否為8位  
  193.             if (Algorithm.equals("DES") && sKey.length() != 8) {  
  194.                 throw new Exception("Key長度不是8位");  
  195.             }  
  196.             byte[] raw = sKey.getBytes("ASCII");  
  197.             SecretKeySpec skeySpec = new SecretKeySpec(raw, Algorithm);  
  198.             Cipher cipher = Cipher.getInstance(Algorithm);  
  199.             cipher.init(Cipher.DECRYPT_MODE, skeySpec);  
  200.             byte[] encrypted1 = hex2byte(sSrc);  
  201.             try {  
  202.                 byte[] original = cipher.doFinal(encrypted1);  
  203.                 String originalString = new String(original);  
  204.                 return originalString;  
  205.             } catch (Exception e) {  
  206.                 throw e;  
  207.             }  
  208.         } catch (Exception ex) {  
  209.             throw ex;  
  210.         }  
  211.     }  
  212.   
  213.     /** 
  214.      * 根據相應的加密算法、指定的密鑰、源文件進行加密,返回加密后的文件 
  215.      * @param Algorithm 加密算法:DES,AES 
  216.      * @param key 這個key可以由用戶自己指定 注意AES的長度為16位,DES的長度為8位 
  217.      * @param info 
  218.      * @return 
  219.      */  
  220.     public static String encrypt(String Algorithm, String sSrc, String sKey) throws Exception {  
  221.         // 判斷Key是否正確  
  222.         if (sKey == null) {  
  223.             throw new Exception("Key為空null");  
  224.         }  
  225.         // 判斷采用AES加解密方式的Key是否為16位  
  226.         if (Algorithm.equals("AES") && sKey.length() != 16) {  
  227.             throw new Exception("Key長度不是16位");  
  228.         }  
  229.         // 判斷采用DES加解密方式的Key是否為8位  
  230.         if (Algorithm.equals("DES") && sKey.length() != 8) {  
  231.             throw new Exception("Key長度不是8位");  
  232.         }  
  233.         byte[] raw = sKey.getBytes("ASCII");  
  234.         SecretKeySpec skeySpec = new SecretKeySpec(raw, Algorithm);  
  235.         Cipher cipher = Cipher.getInstance(Algorithm);  
  236.         cipher.init(Cipher.ENCRYPT_MODE, skeySpec);  
  237.         byte[] encrypted = cipher.doFinal(sSrc.getBytes());  
  238.         return byte2hex(encrypted);  
  239.     }  
  240.   
  241.     /** 
  242.      * 采用DES隨機生成的密鑰進行加密 
  243.      * @param key 
  244.      * @param info 
  245.      * @return 
  246.      */  
  247.     public String encryptToDES(SecretKey key, String info) {  
  248.         return encrypt("DES", key, info);  
  249.     }  
  250.   
  251.     /** 
  252.      * 采用DES指定密鑰的方式進行加密 
  253.      * @param key 
  254.      * @param info 
  255.      * @return 
  256.      * @throws Exception 
  257.      */  
  258.     public String encryptToDES(String key, String info) throws Exception {  
  259.         return encrypt("DES", info, key);  
  260.     }  
  261.   
  262.     /** 
  263.      * 采用DES隨機生成密鑰的方式進行解密,密鑰需要與加密的生成的密鑰一樣 
  264.      * @param key 
  265.      * @param sInfo 
  266.      * @return 
  267.      */  
  268.     public String decryptByDES(SecretKey key, String sInfo) {  
  269.         return decrypt("DES", key, sInfo);  
  270.     }  
  271.   
  272.     /** 
  273.      * 采用DES用戶指定密鑰的方式進行解密,密鑰需要與加密時指定的密鑰一樣 
  274.      * @param key 
  275.      * @param sInfo 
  276.      * @return 
  277.      */  
  278.     public String decryptByDES(String key, String sInfo) throws Exception {  
  279.         return decrypt("DES", sInfo, key);  
  280.     }  
  281.   
  282.     /** 
  283.      * 采用AES隨機生成的密鑰進行加密 
  284.      * @param key 
  285.      * @param info 
  286.      * @return 
  287.      */  
  288.     public String encryptToAES(SecretKey key, String info) {  
  289.         return encrypt("AES", key, info);  
  290.     }  
  291.     /** 
  292.      * 采用AES指定密鑰的方式進行加密 
  293.      * @param key 
  294.      * @param info 
  295.      * @return 
  296.      * @throws Exception 
  297.      */  
  298.     public String encryptToAES(String key, String info) throws Exception {  
  299.         return encrypt("AES", info, key);  
  300.     }  
  301.   
  302.     /** 
  303.      * 采用AES隨機生成密鑰的方式進行解密,密鑰需要與加密的生成的密鑰一樣 
  304.      * @param key 
  305.      * @param sInfo 
  306.      * @return 
  307.      */  
  308.     public String decryptByAES(SecretKey key, String sInfo) {  
  309.         return decrypt("AES", key, sInfo);  
  310.     }  
  311.     /** 
  312.      * 采用AES用戶指定密鑰的方式進行解密,密鑰需要與加密時指定的密鑰一樣 
  313.      * @param key 
  314.      * @param sInfo 
  315.      * @return 
  316.      */  
  317.     public String decryptByAES(String key, String sInfo) throws Exception {  
  318.         return decrypt("AES", sInfo, key);  
  319.     }  
  320.   
  321.     /** 
  322.      * 十六進制字符串轉化為2進制 
  323.      *  
  324.      * @param hex 
  325.      * @return 
  326.      */  
  327.     public static byte[] hex2byte(String strhex) {  
  328.         if (strhex == null) {  
  329.             return null;  
  330.         }  
  331.         int l = strhex.length();  
  332.         if (l % 2 == 1) {  
  333.             return null;  
  334.         }  
  335.         byte[] b = new byte[l / 2];  
  336.         for (int i = 0; i != l / 2; i++) {  
  337.             b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);  
  338.         }  
  339.         return b;  
  340.     }  
  341.   
  342.     /** 
  343.      * 將二進制轉化為16進制字符串 
  344.      *  
  345.      * @param b 二進制字節數組 
  346.      * @return String 
  347.      */  
  348.     public static String byte2hex(byte[] b) {  
  349.         String hs = "";  
  350.         String stmp = "";  
  351.         for (int n = 0; n < b.length; n++) {  
  352.             stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));  
  353.             if (stmp.length() == 1) {  
  354.                 hs = hs + "0" + stmp;  
  355.             } else {  
  356.                 hs = hs + stmp;  
  357.             }  
  358.         }  
  359.         return hs.toUpperCase();  
  360.     }  
  361.   
  362.     /** 
  363.      * 測試 
  364.      *  
  365.      * @param args 
  366.      */  
  367.     public static void main(String[] args) {  
  368.         EncryptUtils encryptUtils = new EncryptUtils();  
  369.         String source = "www.putiman.com";  
  370.         System.out.println("Hello經過MD5:" + encryptUtils.encryptToMD5(source));  
  371.         System.out.println("Hello經過SHA:" + encryptUtils.encryptToSHA(source));  
  372.         System.out.println("========隨機生成Key進行加解密==============");  
  373.         // 生成一個DES算法的密匙  
  374.         SecretKey key = encryptUtils.createSecretDESKey();  
  375.         String str1 = encryptUtils.encryptToDES(key, source);  
  376.         System.out.println("DES加密后為:" + str1);  
  377.         // 使用這個密匙解密  
  378.         String str2 = encryptUtils.decryptByDES(key, str1);  
  379.         System.out.println("DES解密后為:" + str2);  
  380.   
  381.         // 生成一個AES算法的密匙  
  382.         SecretKey key1 = encryptUtils.createSecretAESKey();  
  383.         String stra = encryptUtils.encryptToAES(key1, source);  
  384.         System.out.println("AES加密后為:" + stra);  
  385.         // 使用這個密匙解密  
  386.         String strb = encryptUtils.decryptByAES(key1, stra);  
  387.         System.out.println("AES解密后為:" + strb);  
  388.         System.out.println("========指定Key進行加解密==============");  
  389.         try {  
  390.             String AESKey = encryptUtils.getAESKey(encryptUtils.encryptToSHA(source));  
  391.             String DESKey = encryptUtils.getDESKey(encryptUtils.encryptToSHA(source));  
  392.             System.out.println(AESKey);  
  393.             System.out.println(DESKey);  
  394.             String str11 = encryptUtils.encryptToDES(DESKey, source);  
  395.             System.out.println("DES加密后為:" + str11);  
  396.             // 使用這個密匙解密  
  397.             String str12 = encryptUtils.decryptByDES(DESKey, str11);  
  398.             System.out.println("DES解密后為:" + str12);  
  399.   
  400.             // 生成一個AES算法的密匙  
  401.             String strc = encryptUtils.encryptToAES(AESKey, source);  
  402.             System.out.println("AES加密后為:" + strc);  
  403.             // 使用這個密匙解密  
  404.             String strd = encryptUtils.decryptByAES(AESKey, strc);  
  405.             System.out.println("AES解密后為:" + strd);  
  406.         } catch (Exception e) {  
  407.             e.printStackTrace();  
  408.         }  
  409.     }  
  410. }  
 

更多文章見: http://www.16boke.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM