13693261870
2025-06-24 8565bd83fcd670ec8379084d600eb97d18037d21
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
package com.terra.system.helper;
 
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ClassPathResource;
 
import javax.crypto.Cipher;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
 
/**
 * RSA工具类
 * @author WWW
 */
public class RsaHelper {
    /**
     * 私钥
     */
    private static String privateKey;
 
    /**
     * 公钥
     */
    private static String publicKey;
 
    /**
     * 密钥算法
     */
    private static final String KEY_ALGORITHM = "RSA";
 
    /**
     * RSA密钥长度:1024 或 2048
     */
    private static final int DEFAULT_RSA_KEY_SIZE = 1024;
 
    /**
     * 日志
     */
    private final static Log log = LogFactory.getLog(RsaHelper.class);
 
    /**
     * 生成公私钥
     */
    public static void generate() {
        Map<String, String> result = generateRsaKey(DEFAULT_RSA_KEY_SIZE);
        System.out.println("公钥为:" + result.get("publicKey"));
        System.out.println("私钥为:" + result.get("privateKey"));
    }
 
    /**
     * 获取RSA加密私钥
     *
     * @return
     * @throws IOException
     */
    public static String getPrivateKey() throws IOException {
        if (privateKey == null) {
            InputStream inPrivate = new ClassPathResource("config" + File.separator + "rsa_private_key.txt").getInputStream();
            privateKey = inputStream2String(inPrivate);
            inPrivate.close();
        }
 
        return privateKey;
    }
 
    /**
     * 获取RSA加密公钥
     *
     * @return
     * @throws IOException
     */
    public static String getPublicKey() throws IOException {
        if (publicKey == null) {
            InputStream inPrivate = new ClassPathResource("config" + File.separator + "rsa_public_key.txt").getInputStream();
            publicKey = inputStream2String(inPrivate);
            inPrivate.close();
        }
 
        return publicKey;
    }
 
    /**
     * 读取文本文件
     *
     * @param fileName 文件路径
     * @return
     * @throws IOException
     */
    public static String readFile(String fileName) throws IOException {
        File file = new File(fileName);
        BufferedReader br = new BufferedReader(new FileReader(file));
 
        StringBuilder result = new StringBuilder();
 
        String line = null;
        while ((line = br.readLine()) != null) {
            result.append(System.lineSeparator() + line);
        }
        br.close();
 
        return result.toString();
    }
 
    /**
     * 把inputStream转成String
     *
     * @param is
     * @return
     * @throws IOException
     */
    private static String inputStream2String(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
        int i = -1;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
 
        String str = baos.toString();
        baos.close();
 
        return str;
    }
 
    /**
     * 生成RSA的公私钥
     *
     * @param keySize 1025 或 2048
     * @return
     */
    public static Map<String, String> generateRsaKey(int keySize) {
        Map<String, String> result = new HashMap<>(2);
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
 
            // 初始化密钥对生成器,密钥大小为1024 2048位
            keyPairGen.initialize(keySize, new SecureRandom());
 
            // 生成一个密钥对,保存在keyPair中
            KeyPair keyPair = keyPairGen.generateKeyPair();
 
            // 得到公钥字符串
            String pub = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
            result.put("publicKey", pub);
 
            // 得到私钥字符串
            String pri = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
            result.put("privateKey", pri);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
 
        return result;
    }
 
    /**
     * RSA私钥解密
     *
     * @param str 加密的字符串
     * @return 解密字符串
     * @throws Exception 加密过程中的异常信息
     */
    public static String decrypt(String str) throws Exception {
        // 64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
 
        // Base64编码的私钥
        byte[] decoded = Base64.decodeBase64(getPrivateKey());
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
 
        // RSA解密:RSA/ECB/NoPadding
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
 
        String outStr = new String(cipher.doFinal(inputByte));
 
        return outStr;
    }
 
    /**
     * RSA公钥加密
     *
     * @param str 需要加密的字符串
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(String str) throws Exception {
        // Base64编码的公钥
        byte[] decoded = Base64.decodeBase64(getPublicKey());
 
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
 
        // RSA加密:RSA/ECB/NoPadding
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
 
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
 
        return outStr;
    }
}