Java常用的加密解密類
原文轉載至:http://blog.csdn.net/wyc_cs/article/details/8793198
最近做一個項目,想到以前所有的項目在用戶注冊與登錄及所有涉及用戶自身隱私的信息進行提交到后台時都沒有進行加密處理,甚至直接以明文方式在網絡上傳輸,同時直接以明文的方式存到數據庫中。所以想到需要先進行加密處理之后再進行網絡傳輸,最后將加密后的數據存到數據庫中,這樣也可以增強系統的安全性。
更多文章見: http://www.16boke.com
對於加密與解密是一個很復雜的學科,如果想了解更深入的加密解密知識可以參考其它資料,本文只講解一部分加密解密的使用方式。
常用的加密解密可以分為:信息摘要算法:MD5,SHA(也就是單向加密理論上無法解密)、對稱加密算法 :DES,3DES,AES、非對稱加密算法:RSA,DSA
本文只講解單向加密和對稱加密,關於非對稱加密在以后的時間里進行添加。直接上代碼,親測可以運行:
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import javax.crypto.Cipher;
- import javax.crypto.KeyGenerator;
- import javax.crypto.SecretKey;
- import javax.crypto.spec.SecretKeySpec;
- /**
- * 加密解密工具類
- */
- public class EncryptUtils {
- /**
- * 進行MD5加密
- *
- * @param info 要加密的信息
- * @return String 加密后的字符串
- */
- public String encryptToMD5(String info) {
- byte[] digesta = null;
- try {
- // 得到一個md5的消息摘要
- MessageDigest alga = MessageDigest.getInstance("MD5");
- // 添加要進行計算摘要的信息
- alga.update(info.getBytes());
- // 得到該摘要
- digesta = alga.digest();
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
- // 將摘要轉為字符串
- String rs = byte2hex(digesta);
- return rs;
- }
- /**
- * 進行SHA加密
- *
- * @param info 要加密的信息
- * @return String 加密后的字符串
- */
- public String encryptToSHA(String info) {
- byte[] digesta = null;
- try {
- // 得到一個SHA-1的消息摘要
- MessageDigest alga = MessageDigest.getInstance("SHA-1");
- // 添加要進行計算摘要的信息
- alga.update(info.getBytes());
- // 得到該摘要
- digesta = alga.digest();
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
- // 將摘要轉為字符串
- String rs = byte2hex(digesta);
- return rs;
- }
- /**
- * 根據一定的算法得到相應的key
- * @param src
- * @return
- */
- public String getKey(String algorithm,String src){
- if(algorithm.equals("AES")){
- return src.substring(0, 16);
- }else if(algorithm.equals("DES")){
- return src.substring(0, 8);
- }else{
- return null;
- }
- }
- /**
- * 得到AES加密的key
- * @param src
- * @return
- */
- public String getAESKey(String src){
- return this.getKey("AES", src);
- }
- /**
- * 得到DES加密的key
- * @param src
- * @return
- */
- public String getDESKey(String src){
- return this.getKey("DES", src);
- }
- /**
- * 創建密匙
- *
- * @param algorithm 加密算法,可用 AES,DES,DESede,Blowfish
- * @return SecretKey 秘密(對稱)密鑰
- */
- public SecretKey createSecretKey(String algorithm) {
- // 聲明KeyGenerator對象
- KeyGenerator keygen;
- // 聲明 密鑰對象
- SecretKey deskey = null;
- try {
- // 返回生成指定算法的秘密密鑰的 KeyGenerator 對象
- keygen = KeyGenerator.getInstance(algorithm);
- // 生成一個密鑰
- deskey = keygen.generateKey();
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
- // 返回密匙
- return deskey;
- }
- /**
- * 創建一個AES的密鑰
- * @return
- */
- public SecretKey createSecretAESKey() {
- return createSecretKey("AES");
- }
- /**
- * 創建一個DES的密鑰
- * @return
- */
- public SecretKey createSecretDESKey() {
- return createSecretKey("DES");
- }
- /**
- * 根據相應的加密算法、密鑰、源文件進行加密,返回加密后的文件
- * @param Algorithm 加密算法:DES,AES
- * @param key
- * @param info
- * @return
- */
- public String encrypt(String Algorithm, SecretKey key, String info) {
- // 定義要生成的密文
- byte[] cipherByte = null;
- try {
- // 得到加密/解密器
- Cipher c1 = Cipher.getInstance(Algorithm);
- // 用指定的密鑰和模式初始化Cipher對象
- // 參數:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
- c1.init(Cipher.ENCRYPT_MODE, key);
- // 對要加密的內容進行編碼處理,
- cipherByte = c1.doFinal(info.getBytes());
- } catch (Exception e) {
- e.printStackTrace();
- }
- // 返回密文的十六進制形式
- return byte2hex(cipherByte);
- }
- /**
- * 根據相應的解密算法、密鑰和需要解密的文本進行解密,返回解密后的文本內容
- * @param Algorithm
- * @param key
- * @param sInfo
- * @return
- */
- public String decrypt(String Algorithm, SecretKey key, String sInfo) {
- byte[] cipherByte = null;
- try {
- // 得到加密/解密器
- Cipher c1 = Cipher.getInstance(Algorithm);
- // 用指定的密鑰和模式初始化Cipher對象
- c1.init(Cipher.DECRYPT_MODE, key);
- // 對要解密的內容進行編碼處理
- cipherByte = c1.doFinal(hex2byte(sInfo));
- } catch (Exception e) {
- e.printStackTrace();
- }
- return new String(cipherByte);
- }
- /**
- * 根據相應的解密算法、指定的密鑰和需要解密的文本進行解密,返回解密后的文本內容
- * @param Algorithm 加密算法:DES,AES
- * @param key 這個key可以由用戶自己指定 注意AES的長度為16位,DES的長度為8位
- * @param sInfo
- * @return
- */
- public static String decrypt(String Algorithm, String sSrc, String sKey) throws Exception {
- try {
- // 判斷Key是否正確
- if (sKey == null) {
- throw new Exception("Key為空null");
- }
- // 判斷采用AES加解密方式的Key是否為16位
- if (Algorithm.equals("AES") && sKey.length() != 16) {
- throw new Exception("Key長度不是16位");
- }
- // 判斷采用DES加解密方式的Key是否為8位
- if (Algorithm.equals("DES") && sKey.length() != 8) {
- throw new Exception("Key長度不是8位");
- }
- byte[] raw = sKey.getBytes("ASCII");
- SecretKeySpec skeySpec = new SecretKeySpec(raw, Algorithm);
- Cipher cipher = Cipher.getInstance(Algorithm);
- cipher.init(Cipher.DECRYPT_MODE, skeySpec);
- byte[] encrypted1 = hex2byte(sSrc);
- try {
- byte[] original = cipher.doFinal(encrypted1);
- String originalString = new String(original);
- return originalString;
- } catch (Exception e) {
- throw e;
- }
- } catch (Exception ex) {
- throw ex;
- }
- }
- /**
- * 根據相應的加密算法、指定的密鑰、源文件進行加密,返回加密后的文件
- * @param Algorithm 加密算法:DES,AES
- * @param key 這個key可以由用戶自己指定 注意AES的長度為16位,DES的長度為8位
- * @param info
- * @return
- */
- public static String encrypt(String Algorithm, String sSrc, String sKey) throws Exception {
- // 判斷Key是否正確
- if (sKey == null) {
- throw new Exception("Key為空null");
- }
- // 判斷采用AES加解密方式的Key是否為16位
- if (Algorithm.equals("AES") && sKey.length() != 16) {
- throw new Exception("Key長度不是16位");
- }
- // 判斷采用DES加解密方式的Key是否為8位
- if (Algorithm.equals("DES") && sKey.length() != 8) {
- throw new Exception("Key長度不是8位");
- }
- byte[] raw = sKey.getBytes("ASCII");
- SecretKeySpec skeySpec = new SecretKeySpec(raw, Algorithm);
- Cipher cipher = Cipher.getInstance(Algorithm);
- cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
- byte[] encrypted = cipher.doFinal(sSrc.getBytes());
- return byte2hex(encrypted);
- }
- /**
- * 采用DES隨機生成的密鑰進行加密
- * @param key
- * @param info
- * @return
- */
- public String encryptToDES(SecretKey key, String info) {
- return encrypt("DES", key, info);
- }
- /**
- * 采用DES指定密鑰的方式進行加密
- * @param key
- * @param info
- * @return
- * @throws Exception
- */
- public String encryptToDES(String key, String info) throws Exception {
- return encrypt("DES", info, key);
- }
- /**
- * 采用DES隨機生成密鑰的方式進行解密,密鑰需要與加密的生成的密鑰一樣
- * @param key
- * @param sInfo
- * @return
- */
- public String decryptByDES(SecretKey key, String sInfo) {
- return decrypt("DES", key, sInfo);
- }
- /**
- * 采用DES用戶指定密鑰的方式進行解密,密鑰需要與加密時指定的密鑰一樣
- * @param key
- * @param sInfo
- * @return
- */
- public String decryptByDES(String key, String sInfo) throws Exception {
- return decrypt("DES", sInfo, key);
- }
- /**
- * 采用AES隨機生成的密鑰進行加密
- * @param key
- * @param info
- * @return
- */
- public String encryptToAES(SecretKey key, String info) {
- return encrypt("AES", key, info);
- }
- /**
- * 采用AES指定密鑰的方式進行加密
- * @param key
- * @param info
- * @return
- * @throws Exception
- */
- public String encryptToAES(String key, String info) throws Exception {
- return encrypt("AES", info, key);
- }
- /**
- * 采用AES隨機生成密鑰的方式進行解密,密鑰需要與加密的生成的密鑰一樣
- * @param key
- * @param sInfo
- * @return
- */
- public String decryptByAES(SecretKey key, String sInfo) {
- return decrypt("AES", key, sInfo);
- }
- /**
- * 采用AES用戶指定密鑰的方式進行解密,密鑰需要與加密時指定的密鑰一樣
- * @param key
- * @param sInfo
- * @return
- */
- public String decryptByAES(String key, String sInfo) throws Exception {
- return decrypt("AES", sInfo, key);
- }
- /**
- * 十六進制字符串轉化為2進制
- *
- * @param hex
- * @return
- */
- public static byte[] hex2byte(String strhex) {
- if (strhex == null) {
- return null;
- }
- int l = strhex.length();
- if (l % 2 == 1) {
- return null;
- }
- byte[] b = new byte[l / 2];
- for (int i = 0; i != l / 2; i++) {
- b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
- }
- return b;
- }
- /**
- * 將二進制轉化為16進制字符串
- *
- * @param b 二進制字節數組
- * @return String
- */
- public static String byte2hex(byte[] b) {
- String hs = "";
- String stmp = "";
- for (int n = 0; n < b.length; n++) {
- stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
- if (stmp.length() == 1) {
- hs = hs + "0" + stmp;
- } else {
- hs = hs + stmp;
- }
- }
- return hs.toUpperCase();
- }
- /**
- * 測試
- *
- * @param args
- */
- public static void main(String[] args) {
- EncryptUtils encryptUtils = new EncryptUtils();
- String source = "www.putiman.com";
- System.out.println("Hello經過MD5:" + encryptUtils.encryptToMD5(source));
- System.out.println("Hello經過SHA:" + encryptUtils.encryptToSHA(source));
- System.out.println("========隨機生成Key進行加解密==============");
- // 生成一個DES算法的密匙
- SecretKey key = encryptUtils.createSecretDESKey();
- String str1 = encryptUtils.encryptToDES(key, source);
- System.out.println("DES加密后為:" + str1);
- // 使用這個密匙解密
- String str2 = encryptUtils.decryptByDES(key, str1);
- System.out.println("DES解密后為:" + str2);
- // 生成一個AES算法的密匙
- SecretKey key1 = encryptUtils.createSecretAESKey();
- String stra = encryptUtils.encryptToAES(key1, source);
- System.out.println("AES加密后為:" + stra);
- // 使用這個密匙解密
- String strb = encryptUtils.decryptByAES(key1, stra);
- System.out.println("AES解密后為:" + strb);
- System.out.println("========指定Key進行加解密==============");
- try {
- String AESKey = encryptUtils.getAESKey(encryptUtils.encryptToSHA(source));
- String DESKey = encryptUtils.getDESKey(encryptUtils.encryptToSHA(source));
- System.out.println(AESKey);
- System.out.println(DESKey);
- String str11 = encryptUtils.encryptToDES(DESKey, source);
- System.out.println("DES加密后為:" + str11);
- // 使用這個密匙解密
- String str12 = encryptUtils.decryptByDES(DESKey, str11);
- System.out.println("DES解密后為:" + str12);
- // 生成一個AES算法的密匙
- String strc = encryptUtils.encryptToAES(AESKey, source);
- System.out.println("AES加密后為:" + strc);
- // 使用這個密匙解密
- String strd = encryptUtils.decryptByAES(AESKey, strc);
- System.out.println("AES解密后為:" + strd);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
更多文章見: http://www.16boke.com