ViontechAESUtil.java
2.5 KB
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
package com.viontech.domain;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
public class ViontechAESUtil {
//实例化密钥
private static Key key;
//原始密钥
private static String KEY_STR = "273D470C41CD8C3F766C94E245228C910DB1CB75";
//编码
private static String CHARSETNAME = "UTF-8";
//密钥算法
private static String KEY_ALGORITHM = "AES";
//加密-解密算法 / 工作模式 / 填充方式
private static String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
/**
* 初始化key
*/
static {
try {
KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(KEY_STR.getBytes());
kgen.init(128, random);
key = kgen.generateKey();
kgen = null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @description: AES对称加密字符串,并通过Jdk自带Base64转换为ASCII
* @author: Administrator
* @date: 2017年11月7日 上午9:37:48
* @param str
* @return
*/
public static String getEncryptString(String str) {
try {
byte[] bytes = str.getBytes(CHARSETNAME);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] doFinal = cipher.doFinal(bytes);
return Base64.getEncoder().encodeToString(doFinal);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @description: 对AES加密字符串进行解密
* @author: maojialong
* @date: 2017年11月7日 上午10:14:00
* @param str
* @return
*/
public static String getDecryptString(String str) {
try {
byte[] bytes = Base64.getDecoder().decode(str);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] doFinal = cipher.doFinal(bytes);
return new String(doFinal, CHARSETNAME);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] rgs){
System.out.println(ViontechAESUtil.getEncryptString("postgres"));
System.out.println(ViontechAESUtil.getDecryptString("C1kjGLXX23wckTPm6hmU5Q=="));
}
}