RSA 非对称加密

Posted 缤纷世界WB

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RSA 非对称加密相关的知识,希望对你有一定的参考价值。

演示代码:https://pan.baidu.com/s/10rfSUUDEEHvCDEYH0oEVCw

 

Base64工具类,可以让rsa编码的乱码变成一串字符序列

复制代码
  1 package com.utils;
  2 
  3 import java.io.ByteArrayInputStream;
  4 import java.io.ByteArrayOutputStream;
  5 import java.io.File;
  6 import java.io.FileInputStream;
  7 import java.io.FileOutputStream;
  8 import java.io.InputStream;
  9 import java.io.OutputStream;
 10 
 11 import it.sauronsoftware.base64.Base64;
 12 
 13 /** */
 14 /**
 15  * <p>
 16  * BASE64编码解码工具包
 17  * </p>
 18  * <p>
 19  * 依赖javabase64-1.3.1.jar
 20  * </p>
 21  * 
 22  * @author IceWee
 23  * @date 2012-5-19
 24  * @version 1.0
 25  */
 26 public class Base64Utils {
 27 
 28     /** */
 29     /**
 30      * 文件读取缓冲区大小
 31      */
 32     private static final int CACHE_SIZE = 1024;
 33 
 34     /** */
 35     /**
 36      * <p>
 37      * BASE64字符串解码为二进制数据
 38      * </p>
 39      * 
 40      * @param base64
 41      * @return
 42      * @throws Exception
 43      */
 44     public static byte[] decode(String base64) throws Exception {
 45         return Base64.decode(base64.getBytes());
 46     }
 47 
 48     /** */
 49     /**
 50      * <p>
 51      * 二进制数据编码为BASE64字符串
 52      * </p>
 53      * 
 54      * @param bytes
 55      * @return
 56      * @throws Exception
 57      */
 58     public static String encode(byte[] bytes) throws Exception {
 59         return new String(Base64.encode(bytes));
 60     }
 61 
 62     /** */
 63     /**
 64      * <p>
 65      * 将文件编码为BASE64字符串
 66      * </p>
 67      * <p>
 68      * 大文件慎用,可能会导致内存溢出
 69      * </p>
 70      * 
 71      * @param filePath
 72      *            文件绝对路径
 73      * @return
 74      * @throws Exception
 75      */
 76     public static String encodeFile(String filePath) throws Exception {
 77         byte[] bytes = fileToByte(filePath);
 78         return encode(bytes);
 79     }
 80 
 81     /** */
 82     /**
 83      * <p>
 84      * BASE64字符串转回文件
 85      * </p>
 86      * 
 87      * @param filePath
 88      *            文件绝对路径
 89      * @param base64
 90      *            编码字符串
 91      * @throws Exception
 92      */
 93     public static void decodeToFile(String filePath, String base64) throws Exception {
 94         byte[] bytes = decode(base64);
 95         byteArrayToFile(bytes, filePath);
 96     }
 97 
 98     /** */
 99     /**
100      * <p>
101      * 文件转换为二进制数组
102      * </p>
103      * 
104      * @param filePath
105      *            文件路径
106      * @return
107      * @throws Exception
108      */
109     public static byte[] fileToByte(String filePath) throws Exception {
110         byte[] data = new byte[0];
111         File file = new File(filePath);
112         if (file.exists()) {
113             FileInputStream in = new FileInputStream(file);
114             ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
115             byte[] cache = new byte[CACHE_SIZE];
116             int nRead = 0;
117             while ((nRead = in.read(cache)) != -1) {
118                 out.write(cache, 0, nRead);
119                 out.flush();
120             }
121             out.close();
122             in.close();
123             data = out.toByteArray();
124         }
125         return data;
126     }
127 
128     /** */
129     /**
130      * <p>
131      * 二进制数据写文件
132      * </p>
133      * 
134      * @param bytes
135      *            二进制数据
136      * @param filePath
137      *            文件生成目录
138      */
139     public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
140         InputStream in = new ByteArrayInputStream(bytes);
141         File destFile = new File(filePath);
142         if (!destFile.getParentFile().exists()) {
143             destFile.getParentFile().mkdirs();
144         }
145         destFile.createNewFile();
146         OutputStream out = new FileOutputStream(destFile);
147         byte[] cache = new byte[CACHE_SIZE];
148         int nRead = 0;
149         while ((nRead = in.read(cache)) != -1) {
150             out.write(cache, 0, nRead);
151             out.flush();
152         }
153         out.close();
154         in.close();
155     }
156 
157 }
复制代码
RsaUtil工具类,可以调用里面的方法,产生公钥私钥对,和采用公钥加密,私钥加密等
复制代码
  1 package com.utils;
  2 
  3 import java.io.ByteArrayOutputStream;
  4 import java.security.Key;
  5 import java.security.KeyFactory;
  6 import java.security.KeyPair;
  7 import java.security.KeyPairGenerator;
  8 import java.security.PrivateKey;
  9 import java.security.PublicKey;
 10 import java.security.Signature;
 11 import java.security.interfaces.RSAPrivateKey;
 12 import java.security.interfaces.RSAPublicKey;
 13 import java.security.spec.PKCS8EncodedKeySpec;
 14 import java.security.spec.X509EncodedKeySpec;
 15 import java.util.HashMap;
 16 import java.util.Map;
 17 
 18 import javax.crypto.Cipher;
 19 
 20 /** */
 21 /**
 22  * <p>
 23  * RSA公钥/私钥/签名工具包
 24  * </p>
 25  * <p>
 26  * 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman)
 27  * </p>
 28  * <p>
 29  * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
 30  * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
 31  * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
 32  * </p>
 33  * 
 34  * @author IceWee
 35  * @date 2012-4-26
 36  * @version 1.0
 37  */
 38 public class RSAUtils {
 39 
 40     /** */
 41     /**
 42      * 加密算法RSA
 43      */
 44     public static final String KEY_ALGORITHM = "RSA";
 45 
 46     /** */
 47     /**
 48      * 签名算法
 49      */
 50     public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
 51 
 52     /** */
 53     /**
 54      * 获取公钥的key
 55      */
 56     private static final String PUBLIC_KEY = "RSAPublicKey";
 57 
 58     /** */
 59     /**
 60      * 获取私钥的key
 61      */
 62     private static final String PRIVATE_KEY = "RSAPrivateKey";
 63 
 64     /** */
 65     /**
 66      * RSA最大加密明文大小
 67      */
 68     private static final int MAX_ENCRYPT_BLOCK = 117;
 69 
 70     /** */
 71     /**
 72      * RSA最大解密密文大小
 73      */
 74     private static final int MAX_DECRYPT_BLOCK = 128;
 75 
 76     /** */
 77     /**
 78      * <p>
 79      * 生成密钥对(公钥和私钥)
 80      * </p>
 81      * 
 82      * @return
 83      * @throws Exception
 84      */
 85     public static Map<String, Object> genKeyPair() throws Exception {
 86         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
 87         keyPairGen.initialize(1024);
 88         KeyPair keyPair = keyPairGen.generateKeyPair();
 89         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
 90         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
 91         Map<String, Object> keyMap = new HashMap<String, Object>(2);
 92         keyMap.put(PUBLIC_KEY, publicKey);
 93         keyMap.put(PRIVATE_KEY, privateKey);
 94         return keyMap;
 95     }
 96 
 97     /** */
 98     /**
 99      * <p>
100      * 用私钥对信息生成数字签名
101      * </p>
102      * 
103      * @param data
104      *            已加密数据
105      * @param privateKey
106      *            私钥(BASE64编码)
107      * 
108      * @return
109      * @throws Exception
110      */
111     public static String sign(byte[] data, String privateKey) throws Exception {
112         byte[] keyBytes = Base64Utils.decode(privateKey);
113         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
114         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
115         PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
116         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
117         signature.initSign(privateK);
118         signature.update(data);
119         return Base64Utils.encode(signature.sign());
120     }
121 
122     /** */
123     /**
124      * <p>
125      * 校验数字签名
126      * </p>
127      * 
128      * @param data
129      *            已加密数据
130      * @param publicKey
131      *            公钥(BASE64编码)
132      * @param sign
133      *            数字签名
134      * 
135      * @return
136      * @throws Exception
137      * 
138      */
139     public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
140         byte[] keyBytes = Base64Utils.decode(publicKey);
141         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
142         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
143         PublicKey publicK = keyFactory.generatePublic(keySpec);
144         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
145         signature.initVerify(publicK);
146         signature.update(data);
147         return signature.verify(Base64Utils.decode(sign));
148     }
149 
150     /** */
151     /**
152      * <P>
153      * 私钥解密
154      * </p>
155      * 
156      * @param encryptedData
157      *            已加密数据
158      * @param privateKey
159      *            私钥(BASE64编码)
160      * @return
161      * @throws Exception
162      */
163     public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
164         byte[] keyBytes = Base64Utils.decode(privateKey);
165         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
166         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
167         Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
168         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
169         cipher.init(Cipher.DECRYPT_MODE, privateK);
170         int inputLen = encryptedData.length;
171         ByteArrayOutputStream out = new ByteArrayOutputStream();
172         int offSet = 0;
173         byte[] cache;
174         int i = 0;
175         // 对数据分段解密
176         while (inputLen - offSet > 0) {
177             if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
178                 cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
179             } else {
180                 cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
181             }
182             out.write(cache, 0, cache.length);
183             i++;
184             offSet = i * MAX_DECRYPT_BLOCK;
185         }
186         byte[] decryptedData = out.toByteArray();
187         out.close();
188         return decryptedData;
189     }
190 
191     /** */
192     /**
193      * <p>
194      * 公钥解密
195      * </p>
196      * 
197      * @param encryptedData
198      *            已加密数据
199      * @param publicKey
200      *            公钥(BASE64编码)
201      * @return
202      * @throws Exception
203      */
204     public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
205         byte[] keyBytes = Base64Utils.decode(publicKey);
206         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
207         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
208         Key publicK = keyFactory.generatePublic(x509KeySpec);
209         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
210         cipher.init(Cipher.DECRYPT_MODE, publicK);
211         int inputLen = encryptedData.length;
212         ByteArrayOutputStream out = new ByteArrayOutputStream();
213         int offSet = 0;
214         byte[] cache;
215         int i = 0;
216         // 对数据分段解密
217         while (inputLen - offSet > 0) {
218             if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
219                 cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
220             } else {
221                 cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
222             }
223             out.write(cache, 0, cache.length);
224             i++;
225             offSet = i * MAX_DECRYPT_BLOCK;
226         }
227         byte[] decryptedData = out.toByteArray();
228         out.close();
229         return decryptedData;
230     }
231 
232     /** */
233     /**
234      * <p>
235      * 公钥加密
236      * </p>
237      * 
238      * @param data
239      *            源数据
240      * @param publicKey
241      *            公钥(BASE64编码)
242      * @return
243      * @throws Exception
244      */
245     public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
246         byte[] keyBytes = Base64Utils.decode(publicKey);
247         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
248         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
249         Key publicK = keyFactory.generatePublic(x509KeySpec);
250         // 对数据加密
251         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
252         cipher.init(Cipher.ENCRYPT_MODE, publicK);
253         int inputLen = data.length;
254         ByteArrayOutputStream out = new ByteArrayOutputStream();
255         int offSet = 0;
256         byte[] cache;
257         int i = 0;
258         // 对数据分段加密
259         while (inputLen - offSet > 0) {
260             if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
261                 cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
262             } else {
263                 cache = cipher.doFinal(data, offSet, inputLen - offSet);
264             }
265             out.write(cache, 0, cache.length);
266             i++;
267             offSet = i * MAX_ENCRYPT_BLOCK;
268         }
269         byte[] encryptedData = out.toByteArray();
270         out.close();
271         return encryptedData;
272     }
273 
274     /** */
275     /**
276      * <p>
277      * 私钥加密
278      * </p>
279      * 
280      * @param data
281      *            源数据
282      * @param privateKey
283      *            私钥(BASE64编码)
284      * @return
285      * @throws Exception
286      */
287     public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
288         byte[] keyBytes = Base64Utils.decode(privateKey);
289         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
290         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
291         Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
292         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
293         cipher.init(Cipher.ENCRYPT_MODE, privateK);
294         int inputLen = data.length;
295         ByteArrayOutputStream out = new ByteArrayOutputStream();
296         int offSet = 0;
297         byte[] cache;
298         int i = 0;
299         // 对数据分段加密
300         while (inputLen - offSet > 0) {
301             if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
302                 cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
303             } else {
304                 cache = cipher.doFinal(data, offSet, inputLen - offSet);
305             }
306             out.write(cache, 0, cache.length);
307             i++;
308             offSet = i * MAX_ENCRYPT_BLOCK;
309         }
310         byte[] encryptedData = out.toByteArray();
311         out.close();
312         return encryptedData;
313     }
314 
315     /** */
316     /**
317      * <p>
318      * 获取私钥
319      * </p>
320      * 
321      * @param keyMap
322      *            密钥对
323      * @return
324      * @throws Exception
325      */
326     public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
327         Key key = (Key) keyMap.get(PRIVATE_KEY);
328         return Base64Utils.encode(key.getEncoded());
329     }
330 
331     /** */
332     /**
333      * <p>
334      * 获取公钥
335      * </p>
336      * 
337      * @param keyMap
338      *            密钥对
339      * @return
340      * @throws Exception
341      */
342     public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
343         Key key = (Key) keyMap.get(PUBLIC_KEY);
344         return Base64Utils.encode(key.getEncoded());
345     }
346 
347     /**
348      * java端公钥加密
349      */
350     public static String encryptedDataOnJava(String data, String PUBLICKEY) {
351         try {
352             data = Base64Utils.encode(encryptByPublicKey(data.getBytes(), PUBLICKEY));
353         } catch (Exception e) {
354             // TODO Auto-generated catch block
355             e.printStackTrace();
356         }
357         return data;
358     }
359 
360     /**
361      * java端私钥解密
362      */
363     public static String decryptDataOnJava(String data, String PRIVATEKEY) {
364         String temp = "";
365         try {
366             byte[] rs = Base64Utils.decode(data);
367             temp = new String(RSAUtils.decryptByPrivateKey(rs, PRIVATEKEY),"UTF-8"); //以utf-8的方式生成字符串
368 
369         } catch (Exception e) {
370             e.printStackTrace();
371         }
372         return temp;
373     }
374 
375 }
复制代码

