xiejun
2024-11-01 80b6cbfc9c861469146318d0b3dd5f8b8b525b8a
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
/*
 *      Copyright (c) 2018-2028, DreamLu All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: DreamLu 卢春梦 (596392912@qq.com)
 */
package org.springblade.core.tool.utils;
 
import org.springframework.lang.Nullable;
import org.springframework.util.Base64Utils;
 
import org.springblade.core.tool.tuple.KeyPair;
import javax.crypto.Cipher;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import java.util.Objects;
 
/**
 * RSA加、解密工具
 *
 * <p>
 * 1. 公钥负责加密,私钥负责解密;
 * 2. 私钥负责签名,公钥负责验证。
 * </p>
 *
 * @author L.cm
 */
public class RsaUtil {
    /**
     * 数字签名,密钥算法
     */
    public static final String RSA_ALGORITHM = "RSA";
    public static final String RSA_PADDING = "RSA/ECB/PKCS1Padding";
 
    /**
     * 获取 KeyPair
     *
     * @return KeyPair
     */
    public static KeyPair genKeyPair() {
        return genKeyPair(1024);
    }
 
    /**
     * 获取 KeyPair
     *
     * @param keySize key size
     * @return KeyPair
     */
    public static KeyPair genKeyPair(int keySize) {
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA_ALGORITHM);
            // 密钥位数
            keyPairGen.initialize(keySize);
            // 密钥对
            return new KeyPair(keyPairGen.generateKeyPair());
        } catch (NoSuchAlgorithmException e) {
            throw Exceptions.unchecked(e);
        }
    }
 
    /**
     * 生成RSA私钥
     *
     * @param modulus N特征值
     * @param exponent d特征值
     * @return {@link PrivateKey}
     */
    public static PrivateKey generatePrivateKey(String modulus, String exponent) {
        return generatePrivateKey(new BigInteger(modulus), new BigInteger(exponent));
    }
 
    /**
     * 生成RSA私钥
     *
     * @param modulus N特征值
     * @param exponent d特征值
     * @return {@link PrivateKey}
     */
    public static PrivateKey generatePrivateKey(BigInteger modulus, BigInteger exponent) {
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(modulus, exponent);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            return keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw Exceptions.unchecked(e);
        }
    }
 
    /**
     * 生成RSA公钥
     *
     * @param modulus N特征值
     * @param exponent e特征值
     * @return {@link PublicKey}
     */
    public static PublicKey generatePublicKey(String modulus, String exponent) {
        return generatePublicKey(new BigInteger(modulus), new BigInteger(exponent));
    }
 
    /**
     * 生成RSA公钥
     *
     * @param modulus N特征值
     * @param exponent e特征值
     * @return {@link PublicKey}
     */
    public static PublicKey generatePublicKey(BigInteger modulus, BigInteger exponent) {
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            return keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw Exceptions.unchecked(e);
        }
    }
 
    /**
     * 得到公钥
     *
     * @param base64PubKey 密钥字符串(经过base64编码)
     * @return PublicKey
     */
    public static PublicKey getPublicKey(String base64PubKey) {
        Objects.requireNonNull(base64PubKey, "base64 public key is null.");
        byte[] keyBytes = Base64Utils.decodeFromString(base64PubKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            return keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw Exceptions.unchecked(e);
        }
    }
 
    /**
     * 得到公钥字符串
     *
     * @param base64PubKey 密钥字符串(经过base64编码)
     * @return PublicKey String
     */
    public static String getPublicKeyToBase64(String base64PubKey) {
        PublicKey publicKey = getPublicKey(base64PubKey);
        return getKeyString(publicKey);
    }
 
    /**
     * 得到私钥
     *
     * @param base64PriKey 密钥字符串(经过base64编码)
     * @return PrivateKey
     */
    public static PrivateKey getPrivateKey(String base64PriKey) {
        Objects.requireNonNull(base64PriKey, "base64 private key is null.");
        byte[] keyBytes = Base64Utils.decodeFromString(base64PriKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            return keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw Exceptions.unchecked(e);
        }
    }
 
    /**
     * 得到密钥字符串(经过base64编码)
     *
     * @param key key
     * @return base 64 编码后的 key
     */
    public static String getKeyString(Key key) {
        return Base64Utils.encodeToString(key.getEncoded());
    }
 
    /**
     * 得到私钥 base64
     *
     * @param base64PriKey 密钥字符串(经过base64编码)
     * @return PrivateKey String
     */
    public static String getPrivateKeyToBase64(String base64PriKey) {
        PrivateKey privateKey = getPrivateKey(base64PriKey);
        return getKeyString(privateKey);
    }
 
    /**
     * 共要加密
     *
     * @param base64PublicKey base64 的公钥
     * @param data            待加密的内容
     * @return 加密后的内容
     */
    public static byte[] encrypt(String base64PublicKey, byte[] data) {
        return encrypt(getPublicKey(base64PublicKey), data);
    }
 
    /**
     * 共要加密
     *
     * @param publicKey 公钥
     * @param data      待加密的内容
     * @return 加密后的内容
     */
    public static byte[] encrypt(PublicKey publicKey, byte[] data) {
        return rsa(publicKey, data, Cipher.ENCRYPT_MODE);
    }
 
    /**
     * 私钥加密,用于 qpp 内,公钥解密
     *
     * @param base64PrivateKey base64 的私钥
     * @param data             待加密的内容
     * @return 加密后的内容
     */
    public static byte[] encryptByPrivateKey(String base64PrivateKey, byte[] data) {
        return encryptByPrivateKey(getPrivateKey(base64PrivateKey), data);
    }
 
    /**
     * 私钥加密,加密成 base64 字符串,用于 qpp 内,公钥解密
     *
     * @param base64PrivateKey base64 的私钥
     * @param data             待加密的内容
     * @return 加密后的内容
     */
    public static String encryptByPrivateKeyToBase64(String base64PrivateKey, byte[] data) {
        return Base64Util.encodeToString(encryptByPrivateKey(base64PrivateKey, data));
    }
 
    /**
     * 私钥加密,用于 qpp 内,公钥解密
     *
     * @param privateKey 私钥
     * @param data       待加密的内容
     * @return 加密后的内容
     */
    public static byte[] encryptByPrivateKey(PrivateKey privateKey, byte[] data) {
        return rsa(privateKey, data, Cipher.ENCRYPT_MODE);
    }
 
    /**
     * 公钥加密
     *
     * @param base64PublicKey base64 公钥
     * @param data            待加密的内容
     * @return 加密后的内容
     */
    @Nullable
    public static String encryptToBase64(String base64PublicKey, @Nullable String data) {
        if (StringUtil.isBlank(data)) {
            return null;
        }
        return Base64Utils.encodeToString(encrypt(base64PublicKey, data.getBytes(Charsets.UTF_8)));
    }
 
    /**
     * 解密
     *
     * @param base64PrivateKey base64 私钥
     * @param data             数据
     * @return 解密后的数据
     */
    public static byte[] decrypt(String base64PrivateKey, byte[] data) {
        return decrypt(getPrivateKey(base64PrivateKey), data);
    }
 
    /**
     * 解密
     *
     * @param base64publicKey base64 公钥
     * @param data            数据
     * @return 解密后的数据
     */
    public static byte[] decryptByPublicKey(String base64publicKey, byte[] data) {
        return decryptByPublicKey(getPublicKey(base64publicKey), data);
    }
 
    /**
     * 解密
     *
     * @param privateKey privateKey
     * @param data       数据
     * @return 解密后的数据
     */
    public static byte[] decrypt(PrivateKey privateKey, byte[] data) {
        return rsa(privateKey, data, Cipher.DECRYPT_MODE);
    }
 
    /**
     * 解密
     *
     * @param publicKey PublicKey
     * @param data      数据
     * @return 解密后的数据
     */
    public static byte[] decryptByPublicKey(PublicKey publicKey, byte[] data) {
        return rsa(publicKey, data, Cipher.DECRYPT_MODE);
    }
 
    /**
     * rsa 加、解密
     *
     * @param key  key
     * @param data 数据
     * @param mode 模式
     * @return 解密后的数据
     */
    private static byte[] rsa(Key key, byte[] data, int mode) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_PADDING);
            cipher.init(mode, key);
            return cipher.doFinal(data);
        } catch (Exception e) {
            throw Exceptions.unchecked(e);
        }
    }
 
    /**
     * base64 数据解密
     *
     * @param base64PublicKey base64 公钥
     * @param base64Data      base64数据
     * @return 解密后的数据
     */
    public static byte[] decryptByPublicKeyFromBase64(String base64PublicKey, byte[] base64Data) {
        return decryptByPublicKey(getPublicKey(base64PublicKey), base64Data);
    }
 
    /**
     * base64 数据解密
     *
     * @param base64PrivateKey base64 私钥
     * @param base64Data       base64数据
     * @return 解密后的数据
     */
    @Nullable
    public static String decryptFromBase64(String base64PrivateKey, @Nullable String base64Data) {
        if (StringUtil.isBlank(base64Data)) {
            return null;
        }
        return new String(decrypt(base64PrivateKey, Base64Utils.decodeFromString(base64Data)), Charsets.UTF_8);
    }
 
    /**
     * base64 数据解密
     *
     * @param base64PrivateKey base64 私钥
     * @param base64Data       base64数据
     * @return 解密后的数据
     */
    public static byte[] decryptFromBase64(String base64PrivateKey, byte[] base64Data) {
        return decrypt(base64PrivateKey, Base64Utils.decode(base64Data));
    }
 
    /**
     * base64 数据解密
     *
     * @param base64PublicKey base64 公钥
     * @param base64Data      base64数据
     * @return 解密后的数据
     */
    @Nullable
    public static String decryptByPublicKeyFromBase64(String base64PublicKey, @Nullable String base64Data) {
        if (StringUtil.isBlank(base64Data)) {
            return null;
        }
        return new String(decryptByPublicKeyFromBase64(base64PublicKey, Base64Utils.decodeFromString(base64Data)), Charsets.UTF_8);
    }
 
}