Skip to content

Commit abb7c1a

Browse files
committed
增加加密解密相关工具类
1 parent eb1930e commit abb7c1a

10 files changed

Lines changed: 978 additions & 138 deletions

File tree

Util-Demo/.idea/libraries/Maven__commons_codec_commons_codec_1_10.xml

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Util-Demo/.idea/libraries/Maven__org_bouncycastle_bcprov_jdk15on_1_52.xml

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Util-Demo/.idea/workspace.xml

Lines changed: 345 additions & 137 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Util-Demo/Util-Demo.iml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,13 @@
1212
</content>
1313
<orderEntry type="inheritedJdk" />
1414
<orderEntry type="sourceFolder" forTests="false" />
15+
<orderEntry type="library" name="Maven: org.bouncycastle:bcprov-jdk15on:1.52" level="project" />
16+
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.10" level="project" />
1517
<orderEntry type="library" name="Maven: dom4j:dom4j:1.6.1" level="project" />
1618
<orderEntry type="library" name="Maven: xml-apis:xml-apis:1.0.b2" level="project" />
1719
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpclient:4.5.2" level="project" />
1820
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.4.4" level="project" />
1921
<orderEntry type="library" name="Maven: commons-logging:commons-logging:1.2" level="project" />
20-
<orderEntry type="library" name="Maven: commons-codec:commons-codec:1.9" level="project" />
2122
<orderEntry type="library" name="Maven: redis.clients:jedis:2.8.0" level="project" />
2223
<orderEntry type="library" name="Maven: org.apache.commons:commons-pool2:2.3" level="project" />
2324
<orderEntry type="library" name="Maven: junit:junit:4.12" level="project" />

Util-Demo/pom.xml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,18 @@
99
<version>1.0-SNAPSHOT</version>
1010