json工具类

复制代码
 1 package com.utils;
 2 
 3 import com.google.gson.Gson;
 4 import com.google.gson.GsonBuilder;
 5 import com.google.gson.JsonNull;
 6 
 7 public class JsonUtil {
 8 
 9     private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").serializeNulls().create();
10 
11     /**
12      * @MethodName : toJson
13      * @Description : 将对象转为JSON串,此方法能够满足大部分需求
14      * @param src
15      *            :将要被转化的对象
16      * @return :转化后的JSON串
17      */
18     public static String toJson(Object src) {
19         if (src == null) {
20             return gson.toJson(JsonNull.INSTANCE);
21         }
22         return gson.toJson(src);
23     }
24 }
复制代码

 

 到这一步我们的工具类准备的差不多了,可以开始进入我们的主题了,java端Rsa测试类和web端交互的demo了

Rsa测试java测试类

复制代码
 1 package com.test;
 2 
 3 import java.util.Map;
 4 
 5 import org.junit.Test;
 6 
 7 import com.utils.Base64Utils;
 8 import com.utils.RSAUtils;
 9 
10 public class RSATester {
11 
12     static String publicKey;
13     static String privateKey;
14 
15     static {
16         try {
17             Map<String, Object> keyMap = RSAUtils.genKeyPair();
18             publicKey = RSAUtils.getPublicKey(keyMap);
19             privateKey = RSAUtils.getPrivateKey(keyMap);
20             System.err.println("公钥: \\n\\r" + publicKey);
21             System.err.println("私钥: \\n\\r" + privateKey);
22         } catch (Exception e) {
23             e.printStackTrace();
24         }
25     }
26 
27     public static void main(String[] args) throws Exception {
28         testJavaRsa();
29     }
30 
31     @Test
32     public void tests() throws Exception {
33         String data = "hNYdT0/8wxljGvLQVPYUDeoWS217rmB5msKOljb6OBsOhdL1Domxt6Sy3BqdGqS3StGJuZuQ9wEFzGdyoTQ7IRiC0gRrkLuxvCUq8FANt1JpJCBqvzLdQD/ygCjkJMWWkMU4EFUW3xYkAsidqM8Zynhpk+mdja3789Ng4s68xJI=";
34 
35         String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIn2zWqU7K/2qm5pOpq5bp9R+3MTnStWTfJU9nC/Vo7UKH9dITPvrELCTK+qlqpx5Fes+l0GY7n6u4n4jyiw4ejsvkZYQ5ww477yLOn2FcoEGuZEwPgSCmfTST0OFUgQqn+/J11k9L92jEHyieE3qmhMkMt0UsVUSJwx/nZxo30ZAgMBAAECgYBD3YHigeuEC4R+14iaf8jo2j0kuGtB3Cxvnlez0otTqw1YyYkBsU49cLKkXvfKVEgM0Ow/QltgKvSBxCE31PrrDka5TygVMqqA/IM7NrDvjUcGLjyoeNmLA8660fWcDxUTlAGN5kxIvUATayVwKVflpWPWu0FPKsWrZustnEo+4QJBAMCmYsWqAKWYMVRXFP3/XGRfio8DV793TOckyBSN9eh8UhgoZyT3u7oeHmDJEwm4aNMHlg1Pcdc6tNsvi1FRCiUCQQC3VNzfF4xOtUgX7vWPL8YVljLuXmy12iVYmg6ofu9l31nwM9FLQ1TRFglvF5LWrIXTQb07PgGd5DJMAQWGsqLlAkAPE7Z9M73TN+L8b8hDzJ1leZi1cpSGdoa9PEKwYR/SrxAZtefEm+LEQSEtf+8OfrEtetWCeyo0pvKKiOEFXytFAkEAgynL/DC0yXsZYUYtmYvshHU5ayFTVagFICbYZeSrEo+BoUDxdI9vl0fU6A5NmBlGhaZ65G+waG5jLc1tTrlvoQJAXBEoPcBNAosiZHQfYBwHqU6mJ9/ZacJh3MtJzGGebfEwJgtln5b154iANqNWXpySBLvkK+Boq7FYRiD83pqmUg==";
36         byte[] rs = Base64Utils.decode(data);
37 
38         String r1 = new String(RSAUtils.decryptByPrivateKey(rs, privateKey));
39 
40         System.out.println("\\r\\n\\r\\n" + r1 + "okb");
41 
42     }
43 
44     static void testSign() throws Exception {
45         System.err.println("私钥加密——公钥解密");
46         String source = "32232";
47         System.out.println("原文字:\\r\\n" + source);
48         byte[] data = source.getBytes();
49         byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);
50         System.out.println("加密后:\\r\\n" + new String(encodedData));
51         byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);
52         String target = new String(decodedData);
53         System.out.println("解密后: \\r\\n" + target);
54         System.err.println("私钥签名——公钥验证签名");
55         String sign = RSAUtils.sign(encodedData, privateKey);
56         System.err.println("签名:\\r" + sign);
57         boolean status = RSAUtils.verify(encodedData, publicKey, sign);
58         System.err.println("验证结果:\\r" + status);
59     }
60 
61     static void test() throws Exception {
62         System.err.println("公钥加密——私钥解密");
63         String source = "这是一行没有任何意义的文字,你看完了等于没看,不是吗?";
64         System.out.println("\\r加密前文字:\\r\\n" + source);
65         byte[] data = source.getBytes();
66         byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
67         System.out.println("加密后文字:\\r\\n" + new String(encodedData));
68         System.out.println("----------------:base64处理:" + Base64Utils.encode(encodedData));
69         byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);
70         String target = new String(decodedData);
71         System.out.println("解密后文字: \\r\\n" + target);
72     }
73 
74     /*
75      * 测试自己封装java端加密和解密的方法
76      */
77 
78     static void testJavaRsa() {
79         String PUBLICKEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcd+0zTY9Gn94iqkQJTlxYnEnCeFsLkk0a7hoAvi2B74VzDVV3xH0ZO9RkXvo1SgCB+uzbEWdrgQkzTqyjfTtgOguu3OnkVxIMJF34ibchTY0LWHGxq1m2gLGuVVqrlu1LtdV0X7xo/5zc8Mr+46veWb86kSpqe6rOAm69WWo5GwIDAQAB";
80         String PRIVATEKEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJx37TNNj0af3iKqRAlOXFicScJ4WwuSTRruGgC+LYHvhXMNVXfEfRk71GRe+jVKAIH67NsRZ2uBCTNOrKN9O2A6C67c6eRXEgwkXfiJtyFNjQtYcbGrWbaAsa5VWquW7Uu11XRfvGj/nNzwyv7jq95ZvzqRKmp7qs4Cbr1ZajkbAgMBAAECgYAHp349EkA+DjgJrhah9elilFKvZr/dcwy+koNHIgaL4rG+jRpvP3d3MowTVOocjUA1G5dWqCVNBwTyM5kSbl/nIxSCYwdUoDid4r0JbqkXkTTsIq3euHG8eiWr9rr3SDmwDojWoJEc4liVlfme8dQuMfgxe1QKq7wTrJwCKwbeMQJBAPwpknRPRK8W9hefbbtEu8mlbzUy+ER8Puq6dvS+lnWzJ8n2chJcHRYQFwWpjl4+SZuKeEcDmYmuQ7xuqEIayO0CQQCe2YeaxcU4uuDC45RAwCcMaNw1nDJuA+Gi47lXbroBXoeOiNZunViSZVUgDgrV/Ku6V54TaZIzZ21QFjf7mXEnAkEA7dZwMpAJonOvzfwrzbQ4wyrsx2q5zC68UT1qsdGJrJ48azutwC9tp7+pV0fj5nQtjS1/4Ms+aCQb84ET5rXIyQJAM0m45tgEHZT5DPO94kooUXFp6EVOYwcNyzILnZc6p0aGLhcwZPaYqmvdWEQwa3bxW3D+sPXdJou2V61U1f9s8QJALccvYwwWlCTq1iTmegYk9fOoc+isZKH+Z0YW70kFi94AYEO+utYwmXBEAqQ5VC/bywa1O71xdL4/RGCOSxBf2A==";
81         String data = "你好啊,冯老师!s 223 1@324234234sfsfsf";
82         data = RSAUtils.encryptedDataOnJava(data, PUBLICKEY);
83         System.out.println("加密数据:" + data);
84 
85         System.out.println("解密数据:" + RSAUtils.decryptDataOnJava(data, PRIVATEKEY));
86     }
87 
88     static void testFrontEncrptAndAfterDecrypt() {
89         String PRIVATEKEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIn2zWqU7K/2qm5pOpq5bp9R+3MTnStWTfJU9nC/Vo7UKH9dITPvrELCTK+qlqpx5Fes+l0GY7n6u4n4jyiw4ejsvkZYQ5ww477yLOn2FcoEGuZEwPgSCmfTST0OFUgQqn+/J11k9L92jEHyieE3qmhMkMt0UsVUSJwx/nZxo30ZAgMBAAECgYBD3YHigeuEC4R+14iaf8jo2j0kuGtB3Cxvnlez0otTqw1YyYkBsU49cLKkXvfKVEgM0Ow/QltgKvSBxCE31PrrDka5TygVMqqA/IM7NrDvjUcGLjyoeNmLA8660fWcDxUTlAGN5kxIvUATayVwKVflpWPWu0FPKsWrZustnEo+4QJBAMCmYsWqAKWYMVRXFP3/XGRfio8DV793TOckyBSN9eh8UhgoZyT3u7oeHmDJEwm4aNMHlg1Pcdc6tNsvi1FRCiUCQQC3VNzfF4xOtUgX7vWPL8YVljLuXmy12iVYmg6ofu9l31nwM9FLQ1TRFglvF5LWrIXTQb07PgGd5DJMAQWGsqLlAkAPE7Z9M73TN+L8b8hDzJ1leZi1cpSGdoa9PEKwYR/SrxAZtefEm+LEQSEtf+8OfrEtetWCeyo0pvKKiOEFXytFAkEAgynL/DC0yXsZYUYtmYvshHU5ayFTVagFICbYZeSrEo+BoUDxdI9vl0fU6A5NmBlGhaZ65G+waG5jLc1tTrlvoQJAXBEoPcBNAosiZHQfYBwHqU6mJ9/ZacJh3MtJzGGebfEwJgtln5b154iANqNWXpySBLvkK+Boq7FYRiD83pqmUg==";
90         String data = "FBGU7sQfpSfCgB2hqFuIqkivEUHVRHD8JFdyxYeWqQHsTj9UEuVmvi28n1fOHRwW+3aZD3ttdzfUHWiXD2NErcX/CYs5BtSXT7RcJfWWcXvegq5BBDEAJCADWCRdYnblN+SLUC+ctDXcLw4xmjwAajowSzhCfY/lU3TdnJjO488=";
91         System.out.println("解密数据:" + RSAUtils.decryptDataOnJava(data, PRIVATEKEY));
92     }
93 
94 }
复制代码

 前端加密jsp页面

 

