AES加密與解密(秘鑰)


轉載地址:https://blog.csdn.net/lichuangcsdn/article/details/80842338

 

  1 package com.snsoft.modules.biz.test;
  2 
  3 import org.slf4j.Logger;
  4 import org.slf4j.LoggerFactory;
  5 import sun.misc.BASE64Decoder;
  6 import sun.misc.BASE64Encoder;
  7 import tk.mybatis.mapper.util.StringUtil;
  8 
  9 import javax.crypto.Cipher;
 10 import javax.crypto.KeyGenerator;
 11 import javax.crypto.SecretKey;
 12 import javax.crypto.spec.SecretKeySpec;
 13 import java.io.IOException;
 14 import java.security.SecureRandom;
 15 
 16 /**
 17  * AES加密解密
 18  *
 19  * @author lichuang
 20  * @since 2018-03-23
 21  */
 22 public class SecurityUtil {
 23 
 24     private static final Logger logger = LoggerFactory.getLogger(SecurityUtil.class);
 25 
 26     private static final String ENCODING = "UTF-8";
 27 
 28     private static final String PASSWORD = "46EBA22EF5204DD5B110A1F730513965"; // 加密秘鑰
 29 
 30     /**
 31      * AES加密
 32      *
 33      * @param content
 34      *            明文
 35      * @return 密文
 36      */
 37     public static String encryptAES(String content) {
 38         if (StringUtil.isEmpty(content)) {
 39             throw new RuntimeException("明文不能為空!");
 40         }
 41         byte[] encryptResult = encrypt(content, PASSWORD);
 42         String encryptResultStr = parseByte2HexStr(encryptResult);
 43         // BASE64位加密
 44         encryptResultStr = ebotongEncrypto(encryptResultStr);
 45         return encryptResultStr;
 46     }
 47 
 48     /**
 49      * AES解密
 50      *
 51      * @param encryptResultStr
 52      *            密文
 53      * @return 明文
 54      */
 55     public static String decryptAES(String encryptResultStr) {
 56         if (StringUtil.isEmpty(encryptResultStr)) {
 57             throw new RuntimeException("密文不能為空");
 58         }
 59         // BASE64位解密
 60         try {
 61             String decrpt = ebotongDecrypto(encryptResultStr);
 62             byte[] decryptFrom = parseHexStr2Byte(decrpt);
 63             byte[] decryptResult = decrypt(decryptFrom, PASSWORD);
 64             return new String(decryptResult);
 65         } catch (Exception e) { // 當密文不規范時會報錯,可忽略,但調用的地方需要考慮
 66             return null;
 67         }
 68     }
 69 
 70     /**
 71      * 加密字符串
 72      */
 73     private static String ebotongEncrypto(String str) {
 74         BASE64Encoder base64encoder = new BASE64Encoder();
 75         String result = str;
 76         if (str != null && str.length() > 0) {
 77             try {
 78                 byte[] encodeByte = str.getBytes(ENCODING);
 79                 result = base64encoder.encode(encodeByte);
 80             } catch (Exception e) {
 81                 e.printStackTrace();
 82             }
 83         }
 84         // base64加密超過一定長度會自動換行 需要去除換行符
 85         return result.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
 86     }
 87 
 88     /**
 89      * 解密字符串
 90      */
 91     private static String ebotongDecrypto(String str) {
 92         BASE64Decoder base64decoder = new BASE64Decoder();
 93         try {
 94             byte[] encodeByte = base64decoder.decodeBuffer(str);
 95             return new String(encodeByte);
 96         } catch (IOException e) {
 97             logger.error("IO 異常",e);
 98             return str;
 99         }
100     }
101 
102     /**
103      * 加密
104      *
105      * @param content
106      *            需要加密的內容
107      * @param password
108      *            加密密碼
109      * @return
110      */
111     private static byte[] encrypt(String content, String password) {
112         try {
113             KeyGenerator kgen = KeyGenerator.getInstance("AES");
114             // 注意這句是關鍵,防止linux下 隨機生成key。用其他方式在Windows上正常,但Linux上會有問題
115             SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
116             secureRandom.setSeed(password.getBytes());
117             kgen.init(128, secureRandom);
118             // kgen.init(128, new SecureRandom(password.getBytes()));
119             SecretKey secretKey = kgen.generateKey();
120             byte[] enCodeFormat = secretKey.getEncoded();
121             SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
122             Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
123             byte[] byteContent = content.getBytes("utf-8");
124             cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
125             byte[] result = cipher.doFinal(byteContent);
126             return result; // 加密
127         } catch (Exception e) {
128             logger.error("加密異常", e);
129         }
130         return null;
131     }
132 
133     /**
134      * 解密
135      *
136      * @param content
137      *            待解密內容
138      * @param password
139      *            解密密鑰
140      * @return
141      */
142     private static byte[] decrypt(byte[] content, String password) {
143         try {
144             KeyGenerator kgen = KeyGenerator.getInstance("AES");
145             // 防止linux下 隨機生成key
146             SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
147             secureRandom.setSeed(password.getBytes());
148             kgen.init(128, secureRandom);
149             // kgen.init(128, new SecureRandom(password.getBytes()));
150             SecretKey secretKey = kgen.generateKey();
151             byte[] enCodeFormat = secretKey.getEncoded();
152             SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
153             Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
154             cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
155             byte[] result = cipher.doFinal(content);
156             return result; // 加密
157         } catch (Exception e) {
158             logger.error("解密異常", e);
159         }
160         return null;
161     }
162 
163     /**
164      * 將二進制轉換成16進制
165      *
166      * @param buf
167      * @return
168      */
169     private static String parseByte2HexStr(byte buf[]) {
170         StringBuffer sb = new StringBuffer();
171         for (int i = 0; i < buf.length; i++) {
172             String hex = Integer.toHexString(buf[i] & 0xFF);
173             if (hex.length() == 1) {
174                 hex = '0' + hex;
175             }
176             sb.append(hex.toUpperCase());
177         }
178         return sb.toString();
179     }
180 
181     /**
182      * 將16進制轉換為二進制
183      *
184      * @param hexStr
185      * @return
186      */
187     private static byte[] parseHexStr2Byte(String hexStr) {
188         if (hexStr.length() < 1)
189             return null;
190         byte[] result = new byte[hexStr.length() / 2];
191         for (int i = 0; i < hexStr.length() / 2; i++) {
192             int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
193             int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
194             result[i] = (byte) (high * 16 + low);
195         }
196         return result;
197     }
198 
199     public static void main(String[] args) {
200         express();
201     }
202 
203     /**
204      * 測試
205      */
206     private static void express() {
207         System.out.println("加密解密試試:");
208         String content = "你好北京";
209         System.out.println("原內容為:" + content);
210         String encryContent = encryptAES(content);
211         System.out.println("加密后的內容為:" + encryContent);
212         String decryContent = decryptAES(encryContent);
213         System.out.println("解密后的內容為:" + decryContent);
214     }
215 
216 }

 


免責聲明!

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



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