1111
<dependencies>
12+
<!--RSA依赖-->
13+
<dependency>
14+
<groupId>org.bouncycastle</groupId>
15+
<artifactId>bcprov-jdk15on</artifactId>
16+
<version>1.52</version>
17+
</dependency>
18+
<!--加密解密依赖-->
19+
<dependency>
20+
<groupId>commons-codec</groupId>
21+
<artifactId>commons-codec</artifactId>
22+
<version>1.10</version>
23+
</dependency>
1224
<!--xmlUtil依赖-->
1325
<dependency>
1426
<groupId>dom4j</groupId>
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
package cn.mrdear.util.SecurityUtil;
2+
3+
4+
import org.apache.commons.codec.binary.Base64;
5+
6+
import java.security.SecureRandom;
7+
8+
import javax.crypto.Cipher;
9+
import javax.crypto.KeyGenerator;
10+
import javax.crypto.spec.SecretKeySpec;
11+
12+
/**
13+
* AES工具类
14+
* 使用base64AndaesEncrypt加密
15+
* 使用base64AndaesDecrypt解密
16+
*/
17+
public class AESUtil {
18+
19+
/**
20+
* 测试方法
21+
* @param args
22+
* @throws Exception 抛出异常
23+
*/
24+
public static void main(String[] args) throws Exception {
25+
String str = "niuli111";
26+
String encry = base64AndEncrypt(str,"niuli");
27+
System.out.println(encry);
28+
System.out.println(base64AndDecrypt(encry,"niuli"));
29+
}
30+
/**
31+
* AES加密
32+
*
33+
* @param content
34+
* 待加密的内容
35+
* @param encryptKey
36+
* 加密密钥
37+
* @return 加密后的byte[]
38+
*/
39+
public static byte[] EncryptToBytes(String content, String encryptKey) {
40+
return EncryptToBytes(content.getBytes(),encryptKey);
41+
}
42+
43+
/**
44+
* AES加密
45+
*
46+
* @param encryptContent
47+
* 待加密的内容
48+
* @param encryptKey
49+
* 加密密钥
50+
* @return 加密后的byte[]
51+
*/
52+
public static byte[] EncryptToBytes(byte[] encryptContent, String encryptKey){
53+
try {
54+
return aesByMode(encryptContent,encryptKey, Cipher.ENCRYPT_MODE);
55+
} catch (Exception e) {
56+
e.printStackTrace();
57+
}
58+
return null;
59+
}
60+
61+
/**
62+
* AES加密为base 64 code
63+
*
64+
* @param content
65+
* 待加密的内容
66+
* @param encryptKey
67+
* 加密密钥
68+
* @return 加密后的base 64 code
69+
*/
70+
public static String base64AndEncrypt(String content, String encryptKey){
71+
return Base64.encodeBase64URLSafeString(EncryptToBytes(content, encryptKey));
72+
}
73+
/**
74+
* AES解密
75+
*
76+
* @param encryptBytes
77+
* 待解密的byte[]
78+
* @param decryptKey
79+
* 解密密钥
80+
* @return 解密后的String
81+
*/
82+
public static String DecryptByBytes(byte[] encryptBytes, String decryptKey){
83+
try {
84+
byte[] decryptBytes = aesByMode(encryptBytes,decryptKey,Cipher.DECRYPT_MODE);
85+
return new String(decryptBytes, "UTF-8");
86+
} catch (Exception e) {
87+
e.printStackTrace();
88+
}
89+
return null;
90+
}
91+
92+
/**
93+
* 根据mode选择解密或者加密
94+
* @param content 要操作的内容
95+
* @param key 密钥
96+
* @param MODE 选择模型 Cipher里面的常量
97+
* @return 操作后的串
98+
*/
99+
private static byte[] aesByMode(byte[] content, String key,Integer MODE) throws Exception {
100+
KeyGenerator kgen = KeyGenerator.getInstance("AES");
101+
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
102+
secureRandom.setSeed(key.getBytes());
103+
//生成128位的key
104+
kgen.init(128, secureRandom);
105+
Cipher cipher = Cipher.getInstance("AES");
106+
cipher.init(MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
107+
return cipher.doFinal(content);
108+
}
109+
110+
/**
111+
* AES解密
112+
* @param normalStr 带解密的串
113+
* @param decryptKey 密钥
114+
* @return 解密后的string
115+
*/
116+
public static String DecryptByStr(String normalStr, String decryptKey){
117+
return (normalStr==null || "".equals(normalStr)) ? null : DecryptByBytes(normalStr.getBytes(), decryptKey);
118+
}
119+
120+
/**
121+
* 将base 64 code AES解密
122+
*
123+
* @param encryptStr
124+
* 待解密的base 64 code
125+
* @param decryptKey
126+
* 解密密钥
127+
* @return 解密后的string
128+
*/
129+
public static String base64AndDecrypt(String encryptStr, String decryptKey){
130+
return (encryptStr==null || "".equals(encryptStr)) ? null : DecryptByBytes(Base64.decodeBase64(encryptStr), decryptKey);
131+
}
132+
133+
134+
}
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
package cn.mrdear.util.SecurityUtil;
2+
3+
import org.apache.commons.codec.binary.Hex;
4+
import org.apache.commons.codec.digest.DigestUtils;
5+
import org.slf4j.Logger;
6+
import org.slf4j.LoggerFactory;
7+
8+
import java.security.MessageDigest;
9+
import java.security.NoSuchAlgorithmException;
10+
import java.security.SecureRandom;
11+
12+
/**
13+
* 摘要签名工具类
14+
*/
15+
public class DigestUtil {
16+
17+
private static final Logger logger = LoggerFactory.getLogger(DigestUtil.class);
18+
19+
private static final String SHA1_PRNG = "SHA1PRNG";
20+
21+
private static SecureRandom sRandom;
22+
23+
public enum SecurityEnum {
24+
MD5("MD5"), SHA256("SHA-256"), SHA512("SHA-512"), SHA384("SHA-384"), SHA1("SHA-1"), SHA("SHA");
25+
26+
SecurityEnum(String value) {
27+
this.value = value;
28+
}
29+
private String value;
30+
public String getValue() {
31+
return value;
32+
}
33+
}
34+
35+
36+
static {
37+
try {
38+
sRandom = SecureRandom.getInstance(SHA1_PRNG);
39+
} catch (NoSuchAlgorithmException e) {
40+
logger.error("生成安全随机数失败:", e);
41+
}
42+
}
43+
44+
/**
45+
* 生成指定bit的安全随机数
46+
* @param bits bit位
47+
* @return 生成结果
48+
*/
49+
private static byte[] getNextSecureRandom(int bits) {
50+
if ((bits % 8) != 0) {
51+
throw new IllegalArgumentException("Size is not divisible by 8!");
52+
}
53+
final byte[] bytes = new byte[bits / 8];
54+
sRandom.nextBytes(bytes);
55+
return bytes;
56+
}
57+
58+
/**
59+
* 随机生成指定位数字串
60+
* @return 生成字串
61+
*/
62+
public static String getNextHexRandomNum(int bits) {
63+
return Hex.encodeHexString(getNextSecureRandom(bits*8));
64+
}
65+
66+
/**
67+
* 根据算法得到相应摘要
68+
* @param instance 算法
69+
* @param bytes 需要摘要的内容
70+
* @return 摘要
71+
*/
72+
public static String digest(SecurityEnum instance, byte[] bytes) {
73+
MessageDigest digestUtils = getInstance(instance);
74+
digestUtils.update(bytes);
75+
return byte2String(digestUtils.digest());
76+
}
77+
78+
/**
79+
* 根据算法得到相应摘要
80+
* @param instance 算法
81+
* @param content 需要摘要的内容
82+
* @return 摘要
83+
*/
84+
public static String digest(SecurityEnum instance, String content) {
85+
if (content == null) return "";
86+
return digest(instance,content.getBytes());
87+
}
88+
89+
/**
90+
* 根据算法拿到一个实现者
91+
* @param securityEnum 算法
92+
* @return 实例
93+
*/
94+
private static MessageDigest getInstance(SecurityEnum securityEnum){
95+
MessageDigest digestUtils = null;
96+
try {
97+
digestUtils = MessageDigest.getInstance(securityEnum.getValue());
98+
} catch (NoSuchAlgorithmException e) {
99+
e.printStackTrace();
100+
logger.error("不存在的加密算法");
101+
digestUtils = DigestUtils.getDigest(securityEnum.getValue());
102+
}
103+
return digestUtils;
104+
}
105+
106+
/**
107+
* 加密后的内容转成String
108+
* @param content 内容
109+
* @return 字符串
110+
*/
111+
private static String byte2String(byte[] content){
112+
StringBuilder hexString = new StringBuilder();
113+
// 字节数组转换为 十六进制 数
114+
for (int i = 0; i < content.length; i++) {
115+
String shaHex = Integer.toHexString(content[i] & 0xFF);
116+
if (shaHex.length() < 2) {
117+
hexString.append(0);
118+
}
119+
hexString.append(shaHex);
120+
}
121+
return hexString.toString();
122+
}
123+
}

0 commit comments

Comments
 (0)