RSA加解密(JAVA)

加解密JAVA 实现

引入依赖

1
2
3
4
5
6
7
8

<dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
</dependencies>

代码

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
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class SecretUtil {
private static final Logger log = LoggerFactory.getLogger(SecretUtil.class);
private static final String SM2 = "SM2";
private static final String SM2_ALGORITHM = "EC";
private static final String RSA = "RSA";
private static final int RSA_KEY_SIZE = 2048;

private SecretUtil() {
}


/**
* 生成 rsa key
*
* @return [publicKey, privateKey]
*/
public static String[] generateRsaKey() {
return generatePairKey(RSA, RSA_KEY_SIZE, null);
}

private static String[] generatePairKey(String algorithm, int keySize, Provider provider) {
KeyPairGenerator keyPairGenerator = null;
try {
/*KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象*/
keyPairGenerator = provider == null
? KeyPairGenerator.getInstance(algorithm)
: KeyPairGenerator.getInstance(algorithm, provider);
/* 初始化密钥对生成器 */
keyPairGenerator.initialize(keySize, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
log.warn("{} 公私钥生成失败", algorithm, e);
}
/*判断是否生成成功*/
if (keyPairGenerator == null) {
/*反馈空数组*/
return new String[0];
}
/*生成秘钥*/
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
byte[] publicKeyEncoded = publicKey.getEncoded();
String publicKeyString = Base64.getEncoder().encodeToString(publicKeyEncoded);
PrivateKey privateKey = keyPair.getPrivate();
byte[] privateKeyEncoded = privateKey.getEncoded();
String privateKeyString = Base64.getEncoder().encodeToString(privateKeyEncoded);
return new String[]{publicKeyString, privateKeyString};
}


/**
* RSA 加密
*
* @param content 待加密内容
* @param key 公钥
* @return 加密后结果(Base64编码)
*/

public static String rsaEncrypt(String content, String key) {
return encryptPk(content, key, RSA, null);
}

public static String encryptPk(String content, String key, String algorithm, Provider provider) {
try {
EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(SM2.equalsIgnoreCase(algorithm) ? SM2_ALGORITHM : algorithm);
Cipher cipher = provider == null
? Cipher.getInstance(algorithm)
: Cipher.getInstance(algorithm, provider);
cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generatePublic(keySpec));
byte[] encryptStr = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptStr);
} catch (Exception e) {
log.error("{} 数据加密失败:{}", algorithm, e.getMessage(), e);
return null;
}
}

/**
* RSA 解密
*
* @param content 内容(Base64编码)
* @param key 私钥
* @return 解密后数据
*/
public static String rsaDecrypt(String content, String key) {
return decryptPk(content, key, RSA, null);
}

public static String decryptPk(String content, String key, String algorithm, Provider provider) {
try {
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(SM2.equalsIgnoreCase(algorithm) ? SM2_ALGORITHM : algorithm);
Cipher cipher = provider == null
? Cipher.getInstance(algorithm)
: Cipher.getInstance(algorithm, provider);
cipher.init(Cipher.DECRYPT_MODE, keyFactory.generatePrivate(keySpec));
byte[] decryptBytes = cipher.doFinal(Base64.getDecoder().decode(content));
return new String(decryptBytes);
} catch (Exception e) {
log.error("{} 数据解密失败:{}", algorithm, e.getMessage(), e);
return null;
}
}


}

本文地址: https://github.com/maxzhao-it/blog/post/efc116f5/