自寫AES加密解密工具類

来源:http://www.cnblogs.com/PJH-Forever/archive/2016/08/29/5820216.html
-Advertisement-
Play Games

此類主要用於加密與解密,採用128位ECB模式,PKCS5Padding填充補位。 可使用方法為加密返回二進位encryptBin(content, key)、加密返回十六進位encryptHex(content, key)、二進位內容解密decryptBin(content, key)、十六進位內 ...


此類主要用於加密與解密,採用128位ECB模式,PKCS5Padding填充補位。

可使用方法為加密返回二進位encryptBin(content, key)、加密返回十六進位encryptHex(content, key)、二進位內容解密decryptBin(content, key)、十六進位內容解密decryptHex(content, key)。

content是需要加密的字元串,key是密鑰,隨意一個字元串。

  1 package com.test;
  2 
  3 import java.io.UnsupportedEncodingException;
  4 import java.security.InvalidKeyException;
  5 import java.security.NoSuchAlgorithmException;
  6 import java.security.SecureRandom;
  7 
  8 import javax.crypto.BadPaddingException;
  9 import javax.crypto.Cipher;
 10 import javax.crypto.IllegalBlockSizeException;
 11 import javax.crypto.KeyGenerator;
 12 import javax.crypto.NoSuchPaddingException;
 13 import javax.crypto.SecretKey;
 14 import javax.crypto.spec.SecretKeySpec;
 15 
 16 import org.apache.commons.logging.Log;
 17 import org.apache.commons.logging.LogFactory;
 18 
 19 public class AESCode {
 20     
 21     private static final String algorithm = "AES";
 22     private static final String transformation = "AES/ECB/PKCS5Padding";
 23     private static final String charset = "utf-8";
 24     
 25     private static final Log _log = LogFactory.getLog(AESCode.class);
 26     
 27     /**
 28      * 獲取key 填充密匙 獲取加密的密匙數據
 29      * 
 30      * @paramString key
 31      * @return byte[] enCodeFormat;
 32      * @author panjianghong 2016-8-29
 33      * */
 34     private static byte[] getEnCodeFormat(String key){
 35 
 36         try {
 37             KeyGenerator kgen = KeyGenerator.getInstance("AES");
 38             kgen.init(128, new SecureRandom(key.getBytes()));
 39             SecretKey secretKey = kgen.generateKey();
 40             byte[] enCodeFormat = secretKey.getEncoded();
 41             return enCodeFormat;
 42         } catch (NoSuchAlgorithmException e) {
 43             _log.error("獲取密匙數據失敗!");
 44         } 
 45         return null;
 46     }
 47     
 48     
 49     
 50     /**
 51      * 獲取加密數據的二進位字元串數據
 52      * 
 53      * @param  content
 54      * @param  enCodeFormat
 55      * @return String 
 56      * @author panjianghong 2016-8-29
 57      * */
 58     public static String encryptBin(String content, String key){
 59         
 60         try {
 61             byte[] byteConten = encrypt(content, key);
 62             return byte2BinString(byteConten);
 63         } catch (Exception e) {
 64             _log.error("獲取二進位加密數據失敗!");
 65         }
 66         return null;
 67     }
 68     
 69     
 70     
 71     /**
 72      * 獲取加密數據的十六進位字元串數據
 73      * 
 74      * @param  content
 75      * @param  enCodeFormat
 76      * @return String 
 77      * @author panjianghong 2016-8-29
 78      * */
 79     public static String encryptHex(String content, String key){
 80         
 81         try {
 82             byte[] byteConten = encrypt(content, key);
 83             return byte2HexString(byteConten);
 84         } catch (Exception e) {
 85             _log.error("獲取十六進位加密數據失敗!");
 86         }
 87         return null;
 88     }
 89     
 90 
 91     /**
 92      * 獲取文件的加密數據
 93      * 返回加密數據的位元組數組 byte[] 
 94      * 
 95      * @param  content
 96      * @param  enCodeFormat
 97      * @return  byte[] byteResoult 
 98      * @author panjianghong 2016-8-29
 99      * */
100     private static byte[] encrypt(String content, String key){
101         
102         try {
103             SecretKeySpec secretyKey = new SecretKeySpec(getEnCodeFormat(key), algorithm);
104             Cipher cipher = Cipher.getInstance(transformation);
105             byte[] byteContent = content.getBytes(charset);
106             cipher.init(Cipher.ENCRYPT_MODE, secretyKey);
107             byte[] byteResoult = cipher.doFinal(byteContent);
108             return byteResoult;
109         } catch (InvalidKeyException e) {
110             _log.error("獲取加密數據的位元組數組失敗!");
111         } catch (NoSuchAlgorithmException e) {
112             _log.error("獲取加密數據的位元組數組失敗!");
113         } catch (NoSuchPaddingException e) {
114             _log.error("獲取加密數據的位元組數組失敗!");
115         } catch (UnsupportedEncodingException e) {
116             _log.error("獲取加密數據的位元組數組失敗!");
117         } catch (IllegalBlockSizeException e) {
118             _log.error("獲取加密數據的位元組數組失敗!");
119         } catch (BadPaddingException e) {
120             _log.error("獲取加密數據的位元組數組失敗!");
121         }
122         
123         return null;
124     }
125     
126     /**
127      * 以二進位字元串數據進行解密
128      * 
129      * @param  content
130      * @param  enCodeFormat
131      * @return  String
132      * @author panjianghong 2016-8-29
133      * */
134     
135     public static String decryptBin(String binContent, String key){
136         
137         try {
138             SecretKeySpec secretyKey = new SecretKeySpec(getEnCodeFormat(key), algorithm);
139             Cipher cipher = Cipher.getInstance(transformation);
140             cipher.init(Cipher.DECRYPT_MODE, secretyKey);
141             byte[] byteResoult = cipher.doFinal(binString2Byte(binContent));
142             try {
143                 return new String(byteResoult,"utf-8");
144             } catch (UnsupportedEncodingException e) {
145                 _log.error("解密二進位數據失敗!");
146                 return null;
147             }
148         } catch (InvalidKeyException e) {
149             _log.error("解密二進位數據失敗!");
150         } catch (NoSuchAlgorithmException e) {
151             _log.error("解密二進位數據失敗!");
152         } catch (NoSuchPaddingException e) {
153             _log.error("解密二進位數據失敗!");
154         } catch (IllegalBlockSizeException e) {
155             _log.error("解密二進位數據失敗!");
156         } catch (BadPaddingException e) {
157             _log.error("解密二進位數據失敗!");
158         }
159         
160         return null;
161     }
162     
163     /**
164      * 以十六進位字元串數據進行解密
165      * 
166      * @param  content
167      * @param  enCodeFormat
168      * @return  String
169      * @author panjianghong 2016-8-29
170      * */
171     public static String decryptHex(String binContent, String key){
172         
173         try {
174             SecretKeySpec secretyKey = new SecretKeySpec(getEnCodeFormat(key), algorithm);
175             Cipher cipher = Cipher.getInstance(transformation);
176             cipher.init(Cipher.DECRYPT_MODE, secretyKey);
177             byte[] byteResoult = cipher.doFinal(hexString2Byte(binContent));
178             try {
179                 return new String(byteResoult,"utf-8");
180             } catch (UnsupportedEncodingException e) {
181                 _log.error("解密十六進位數據失敗!");
182                 return null;
183             }
184         } catch (InvalidKeyException e) {
185             _log.error("解密十六進位數據失敗!");
186         } catch (NoSuchAlgorithmException e) {
187             _log.error("解密十六進位數據失敗!");
188         } catch (NoSuchPaddingException e) {
189             _log.error("解密十六進位數據失敗!");
190         } catch (IllegalBlockSizeException e) {
191             _log.error("解密十六進位數據失敗!");
192         } catch (BadPaddingException e) {
193             _log.error("解密十六進位數據失敗!");
194         }
195         
196         return null;
197     }
198     
199     
200     
201     
202     /**
203      * 位元組數組轉化成二進位數
204      * @param  content
205      * @return  string
206      * @author panjianghong 2016-8-29
207      * */
208     private static String byte2BinString(byte[] content){
209         if(null == content){
210             _log.error("需要轉換的參數為空!");
211             return null;
212         }
213         
214         return hexString2BinString(byte2HexString(content));
215     }    
216     
217     /**
218      * 位元組數組轉化成十六進位數的小寫形式
219      * @param  content
220      * @return  string
221      * @author panjianghong 2016-8-29
222      * */
223     private static String byte2HexString(byte[] content){
224         if(null == content){
225             _log.error("需要轉換的參數為空!");
226             return null;
227         }
228         
229         StringBuffer sb = new StringBuffer();
230         for (int i = 0; i < content.length; i++) {
231             String hex = Integer.toHexString(content[i] & 0xFF); 
232             if (hex.length() == 1) {
233                 hex = '0' + hex;
234             }
235             sb.append(hex.toLowerCase());
236         }
237         
238         return sb.toString();
239     }
240     
241     /**
242      * 十六進位數轉化成二進位數
243      * @param  content
244      * @return string
245      * @author panjianghong 2016-8-29
246      * */
247     private static String hexString2BinString(String content){
248         
249         if (null == content || content.length() % 2 != 0) {
250             _log.error("需要轉換的參數為空或者參數長度不是2的倍數!");
251             return null; 
252         }
253              
254         StringBuffer bString = new StringBuffer();
255         StringBuffer tmp = new StringBuffer();  
256         for (int i = 0; i < content.length(); i++)  
257         {  
258             tmp.append("0000").append(Integer.toBinaryString(Integer.parseInt(content.substring(i, i + 1), 16)));  
259             bString.append(tmp.toString().substring(tmp.toString().length() - 4));  
260             tmp.delete(0, tmp.toString().length());
261         }  
262         return bString.toString(); 
263     }
264     /**
265      * 二進位數轉化成十六進位數
266      * @param  content
267      * @return string
268      * @author panjianghong 2016-8-29
269      * */
270     private static String BinString2hexString(String content){
271         
272         if (null == content || content.equals("") || content.length() % 8 != 0){
273             _log.error("需要轉換的參數為空或者參數長度不是8的倍數!");
274             return null;  
275         }
276             
277         StringBuffer tmp = new StringBuffer();  
278         int iTmp = 0;  
279         for (int i = 0; i < content.length(); i += 4)  
280         {  
281             iTmp = 0;  
282             for (int j = 0; j < 4; j++)  
283             {  
284                 iTmp += Integer.parseInt(content.substring(i + j, i + j + 1)) << (4 - j - 1);  
285             }  
286             tmp.append(Integer.toHexString(iTmp));  
287         }  
288         return tmp.toString();   
289     }
290         
291     
292     /**
293      * 16進位數轉化成位元組數組
294      * @param  content
295      * @return string
296      * @author panjianghong 2016-8-29
297      * */
298     private static byte[] hexString2Byte(String content){
299          if (content.length() < 1){
300              _log.error("需要轉換的參數為空或者參數長度<1!");
301              return null;
302          }
303                 
304         byte[] byteRresult = new byte[content.length() / 2];
305         for (int i = 0; i < content.length() / 2; i++) {
306             int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
307             int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
308             byteRresult[i] = (byte) (high * 16 + low);
309         }
310         return byteRresult;
311     }
312     
313     /**
314      * 二進位數轉化成位元組數組
315      * @param  content
316      * @return string
317      * @author panjianghong 2016-8-29
318      * */
319     private static byte[] binString2Byte(String content){
320          if (content.length() < 1){
321              _log.error("需要轉換的參數為空或者參數長度<1!");
322              return null;
323          }
324                 
325         return hexString2Byte(BinString2hexString(content));
326     }
327     
328 }

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 不啰嗦上代碼: 怎麼調用不用我說了吧,看返回的4個方法: addTranEvent,addAnimEvent,removeAnimEvent,setStyleAttribute ...
  • 第二版 (-1)寫在前面 本文不是要詳細說明Validation插件的使用,而是將滿足開發需求的代碼已最應該使用的方式寫出來,並附有詳細的註釋 想要瞭解更多,去jquery的官網,有最新,最全面的,後續可能會寫怎麼從jquery官網獲得信息的博文 (0)資源配置 官網的jar包: lib 有該插件所 ...
  • 如何簡單相容性的實現父元素是半透明背景色,而子元素不受影響。 相容所有瀏覽器的背景顏色半透明CSS代碼: 註意:startColorStr 和 endColorStr 的值,前兩位是十六進位的透明度,後面六位是十六進位的顏色。 其格式為 #AARRGGBB 。 AA 、 RR 、 GG 、 BB 為 ...
  • 工具: Visual Studio 2015 update 3 Asp.Net Core 1.0 1 準備工作 申請微信公眾平臺介面測試帳號,申請網址:(http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login)。申請介面測試號無需公 ...
  • 在 UWP 的開發過程中,我們可能需要提供多種交互方式,例如滑鼠、鍵盤、觸摸、游戲手柄等,當然,語音也是一項很重要的功能。 眾所周知,在 Windows 中的許多個版本都包含有語音功能,特別是在 Windows 10 上,Cortana(小娜)更是非常智能。同時,對於開發者而言,我們也能非常方便的在 ...
  • 為什麼現在有非常多的聰明人都在致力於互聯網? 最近在讀埃隆·馬斯克傳記,他說「我認為現在有非常多的聰明人都在致力於互聯網」。 仔細一想,好像真的是這樣的。 我問了自己一個問題:如果你不敲代碼了,你能做什麼? 答案令人極其恐怖。嚇得我趕緊又去寫了一句 system.out.print("Hello W ...
  • python phpbb3 2016年8月30日 04:50:48 codegay phpbb3是國外一個開源的PHP論壇,python phpbb3這個項目是用python3實現很多對phpbb3論壇操作的方法,比如登錄,發貼,刪貼之類的操作。 從時間上看作者是4年前寫的項目,不過從代碼上看貌似大 ...
  • 接上一節課,我們專門新建了一個godconfig類,設置了兩個屬性prj_name(項目名),prj_author(作者),然後我們獲取標準輸入(stdin)把結果保存在了類裡面。 好吧,這節課的名字比較奇葩-我得了”懶癌”,假如我們忘記寫godconfig類的屬性,我們的程式還會運行嗎?答案是依舊 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...