-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathAESUtils.java
406 lines (374 loc) · 12.2 KB
/
AESUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
package com.example.user.utils.string;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* <p>
* AES加密解密工具包
* </p>
*
* @author IceWee
* @version 1.0
* @date 2012-5-18
*/
public class AESUtils {
private static final String ALGORITHM = "AES";
private static final int KEY_SIZE = 256;
private static final int CACHE_SIZE = 1024;
/**
* <p>
* 生成随机密钥
* </p>
*
* @return
* @throws Exception
*/
public static String getSecretKey() throws Exception {
return getSecretKey(null);
}
/**
* <p>
* 生成密钥
* </p>
*
* @param seed 密钥种子
* @return
* @throws Exception
*/
public static String getSecretKey(String seed) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
SecureRandom secureRandom;
if (seed != null && !"".equals(seed)) {
secureRandom = new SecureRandom(seed.getBytes());
} else {
secureRandom = new SecureRandom();
}
keyGenerator.init(KEY_SIZE, secureRandom);
SecretKey secretKey = keyGenerator.generateKey();
return seed;
}
// /**
// * <p>
// * 加密
// * </p>
// *
// * @param data
// * @param key
// * @return
// * @throws Exception
// */
// public static byte[] encrypt(byte[] data, String key) throws Exception {
// Key k = toKey(Base64Utils.decode(key));
// byte[] raw = k.getEncoded();
// SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
// Cipher cipher = Cipher.getInstance(ALGORITHM);
// cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
// return cipher.doFinal(data);
// }
/**
* <p>
* 文件加密
* </p>
*
* @param key
* @param sourceFilePath
* @param destFilePath
* @throws Exception
*/
public static void encryptFile(String key, String sourceFilePath, String destFilePath, String fileDir) throws Exception {
File sourceFile = new File(sourceFilePath);
File destFile = new File(fileDir);
if (sourceFile.exists() && sourceFile.isFile()) {
// if (!destFile.getParentFile().exists()) {
// destFile.getParentFile().mkdirs();
// }
// destFile.createNewFile();
if (!destFile.exists()) {
destFile.mkdirs();
}
File file = new File(destFilePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(file);
Key k = toKey(key.getBytes());
byte[] raw = k.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
CipherInputStream cin = new CipherInputStream(in, cipher);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = cin.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
cin.close();
in.close();
}
}
/**
* AES加密字符串
*
* @param content 需要被加密的字符串
* @return 密文
*/
public static String encryptText(String key, String content) {
try {
Key k = toKey(key.getBytes());
byte[] raw = k.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] result = cipher.doFinal(byteContent);// 加密
return Base64.encodeToString(result, Base64.DEFAULT);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* <p>
* 文本解密
* </p>
*
* @param key
* @param
* @param
* @throws Exception
*/
public static String decryptText(String key, String content) throws Exception {
try {
Key k = toKey(key.getBytes());
byte[] raw = k.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] result = cipher.doFinal(Base64.decode(content, Base64.DEFAULT));
return new String(result, "utf-8"); // 明文
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return "";
}
// /**
// * <p>
// * 解密
// * </p>
// *
// * @param data
// * @param key
// * @return
// * @throws Exception
// */
// public static byte[] decrypt(byte[] data, String key) throws Exception {
// Key k = toKey(Base64Utils.decode(key));
// byte[] raw = k.getEncoded();
// SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
// Cipher cipher = Cipher.getInstance(ALGORITHM);
// cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
// return cipher.doFinal(data);
// }
/**
* <p>
* 文件解密
* </p>
*
* @param key
* @param sourceFilePath
* @param destFilePath
* @throws Exception
*/
public static void decryptFile(String key, String sourceFilePath, String destFilePath) throws Exception {
File sourceFile = new File(sourceFilePath);
File destFile = new File(destFilePath);
if (sourceFile.exists() && sourceFile.isFile()) {
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
FileInputStream in = new FileInputStream(sourceFile);
FileOutputStream out = new FileOutputStream(destFile);
Key k = toKey(key.getBytes());
byte[] raw = k.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
CipherOutputStream cout = new CipherOutputStream(out, cipher);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
cout.write(cache, 0, nRead);
cout.flush();
}
cout.close();
out.close();
in.close();
}
}
/**
* <p>
* 转换密钥
* </p>
*
* @param key
* @return
* @throws Exception
*/
private static Key toKey(byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
return secretKey;
}
/*
*bitmap转base64
*/
public static String bitmapToBase64(Bitmap bitmap) {
String result = "";
ByteArrayOutputStream bos = null;
try {
if (null != bitmap) {
bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);//将bitmap放入字节数组流中
bos.flush();//将bos流缓存在内存中的数据全部输出,清空缓存
bos.close();
byte[] bitmapByte = bos.toByteArray();
result = Base64.encodeToString(bitmapByte, Base64.DEFAULT);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/*
*base64转bitmap
*/
public static Bitmap base64ToBitmap(String base64String) {
byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bitmap;
}
// 将文件转为String
public static String fileToString(String path) throws Exception {
File file = new File(path);
InputStream inStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
String s = new String(Base64.encode(data, Base64.DEFAULT));
outStream.close();
inStream.close();
return s;
}
// 把string转成文件
public static File stringToFile(String res, String fileType, String tempPath) throws Exception {
byte[] data = Base64.decode(res, Base64.DEFAULT);
// String dir = EaseConstant.DIR_ENCRPT_IMAGE+"mini/";
// File dirFile = new File(dir);
// if (!dirFile.exists()) {
// dirFile.mkdirs();
// }
File distFile = new File(tempPath);
distFile = byteToFile(data, distFile.getAbsolutePath());
return distFile;
}
//将byte写入文件
public static File byteToFile(byte[] buf, String filePath) throws Exception {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(buf);
if (bos != null) {
bos.close();
}
if (fos != null) {
fos.close();
}
return file;
}
/**
* 保存文件
*
* @param bm
* @param fileName
* @throws IOException
*/
public static File bitmapToFile(Bitmap bm, String path, String fileName) throws IOException {
File dirFile = new File(path);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
File myCaptureFile = new File(path + fileName);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
return myCaptureFile;
}
}