复制代码
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 <script src="js/jquery-2.1.3.js"></script>
 9 <script src="js/jsencrypt.min.js"></script>
10 </head>
11 <body>
12 
13     <script type="text/javascript">
14         $(function() {
15             $("#bt").click(
16                     function() {
17 
18                         var encrypt = new JSEncrypt();
19                         encrypt.setPublicKey($("#publickey").val());
20                         encrypt.setPrivateKey($("#privatekey").val());
21                         var password = $("#password").val();
22                         var uname = $("#uname").val();
23                         password = encrypt.encrypt(password);
24 
25                         uname = encrypt.encrypt(uname);
26                         $("#jmName").val(uname);
27                         $("#jmPasswrod").val(password);
28                         var jsonData = {
29                             "password" : password,
30                             "uname" : uname
31                         };
32 
33                         $.post("jiemi.do", jsonData, function(result) {
34                             alert("解密的用户名:" + result.uname + "\\n" + "解密的密码:"
35                                     + result.password);
36 
37                         }, \'json\');
38                     });
39         });
40     </script>
41     <h2>公钥:</h2>
42     <textarea id="publickey" rows="5" cols="45">MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ9s1qlOyv9qpuaTqauW6fUftzE50rVk3yVPZwv1aO1Ch/XSEz76xCwkyvqpaqceRXrPpdBmO5+ruJ+I8osOHo7L5GWEOcMOO+8izp9hXKBBrmRMD4Egpn00k9DhVIEKp/vyddZPS/doxB8onhN6poTJDLdFLFVEicMf52caN9GQIDAQAB
43         </textarea>
44     <h2>私钥</h2>
45     <textarea rows="10" cols="45" id="privatekey">MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIn2zWqU7K/2qm5pOpq5bp9R+3MTnStWTfJU9nC/Vo7UKH9dITPvrELCTK+qlqpx5Fes+l0GY7n6u4n4jyiw4ejsvkZYQ5ww477yLOn2FcoEGuZEwPgSCmfTST0OFUgQqn+/J11k9L92jEHyieE3qmhMkMt0UsVUSJwx/nZxo30ZAgMBAAECgYBD3YHigeuEC4R+14iaf8jo2j0kuGtB3Cxvnlez0otTqw1YyYkBsU49cLKkXvfKVEgM0Ow/QltgKvSBxCE31PrrDka5TygVMqqA/IM7NrDvjUcGLjyoeNmLA8660fWcDxUTlAGN5kxIvUATayVwKVflpWPWu0FPKsWrZustnEo+4QJBAMCmYsWqAKWYMVRXFP3/XGRfio8DV793TOckyBSN9eh8UhgoZyT3u7oeHmDJEwm4aNMHlg1Pcdc6tNsvi1FRCiUCQQC3VNzfF4xOtUgX7vWPL8YVljLuXmy12iVYmg6ofu9l31nwM9FLQ1TRFglvF5LWrIXTQb07PgGd5DJMAQWGsqLlAkAPE7Z9M73TN+L8b8hDzJ1leZi1cpSGdoa9PEKwYR/SrxAZtefEm+LEQSEtf+8OfrEtetWCeyo0pvKKiOEFXytFAkEAgynL/DC0yXsZYUYtmYvshHU5ayFTVagFICbYZeSrEo+BoUDxdI9vl0fU6A5NmBlGhaZ65G+waG5jLc1tTrlvoQJAXBEoPcBNAosiZHQfYBwHqU6mJ9/ZacJh3MtJzGGebfEwJgtln5b154iANqNWXpySBLvkK+Boq7FYRiD83pqmUg==</textarea>
46     <hr />
47     <form>
48         用户名:<input type="text" name="uname" id="uname" /> 密码:<input
49             type="text" name="password" id="password" />
50         <hr />
51         用户密文
52         <textarea id="jmName">
53     </textarea>
54         密码密文
55         <textarea id="jmPasswrod">
56     </textarea>
57         <input type="button" id="bt" value="提交" />
58     </form>
59 
60 </body>
61 </html>
复制代码

 后端servlet解密

复制代码
 1 package com;
 2 
 3 import java.io.IOException;
 4 import java.util.HashMap;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.utils.JsonUtil;
12 import com.utils.RSAUtils;
13 
14 /**
15  * Servlet implementation class JieMiServlet
16  */
17 public class JieMiServlet extends HttpServlet {
18     private static final long serialVersionUID = 1L;
19 
20     protected void doGet(HttpServletRequest request, HttpServletResponse response)
21             throws ServletException, IOException {
22         doPost(request, response);
23     }
24 
25     protected void doPost(HttpServletRequest request, HttpServletResponse response)
26             throws ServletException, IOException {
27         // 获取数据
28         String uname = request.getParameter("uname");
29         String password = request.getParameter("password");
30         String PRIVATEKEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIn2zWqU7K/2qm5pOpq5bp9R+3MTnStWTfJU9nC/Vo7UKH9dITPvrELCTK+qlqpx5Fes+l0GY7n6u4n4jyiw4ejsvkZYQ5ww477yLOn2FcoEGuZEwPgSCmfTST0OFUgQqn+/J11k9L92jEHyieE3qmhMkMt0UsVUSJwx/nZxo30ZAgMBAAECgYBD3YHigeuEC4R+14iaf8jo2j0kuGtB3Cxvnlez0otTqw1YyYkBsU49cLKkXvfKVEgM0Ow/QltgKvSBxCE31PrrDka5TygVMqqA/IM7NrDvjUcGLjyoeNmLA8660fWcDxUTlAGN5kxIvUATayVwKVflpWPWu0FPKsWrZustnEo+4QJBAMCmYsWqAKWYMVRXFP3/XGRfio8DV793TOckyBSN9eh8UhgoZyT3u7oeHmDJEwm4aNMHlg1Pcdc6tNsvi1FRCiUCQQC3VNzfF4xOtUgX7vWPL8YVljLuXmy12iVYmg6ofu9l31nwM9FLQ1TRFglvF5LWrIXTQb07PgGd5DJMAQWGsqLlAkAPE7Z9M73TN+L8b8hDzJ1leZi1cpSGdoa9PEKwYR/SrxAZtefEm+LEQSEtf+8OfrEtetWCeyo0pvKKiOEFXytFAkEAgynL/DC0yXsZYUYtmYvshHU5ayFTVagFICbYZeSrEo+BoUDxdI9vl0fU6A5NmBlGhaZ65G+waG5jLc1tTrlvoQJAXBEoPcBNAosiZHQfYBwHqU6mJ9/ZacJh3MtJzGGebfEwJgtln5b154iANqNWXpySBLvkK+Boq7FYRiD83pqmUg==";
31         // 解密
32         uname = RSAUtils.decryptDataOnJava(uname, PRIVATEKEY);
33         password = RSAUtils.decryptDataOnJava(password, PRIVATEKEY);
34         // 用map封装返回的数据
35         HashMap<String, Object> result = new HashMap<String, Object>();
36         result.put("uname", uname);
37         result.put("password", password);
38 
39         response.getWriter().print(JsonUtil.toJson(result));
40 
41     }
42 
43 }
复制代码

 

转自【https://www.cnblogs.com/nanyangke-cjz/p/5898361.html】

以上是关于RSA 非对称加密的主要内容,如果未能解决你的问题,请参考以下文章

技术 | RSA非对称加密算法详解

源码基于最优非对称加密填充的RSA加密

java编写非对称加密,解密,公钥加密,私钥解密,RSA,rsa

RSA 非对称加密

非对称加密算法-RSA算法

非对称加密Rsa数字签名Go实战