liulin
2025-07-02 b9f0f641b85bbbfe74fc23efe4f4965586d9e3af
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
package com.lunhan.water.common.security;
 
import org.apache.commons.codec.binary.Base64;
 
import javax.crypto.Cipher;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
 
public class RSAUtil {
    private static String getKey(String filePath) {
        try {
            // Read key from file
            String strKeyPEM = "";
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String line;
            while ((line = br.readLine()) != null) {
                strKeyPEM += line + "\n";
            }
            br.close();
            return strKeyPEM;
        } catch (Exception e) {
            throw new RuntimeException("RSA读取文件(" + filePath + ")失败: " + e.getMessage());
        }
    }
 
 
 
 
 
    /**
     * 从pem文件获取私钥PrivateKey
     *
     * @param filePath pem文件路径
     */
    public static PrivateKey getPrivateKey(String filePath) {
        String privateKeyPEM = RSAUtil.getKey(filePath);
        return RSAUtil.getPrivateKeyFromString(privateKeyPEM);
    }
    /**
     * String转私钥PrivateKey
     *
     * @param key
     */
    public static PrivateKey getPrivateKeyFromString(String key) {
        try {
            String privateKeyPEM = key;
            privateKeyPEM = privateKeyPEM.replaceFirst("\\-+BEGIN PRIVATE KEY\\-+[^a-zA-Z0-9_\\-]+", "");
            privateKeyPEM = privateKeyPEM.replaceFirst("\\-+END PRIVATE KEY\\-+", "").replaceAll("\\s+", "");
            byte[] encoded = Base64.decodeBase64(privateKeyPEM);
 
            KeyFactory kf = KeyFactory.getInstance("RSA");
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
            return kf.generatePrivate(keySpec);
        } catch (Exception e) {
            throw new RuntimeException("RSA从字符串获取私钥失败: " + e.getMessage());
        }
    }
 
 
 
 
 
    public static PublicKey getPublicKey(String filename) throws IOException, GeneralSecurityException {
        String publicKeyPEM = RSAUtil.getKey(filename);
        return RSAUtil.getPublicKeyFromString(publicKeyPEM);
    }
 
    public static PublicKey getPublicKeyFromString(String key) {
        try {
            String publicKeyPEM = key;
            publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
            publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
            byte[] encoded = Base64.decodeBase64(publicKeyPEM);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            PublicKey pubKey = kf.generatePublic(new X509EncodedKeySpec(encoded));
            return pubKey;
        } catch (Exception e) {
            throw new RuntimeException("RSA从字符串获取公钥失败: " + e.getMessage());
        }
    }
 
 
 
 
 
    public static String sign(PrivateKey privateKey, String message) {
        try {
            Signature sign = Signature.getInstance("SHA1withRSA");
            sign.initSign(privateKey);
            sign.update(message.getBytes(StandardCharsets.UTF_8));
            return new String(Base64.encodeBase64(sign.sign()), StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("RSA签名生成失败: " + e.getMessage());
        }
    }
    public static boolean verify(PublicKey publicKey, String message, String signature) {
        try {
            Signature sign = Signature.getInstance("SHA1withRSA");
            sign.initVerify(publicKey);
            sign.update(message.getBytes(StandardCharsets.UTF_8));
            return sign.verify(Base64.decodeBase64(signature.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            throw new RuntimeException("RSA签名验证失败: " + e.getMessage());
        }
    }
 
 
 
 
 
    public static String encryptRSA(String rawText, String publicKey) {
        return RSAUtil.encryptRSA(rawText, RSAUtil.getPublicKeyFromString(publicKey));
    }
    public static String encryptRSA(String rawText, PublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64String(cipher.doFinal(rawText.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            throw new RuntimeException("RSA加密失败: " + e.getMessage());
        }
    }
 
 
 
 
 
    //公钥加密
//    public static String encrypt(String content, String publicKey) {
//        return RSAUtil.encrypt(content, RSAUtil.getPublicKeyFromString(publicKey));
//    }
//    public static String encrypt(String content, PublicKey publicKey) {
//        try {
//            byte[] output = RSAUtil.encrypt(content.getBytes(), publicKey);
//            BASE64Encoder encoder = new BASE64Encoder();
//            return encoder.encode(output);
//        } catch (Exception e) {
//            throw new RuntimeException("RSA加密失败: " + e.getMessage());
//        }
//    }
    //公钥加密
    public static byte[] encrypt(byte[] content, PublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//java默认"RSA"="RSA/ECB/PKCS1Padding"
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(content);
        } catch (Exception e) {
            throw new RuntimeException("RSA加密失败: " + e.getMessage());
        }
    }
 
 
 
 
 
    public static String decryptRSA(String cipherText, String privateKey) {
        return RSAUtil.decryptRSA(cipherText, RSAUtil.getPrivateKey(privateKey));
    }
 
    public static String decryptRSA(String cipherText, PrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(cipher.doFinal(Base64.decodeBase64(cipherText)), StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("RSA解密失败: " + e.getMessage());
        }
    }
 
 
 
 
 
    //私钥解密
//    public static String decrypt(String content, String privateKey) {
//        return RSAUtil.decrypt(content, RSAUtil.getPrivateKey(privateKey));
//    }
//    public static String decrypt(String content, PrivateKey privateKey) {
//        try {
//            byte[] buffer = RSAUtil.decrypt(content.getBytes(), privateKey);
//            BASE64Encoder encoder = new BASE64Encoder();
//            return encoder.encode(buffer);
//        } catch (Exception e) {
//            throw new RuntimeException("RSA解密失败: " + e.getMessage());
//        }
//    }
    //私钥解密
    public static byte[] decrypt(byte[] content, PrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(content);
        } catch (Exception e) {
            throw new RuntimeException("RSA解密失败: " + e.getMessage());
        }
    }
}