· 7 years ago · Aug 28, 2018, 10:12 AM
1package org.rsa.encry;
2
3
4import java.security.InvalidKeyException;
5import java.util.ArrayList;
6import java.util.List;
7import java.util.Scanner;
8import javax.crypto.*;
9import javax.crypto.spec.*;
10import java.io.*;
11
12/**
13 * <p>æ ‡é¢˜: AESUtil</p>
14 * <p>æè¿°: AESåŠ å¯†å·¥å…·ç±» 实现对å—符串(String)æˆ–æ–‡ä»¶çš„åŠ å¯†ä¸Žè§£å¯† 支æŒ128ã€192ã€256ä½å¯†åŒ™</p>
15 * <p>附: è‹¥è¦ä½¿ç”¨192ã€256ä½å¯†åŒ™ 需è¦åˆ°Sun下载jce_policy-6.zip 并解压安装</p>
16 *
17 * @author juapk.com
18 * @version 1.0
19 */
20public class AESTool {
21 //密匙
22 private byte[] key;
23
24 //åŠ å¯†çš„å¯†åŒ™ä½æ•°(默认256ä½AESåŠ å¯†)
25 private int keySize = 256;
26
27 //å¾…åŠ å¯†æºæ–‡ä»¶
28 private String srcFile;
29
30 //åŠ å¯†åŽçš„æ–‡ä»¶
31 private String desFile;
32
33 //è°ƒæ•™åŽæ€§ä»·æ¯”很好的缓冲区大å°(最好ä¸è¦æ”¹åЍ)
34 //private int blockSize = 61440;
35 private int blockSize = 1024;
36
37 private int mode;
38
39 //æœ‰æ•ˆå¯†åŒ™ä½æ•°é›†åˆ
40 private static List<Integer> KEYSIZELIST = new ArrayList<Integer>();
41
42 static {
43 //åˆå§‹åŒ–æœ‰æ•ˆå¯†åŒ™ä½æ•°
44 KEYSIZELIST.add(128);
45 KEYSIZELIST.add(192);
46 KEYSIZELIST.add(256);
47 }
48
49 /**
50 * æž„é€ æ–¹æ³•
51 */
52 public AESTool(String srcFile, String desFile, byte[] key) {
53 this.srcFile = srcFile;
54 this.desFile = desFile;
55 this.key = key;
56 }
57
58 /**
59 * ç±»å…¥å£æ–¹æ³•ï¼ŒåŒ…å«æ–‡ä»¶åŠå—ç¬¦ä¸²åŠ è§£å¯†è°ƒç”¨ç¤ºä¾‹
60 *
61 * @param args
62 * @return void
63 */
64 public static void main(String[] args) throws Exception {
65 System.out.println("*******************************************");
66 System.out.println("***************AESåŠ å¯†å·¥å…·*******************");
67 System.out.println("*********æ“作指令:1åŠ å¯† 2解密 3退出**********");
68 System.out.println("*******************************************");
69 Scanner sc = new Scanner(System.in);
70 String commond = null;
71
72 do {
73 System.out.println("请输入æ“作指令:");
74 if (sc.hasNext()) {
75 commond = sc.nextLine();
76 }
77 } while (!"1".equals(commond) && !"2".equals(commond) && !"3".equals(commond));
78
79 if ("1".equals(commond)) {
80 System.out.println("请输入原始文件路径(如:c:/a.rar)");
81
82 String srcFile = null;
83 if (sc.hasNext()) {
84 srcFile = sc.nextLine();
85 }
86
87 System.out.println("è¯·è¾“å…¥åŠ å¯†æ–‡ä»¶å˜æ”¾è·¯å¾„(如:c:/b.uumap");
88 String desFile = null;
89 if (sc.hasNext()) {
90 desFile = sc.nextLine();
91 }
92
93 System.out.println("请输入32ä½å¯†åŒ™(å¯ç”±å—æ¯ã€æ•°å—ã€è‹±æ–‡ç‰¹æ®Šå—符组æˆ):");
94 String key = null;
95 if (sc.hasNext()) {
96 key = sc.nextLine();
97 }
98
99 sc.close();
100
101 AESTool aesUtil = new AESTool(srcFile, desFile, key.getBytes());
102
103 aesUtil.encode();//æ–‡ä»¶åŠ å¯†
104 } else if ("2".equals(commond)) {
105 System.out.println("è¯·è¾“å…¥åŠ å¯†æ–‡ä»¶å˜æ”¾è·¯å¾„(如:c:/b.uumap");
106
107 String desFile = null;
108 if (sc.hasNext()) {
109 desFile = sc.nextLine();
110 }
111
112 System.out.println("è¯·è¾“å…¥è§£å¯†åŽæ–‡ä»¶å˜æ”¾è·¯å¾„(如:c:/c.rar");
113 String decodeFile = null;
114 if (sc.hasNext()) {
115 decodeFile = sc.nextLine();
116 }
117
118 System.out.println("请输入32ä½å¯†åŒ™(å¯ç”±å—æ¯ã€æ•°å—ã€è‹±æ–‡ç‰¹æ®Šå—符组æˆ):");
119 String key = null;
120 if (sc.hasNext()) {
121 key = sc.nextLine();
122 }
123
124 sc.close();
125
126 AESTool aesUtil = new AESTool(desFile, decodeFile, key.getBytes());
127
128 //æ–‡ä»¶åŠ å¯†è§£å¯†ç¤ºä¾‹
129 aesUtil.decode();//文件解密*/
130 } else if ("3".equals(commond)) {
131 System.out.println("******************退出**********************");
132 System.exit(0);
133 }
134 }
135
136 /**
137 * æ–‡ä»¶åŠ å¯†æ–¹æ³•
138 *
139 * @return void
140 * @throws Exception
141 */
142 public void encode() throws Exception {
143
144 //æ ¡éªŒå¹¶åˆ›å»ºæ–‡ä»¶ç›®å½•
145 validateFile(this.desFile);
146
147 //获å–éšæœºå¯†åŒ™
148 byte[] raw = this.key;
149
150 //åˆå§‹åŒ–SecretKeySpec对象
151 SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
152
153 //åˆå§‹åŒ–Cipher对象
154 Cipher cipher = Cipher.getInstance("AES");
155
156 //用指定密匙对象åˆå§‹åŒ–åŠ å¯†Cipher对象
157 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
158
159 //åŠ å¯†æ–‡ä»¶
160 encodeFile(cipher);
161 }
162
163 /**
164 * 文件解密方法
165 *
166 * @return void
167 * @throws Exception
168 */
169 public void decode() throws Exception {
170 //æ ¡éªŒå¹¶åˆ›å»ºæ–‡ä»¶ç›®å½•
171 validateFile(this.srcFile);
172
173 //åˆå§‹åŒ–SecretKeySpec对象
174 SecretKeySpec skeySpec = new SecretKeySpec(this.key, "AES");
175
176 //åˆå§‹åŒ–Cipher对象
177 Cipher cipher = Cipher.getInstance("AES");
178
179 //用指定密匙对象åˆå§‹åŒ–åŠ å¯†Cipher对象
180 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
181
182 //解密文件
183 decodeFile(cipher, skeySpec);
184 }
185
186
187 /**
188 * 文件解密方法
189 *
190 * @return void
191 * @throws Exception
192 */
193 public byte[] decodeToBytes() throws Exception {
194 //åˆå§‹åŒ–SecretKeySpec对象
195 SecretKeySpec skeySpec = new SecretKeySpec(this.key, "AES");
196
197 //åˆå§‹åŒ–Cipher对象
198 Cipher cipher = Cipher.getInstance("AES");
199
200 //用指定密匙对象åˆå§‹åŒ–åŠ å¯†Cipher对象
201 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
202
203 //解密文件
204 return decodeFileToBytes(cipher, skeySpec);
205 }
206
207 /**
208 * å—ç¬¦ä¸²åŠ å¯†æ–¹æ³•
209 *
210 * @return void
211 * @throws Exception
212 */
213 public byte[] encodeStr(String str, int keySize) throws Exception {
214
215 if (!validate(str, keySize)) {
216 System.out.println("å—ç¬¦ä¸²åŠ å¯†å‚æ•°æ ¡éªŒå¤±è´¥");
217 return null;
218 }
219
220 //获å–KeyGenerator对象
221 KeyGenerator kgen = KeyGenerator.getInstance("AES");
222
223 //è®¾ç½®åŠ å¯†å¯†åŒ™ä½æ•°ï¼Œç›®å‰æ”¯æŒ128ã€192ã€256ä½
224 kgen.init(keySize);
225
226 //获å–密匙对象
227 SecretKey skey = kgen.generateKey();
228
229 //获å–éšæœºå¯†åŒ™
230 byte[] raw = skey.getEncoded();
231
232 //åˆå§‹åŒ–SecretKeySpec对象
233 SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
234
235 //åˆå§‹åŒ–Cipher对象
236 Cipher cipher = Cipher.getInstance("AES");
237
238 //用指定密匙对象åˆå§‹åŒ–åŠ å¯†Cipher对象
239 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
240
241 //åŠ å¯†å—符串
242 return cipher.doFinal(str.getBytes("utf-8"));
243 }
244
245 /**
246 * å—符串解密方法
247 *
248 * @return void
249 * @throws Exception
250 */
251 public String decodeStr(byte[] date) throws Exception {
252
253 if (null == date || date.length % 16 != 0) {
254 System.out.println("å—ç¬¦ä¸²è§£å¯†å‚æ•°æ ¡éªŒå¤±è´¥");
255 return null;
256 }
257
258 //åˆå§‹åŒ–SecretKeySpec对象
259 SecretKeySpec skeySpec = new SecretKeySpec(this.key, "AES");
260
261 //åˆå§‹åŒ–Cipher对象
262 Cipher cipher = Cipher.getInstance("AES");
263
264 //用指定密匙对象åˆå§‹åŒ–åŠ å¯†Cipher对象
265 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
266
267 //解密å—符串
268 byte[] decData = cipher.doFinal(date);
269
270 return new String(decData, "utf-8");
271 }
272
273 /**
274 * æ–‡ä»¶åŠ å¯†å…·ä½“é€»è¾‘å®žçŽ°æ–¹æ³•
275 *
276 * @param cipher
277 * @return void
278 */
279 public void encodeFile(Cipher cipher) {
280
281 System.out.println("**********å¯åŠ¨åŠ å¯†************");
282
283 try {
284 FileInputStream brafReadFile;
285 FileOutputStream brafWriteFile;
286 brafReadFile = new FileInputStream(this.srcFile);
287 brafWriteFile = new FileOutputStream(this.desFile);
288
289 byte buf[] = new byte[this.blockSize];
290
291 while (brafReadFile.read(buf) != -1) {
292 brafWriteFile.write(cipher.doFinal(buf));
293 }
294
295
296 brafWriteFile.close();
297 brafReadFile.close();
298 System.out.println("**********åŠ å¯†å®Œæˆ************");
299 } catch (IllegalBlockSizeException | BadPaddingException | IOException e) {
300 e.printStackTrace();
301 }
302 }
303
304 /**
305 * 文件解密具体逻辑实现方法
306 *
307 * @param cipher
308 * @param skeySpec
309 * @return void
310 */
311 public void decodeFile(Cipher cipher, SecretKeySpec skeySpec) {
312
313 try {
314 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
315 } catch (InvalidKeyException e) {
316 e.printStackTrace();
317 }
318
319 System.out.println("**********å¯åŠ¨è§£å¯†************");
320
321 FileInputStream brafReadFile = null;
322 FileOutputStream brafWriteFile = null;
323 try {
324 brafReadFile = new FileInputStream(this.srcFile);
325 brafWriteFile = new FileOutputStream(this.desFile);
326
327 byte buf[] = new byte[this.blockSize + 16];
328
329 while (brafReadFile.read(buf) != -1) {
330 byte[] decData = cipher.doFinal(buf);
331 brafWriteFile.write(decData);
332 }
333
334 System.out.println("**********解密完æˆ************");
335 } catch (IllegalBlockSizeException | BadPaddingException | IOException e) {
336 e.printStackTrace();
337 } finally {
338 try {
339 brafWriteFile.close();
340 brafReadFile.close();
341 } catch (IOException e) {
342 e.printStackTrace();
343 }
344 }
345 }
346
347 public byte[] decodeFileToBytes(Cipher cipher, SecretKeySpec skeySpec) {
348 try {
349 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
350 } catch (InvalidKeyException e) {
351 e.printStackTrace();
352 }
353
354 System.out.println("**********å¯åŠ¨è§£å¯†************");
355
356 FileInputStream brafReadFile = null;
357 ByteArrayOutputStream brafWriteArray = null;
358 try {
359 brafReadFile = new FileInputStream(this.srcFile);
360 //brafWriteFile = new FileOutputStream(this.desFile);
361 brafWriteArray = new ByteArrayOutputStream();
362
363 byte buf[] = new byte[this.blockSize + 16];
364
365 while (brafReadFile.read(buf) != -1) {
366 byte[] decData = cipher.doFinal(buf);
367 brafWriteArray.write(decData);
368 }
369
370 System.out.println("**********解密完æˆ************");
371 } catch (IllegalBlockSizeException | BadPaddingException | IOException e) {
372 e.printStackTrace();
373 } finally {
374 try {
375 brafWriteArray.close();
376 brafReadFile.close();
377 } catch (IOException e) {
378 e.printStackTrace();
379 }
380 }
381
382 return brafWriteArray.toByteArray();
383 }
384
385 /**
386 * 傿•°æ ¡éªŒ
387 *
388 * @return boolean
389 */
390 private static boolean validate(String str, int keySize) {
391
392 if (null == str) {
393 return false;
394 }
395
396 return KEYSIZELIST.contains(keySize);
397 }
398
399 /**
400 * æ–‡ä»¶å‚æ•°æ ¡éªŒï¼Œè‹¥ä¸å˜åœ¨æ”¹æ–‡ä»¶ç›®å½•,则创建目录;若该文件å˜åœ¨åˆ™åˆ é™¤æ¤æ–‡ä»¶
401 *
402 * @return boolean
403 */
404 private static boolean validateFile(String filePath) {
405
406 if (null == filePath || "".equals(filePath)) {
407 System.out.println("æ— æ•ˆçš„æ–‡ä»¶è·¯å¾„");
408 return false;
409 }
410
411 String dir = filePath.substring(0, filePath.lastIndexOf("/") + 1);
412
413 File dirFile = new File(dir);
414
415 if (!dirFile.exists()) {
416 dirFile.mkdirs();
417 }
418
419 File file = new File(filePath);
420 if (file.exists()) {
421 file.delete();
422 }
423
424 return true;
425 }
426}