java 加密解密工具類(實用!!!)

最近發現了一個加密解密的好例子,很方便使用,能夠做爲平時開發的工具集,記錄一下。java

  1 package com.sh.springboottdemo2.util;
  2 
  3 
  4 import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
  5 
  6 import javax.crypto.Cipher;
  7 import javax.crypto.KeyGenerator;
  8 import javax.crypto.Mac;
  9 import javax.crypto.SecretKey;
 10 import javax.crypto.spec.SecretKeySpec;
 11 import java.security.MessageDigest;
 12 import java.security.SecureRandom;
 13 
 14 public class EncryptUtil {
 15     public static final String MD5 = "MD5";
 16     public static final String SHA1 = "SHA1";
 17     public static final String HmacMD5 = "HmacMD5";
 18     public static final String HmacSHA1 = "HmacSHA1";
 19     public static final String DES = "DES";
 20     public static final String AES = "AES";
 21 
 22     /**編碼格式;默認使用uft-8*/
 23     public String charset = "utf-8";
 24     /**DES*/
 25     public int keysizeDES = 0;
 26     /**AES*/
 27     public int keysizeAES = 128;
 28 
 29     public static EncryptUtil me;
 30 
 31     private EncryptUtil(){
 32         //單例
 33     }
 34     //雙重鎖
 35     public static EncryptUtil getInstance(){
 36         if (me==null) {
 37            synchronized (EncryptUtil.class) {
 38                if(me == null){
 39                    me = new EncryptUtil();
 40                }
 41            }
 42         }
 43         return me;
 44     }
 45 
 46     /**
 47      * 使用MessageDigest進行單向加密(無密碼)
 48      * @param res 被加密的文本
 49      * @param algorithm 加密算法名稱
 50      * @return
 51      */
 52     private String messageDigest(String res,String algorithm){
 53         try {
 54             MessageDigest md = MessageDigest.getInstance(algorithm);
 55             byte[] resBytes = charset==null?res.getBytes():res.getBytes(charset);
 56             return base64(md.digest(resBytes));
 57         } catch (Exception e) {
 58             e.printStackTrace();
 59         }
 60         return null;
 61     }
 62 
 63     /**
 64      * 使用KeyGenerator進行單向/雙向加密(可設密碼)
 65      * @param res 被加密的原文
 66      * @param algorithm  加密使用的算法名稱
 67      * @param key 加密使用的祕鑰
 68      * @return
 69      */
 70     private String keyGeneratorMac(String res,String algorithm,String key){
 71         try {
 72             SecretKey sk = null;
 73             if (key==null) {
 74                 KeyGenerator kg = KeyGenerator.getInstance(algorithm);
 75                 sk = kg.generateKey();
 76             }else {
 77                 byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
 78                 sk = new SecretKeySpec(keyBytes, algorithm);
 79             }
 80             Mac mac = Mac.getInstance(algorithm);
 81             mac.init(sk);
 82             byte[] result = mac.doFinal(res.getBytes());
 83             return base64(result);
 84         } catch (Exception e) {
 85             e.printStackTrace();
 86         }
 87         return null;
 88     }
 89 
 90     /**
 91      * 使用KeyGenerator雙向加密,DES/AES,注意這裏轉化爲字符串的時候是將2進制轉爲16進制格式的字符串,不是直接轉,由於會出錯
 92      * @param res 加密的原文
 93      * @param algorithm 加密使用的算法名稱
 94      * @param key  加密的祕鑰
 95      * @param keysize
 96      * @param isEncode
 97      * @return
 98      */
 99     private String keyGeneratorES(String res,String algorithm,String key,int keysize,boolean isEncode){
100         try {
101             KeyGenerator kg = KeyGenerator.getInstance(algorithm);
102             if (keysize == 0) {
103                 byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
104                 kg.init(new SecureRandom(keyBytes));
105             }else if (key==null) {
106                 kg.init(keysize);
107             }else {
108                 byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
109                 kg.init(keysize, new SecureRandom(keyBytes));
110             }
111             SecretKey sk = kg.generateKey();
112             SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm);
113             Cipher cipher = Cipher.getInstance(algorithm);
114             if (isEncode) {
115                 cipher.init(Cipher.ENCRYPT_MODE, sks);
116                 byte[] resBytes = charset==null?res.getBytes():res.getBytes(charset);
117                 return parseByte2HexStr(cipher.doFinal(resBytes));
118             }else {
119                 cipher.init(Cipher.DECRYPT_MODE, sks);
120                 return new String(cipher.doFinal(parseHexStr2Byte(res)));
121             }
122         } catch (Exception e) {
123             e.printStackTrace();
124         }
125         return null;
126     }
127 
128     private String base64(byte[] res){
129         return Base64.encode(res);
130     }
131 
132     /**將二進制轉換成16進制 */
133     public static String parseByte2HexStr(byte buf[]) {
134         StringBuffer sb = new StringBuffer();
135         for (int i = 0; i < buf.length; i++) {
136             String hex = Integer.toHexString(buf[i] & 0xFF);
137             if (hex.length() == 1) {
138                 hex = '0' + hex;
139             }
140             sb.append(hex.toUpperCase());
141         }
142         return sb.toString();
143     }
144     /**將16進制轉換爲二進制*/
145     public static byte[] parseHexStr2Byte(String hexStr) {
146         if (hexStr.length() < 1)
147             return null;
148         byte[] result = new byte[hexStr.length()/2];
149         for (int i = 0;i< hexStr.length()/2; i++) {
150             int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
151             int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
152             result[i] = (byte) (high * 16 + low);
153         }
154         return result;
155     }
156 
157     /**
158      * md5加密算法進行加密(不可逆)
159      * @param res 須要加密的原文
160      * @return
161      */
162     public String MD5(String res) {
163         return messageDigest(res, MD5);
164     }
165 
166     /**
167      * md5加密算法進行加密(不可逆)
168      * @param res  須要加密的原文
169      * @param key  祕鑰
170      * @return
171      */
172     public String MD5(String res, String key) {
173         return keyGeneratorMac(res, HmacMD5, key);
174     }
175 
176     /**
177      * 使用SHA1加密算法進行加密(不可逆)
178      * @param res 須要加密的原文
179      * @return
180      */
181     public String SHA1(String res) {
182         return messageDigest(res, SHA1);
183     }
184 
185     /**
186      * 使用SHA1加密算法進行加密(不可逆)
187      * @param res 須要加密的原文
188      * @param key 祕鑰
189      * @return
190      */
191     public String SHA1(String res, String key) {
192         return keyGeneratorMac(res, HmacSHA1, key);
193     }
194 
195     /**
196      * 使用DES加密算法進行加密(可逆)
197      * @param res 須要加密的原文
198      * @param key 祕鑰
199      * @return
200      */
201     public String DESencode(String res, String key) {
202         return keyGeneratorES(res, DES, key, keysizeDES, true);
203     }
204 
205     /**
206      * 對使用DES加密算法的密文進行解密(可逆)
207      * @param res 須要解密的密文
208      * @param key 祕鑰
209      * @return
210      */
211     public String DESdecode(String res, String key) {
212         return keyGeneratorES(res, DES, key, keysizeDES, false);
213     }
214 
215     /**
216      * 使用AES加密算法經行加密(可逆)
217      * @param res 須要加密的密文
218      * @param key 祕鑰
219      * @return
220      */
221     public String AESencode(String res, String key) {
222         return keyGeneratorES(res, AES, key, keysizeAES, true);
223     }
224 
225     /**
226      * 對使用AES加密算法的密文進行解密
227      * @param res 須要解密的密文
228      * @param key 祕鑰
229      * @return
230      */
231     public String AESdecode(String res, String key) {
232         return keyGeneratorES(res, AES, key, keysizeAES, false);
233     }
234 
235     /**
236      * 使用異或進行加密
237      * @param res 須要加密的密文
238      * @param key 祕鑰
239      * @return
240      */
241     public String XORencode(String res, String key) {
242         byte[] bs = res.getBytes();
243         for (int i = 0; i < bs.length; i++) {
244             bs[i] = (byte) ((bs[i]) ^ key.hashCode());
245         }
246         return parseByte2HexStr(bs);
247     }
248 
249     /**
250      * 使用異或進行解密
251      * @param res 須要解密的密文
252      * @param key 祕鑰
253      * @return
254      */
255     public String XORdecode(String res, String key) {
256         byte[] bs = parseHexStr2Byte(res);
257         for (int i = 0; i < bs.length; i++) {
258             bs[i] = (byte) ((bs[i]) ^ key.hashCode());
259         }
260         return new String(bs);
261     }
262 
263     /**
264      * 直接使用異或(第一調用加密,第二次調用解密)
265      * @param res 密文
266      * @param key 祕鑰
267      * @return
268      */
269     public int XOR(int res, String key) {
270         return res ^ key.hashCode();
271     }
272 
273     /**
274      * 使用Base64進行加密
275      * @param res 密文
276      * @return
277      */
278     public String Base64Encode(String res) {
279         return Base64.encode(res.getBytes());
280     }
281 
282     /**
283      * 使用Base64進行解密
284      * @param res
285      * @return
286      */
287     public String Base64Decode(String res) {
288         return new String(Base64.decode(res));
289     }
290 }
相關文章
相關標籤/搜索