常见的集中加密方法BASE64、MD5、SHA、HMAC

  1 package com.ice.webos.util.security;
  2 
  3 import java.io.UnsupportedEncodingException;
  4 import java.math.BigInteger;
  5 import java.security.Key;
  6 import java.security.MessageDigest;
  7 import java.security.SecureRandom;
  8 
  9 import javax.crypto.Cipher;
 10 import javax.crypto.KeyGenerator;
 11 import javax.crypto.Mac;
 12 import javax.crypto.SecretKey;
 13 import javax.crypto.SecretKeyFactory;
 14 import javax.crypto.spec.DESKeySpec;
 15 import javax.crypto.spec.SecretKeySpec;
 16 
 17 import sun.misc.BASE64Decoder;
 18 import sun.misc.BASE64Encoder;
 19 
 20 /**
 21  * <ul>
 22  * <li>BASE64的加密解密是双向的,可以求反解。</li>
 23  * <li>MD5、SHA以及HMAC是单向加密,任何数据加密后只会产生唯一的一个加密串,通常用来校验数据在传输过程中是否被修改。</li>
 24  * <li>HMAC算法有一个密钥,增强了数据传输过程中的安全性,强化了算法外的不可控因素。</li>
 25  * <li>DES DES-Data Encryption Standard,即数据加密算法。
 26  * DES算法的入口参数有三个:Key、Data、Mode。
 27  * <ul>
 28  * <li>Key:8个字节共64位,是DES算法的工作密钥;</li>
 29  * <li>Data:8个字节64位,是要被加密或被解密的数据;</li>
 30  * <li>Mode:DES的工作方式,有两种:加密或解密。</li>
 31  * </ul>
 32  * </li>
 33  * <ul>
 34  * 
 35  * @author Ice_Liu
 36  * 
 37  */
 38 public class CryptUtil {
 39     private static final String KEY_MD5 = "MD5";
 40     private static final String KEY_SHA = "SHA";
 41     /**
 42      * MAC算法可选以下多种算法
 43      * 
 44      * <pre>
 45      *  
 46      * HmacMD5  
 47      * HmacSHA1  
 48      * HmacSHA256  
 49      * HmacSHA384  
 50      * HmacSHA512 
 51      * </pre>
 52 */
 53     public static final String KEY_MAC = "HmacMD5";
 54 
 55     /**
 56      * BASE64解密
 57      * 
 58      * @param key
 59      * @return
 60      * @throws Exception
 61 */
 62     public static byte[] decryptBASE64(String key) throws Exception {
 63         return (new BASE64Decoder()).decodeBuffer(key);
 64     }
 65 
 66     /**
 67      * BASE64 加密
 68      * 
 69      * @param key
 70      * @return
 71      * @throws Exception
 72 */
 73     public static String encryptBASE64(byte[] key) throws Exception {
 74         return (new BASE64Encoder()).encodeBuffer(key);
 75     }
 76 
 77     /**
 78      * MD5加密
 79      * 
 80      * @param data
 81      * @return
 82      * @throws Exception
 83 */
 84     public static byte[] encryptMD5(byte[] data) throws Exception {
 85 
 86         MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
 87         md5.update(data);
 88 
 89         return md5.digest();
 90 
 91     }
 92 
 93     /**
 94      * SHA加密
 95      * 
 96      * @param data
 97      * @return
 98      * @throws Exception
 99 */
100     public static byte[] encryptSHA(byte[] data) throws Exception {
101 
102         MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
103         sha.update(data);
104 
105         return sha.digest();
106 
107     }
108 
109     /**
110      * 初始化HMAC密钥
111      * 
112      * @return
113      * @throws Exception
114 */
115     public static String initMacKey() throws Exception {
116         KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
117         SecretKey secretKey = keyGenerator.generateKey();
118         return encryptBASE64(secretKey.getEncoded());
119     }
120 
121     /**
122      * HMAC 加密
123      * 
124      * @param data
125      * @param key
126      * @return
127      * @throws Exception
128 */
129     public static byte[] encryptHMAC(byte[] data, String key) throws Exception {
130         SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);
131         Mac mac = Mac.getInstance(secretKey.getAlgorithm());
132         mac.init(secretKey);
133         return mac.doFinal(data);
134     }
135 
136     /**
137      * DES 算法 <br>
138      * 可替换为以下任意一种算法,同时key值的size相应改变。
139      * 
140      * <pre>
141      * DES                  key size must be equal to 56 
142      * DESede(TripleDES)    key size must be equal to 112 or 168 
143      * AES                  key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available 
144      * Blowfish             key size must be multiple of 8, and can only range from 32 to 448 (inclusive) 
145      * RC2                  key size must be between 40 and 1024 bits 
146      * RC4(ARCFOUR)         key size must be between 40 and 1024 bits 
147      * </pre>
148 */
149     public static final String ALGORITHM = "DES";
150 
151     /**
152      * DES 算法转换密钥<br>
153      * 
154      * @param key
155      * @return
156      * @throws Exception
157 */
158     private static Key toKey(byte[] key) throws Exception {
159         SecretKey secretKey = null;
160         if (ALGORITHM.equals("DES") || ALGORITHM.equals("DESede")) {
161             DESKeySpec dks = new DESKeySpec(key);
162             SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
163             secretKey = keyFactory.generateSecret(dks);
164         } else {
165             // 当使用其他对称加密算法时,如AES、Blowfish等算法时,用下述代码替换上述三行代码
166             secretKey = new SecretKeySpec(key, ALGORITHM);
167         }
168         return secretKey;
169     }
170 
171     /**
172      * DES 算法解密
173      * 
174      * @param data
175      * @param key
176      * @return
177      * @throws Exception
178 */
179     public static byte[] decrypt(byte[] data, String key) throws Exception {
180         Key k = toKey(decryptBASE64(key));
181         Cipher cipher = Cipher.getInstance(ALGORITHM);
182         cipher.init(Cipher.DECRYPT_MODE, k);
183         return cipher.doFinal(data);
184     }
185 
186     /**
187      * DES 算法加密
188      * 
189      * @param data
190      * @param key
191      * @return
192      * @throws Exception
193 */
194     public static byte[] encrypt(byte[] data, String key) throws Exception {
195         Key k = toKey(decryptBASE64(key));
196         Cipher cipher = Cipher.getInstance(ALGORITHM);
197         cipher.init(Cipher.ENCRYPT_MODE, k);
198         return cipher.doFinal(data);
199     }
200 
201     /**
202      * DES 算法生成密钥
203      * 
204      * @return
205      * @throws Exception
206 */
207     public static String initKey() throws Exception {
208         return initKey(null);
209     }
210 
211     /**
212      * DES 算法生成密钥
213      * 
214      * @param seed
215      * @return
216      * @throws Exception
217 */
218     public static String initKey(String seed) throws Exception {
219         SecureRandom secureRandom = null;
220         if (seed != null) {
221             secureRandom = new SecureRandom(decryptBASE64(seed));
222         } else {
223             secureRandom = new SecureRandom();
224         }
225         KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
226         kg.init(secureRandom);
227         SecretKey secretKey = kg.generateKey();
228         return encryptBASE64(secretKey.getEncoded());
229     }
230 
231     public static void main(String[] args) {
232         try {
233             String s = "阿伯才的覆盖";
234             String b = CryptUtil.encryptBASE64(s.getBytes("UTF-8"));
235             System.out.println("BASE64加密后:" + b);
236             byte[] c = CryptUtil.decryptBASE64(b);
237             System.out.println("BASE64解密后:" + new String(c, "UTF-8"));
238 
239             c = encryptMD5(s.getBytes());
240             System.out.println("MD5   加密后:" + new BigInteger(c).toString(16));
241 
242             c = encryptSHA(s.getBytes());
243             System.out.println("SHA   加密后:" + new BigInteger(c).toString(16));
244 
245             String key = initMacKey();
246             System.out.println("HMAC密匙:" + key);
247             c = encryptHMAC(s.getBytes(), key);
248             System.out.println("HMAC  加密后:" + new BigInteger(c).toString(16));
249 
250             key = initKey();
251             System.out.println(ALGORITHM + "密钥:	" + key);
252             c = encrypt(s.getBytes("UTF-8"), key);
253             System.out.println(ALGORITHM + "   加密后:" + new BigInteger(c).toString(16));
254             c = decrypt(c, key);
255             System.out.println(ALGORITHM + "   解密后:" + new String(c, "UTF-8"));
256         } catch (UnsupportedEncodingException e) {
257         } catch (Exception e) {
258         }
259     }
260 }
原文地址:https://www.cnblogs.com/wdpnodecodes/p/8001599.html