1.关于RSA算法的原理解析参考:http://www.ruanyifeng.com/blog/2013/06/rsa_algorithm_part_one.html

2.RSA密钥长度、明文长度和密文长度参考:https://blog.csdn.net/liuhuabai100/article/details/7585879

3.以下示例代码可以将密钥Base64转码之后保存到文本文件内,也可以从文本文件中读取密钥。

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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
public class RSAGenerator {
 
    /**
     * 算法
     */
    private String ALGORITHM_RSA = "RSA";
    private String DEFAULT_ENCODING = "UTF-8";
 
    public static final String KEY_TYPE_PUBLIC = "PUBLIC";
    public static final String KEY_TYPE_PRIVATE = "PRIVATE";
 
    /**
     * 公钥
     */
    private RSAPublicKey publicKey;
 
    private String publicKeyStr;
 
    /**
     * 私钥
     */
    private RSAPrivateKey privateKey;
 
    private String privateKeyStr;
 
    /**
     * 用于加解密
     */
    private Cipher cipher;
 
    /**
     * 明文块的长度 它必须小于密文块的长度 - 11
     */
    private int originLength = 128;
    /**
     * 密文块的长度
     */
    private int encrytLength = 256;
 
    /**
     * 生成密钥对
     * @return
     */
    public RSAGenerator generateKeyPair() {
        try {
            // RSA加密算法
            KeyPairGenerator keyPairGenerator = KeyPairGenerator
                    .getInstance(ALGORITHM_RSA);
            // 创建密钥对,长度采用2048
            keyPairGenerator.initialize(2048);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            // 分别得到公钥和私钥
            publicKey = (RSAPublicKey) keyPair.getPublic();
            privateKey = (RSAPrivateKey) keyPair.getPrivate();
 
            // 使用 Base64编码
            publicKeyStr = Base64Util.encode(publicKey.getEncoded());
            privateKeyStr = Base64Util.encode(privateKey.getEncoded());
             
            //将BASE64编码的结果保存到文件内
            String classPath = this.getClass().getClassLoader().getResource("").toString();
            String prefix = classPath.substring(classPath.indexOf(":") + 1);
            String publicFilePath = prefix+"public.txt";
            File publicFile= new File(publicFilePath);
            saveBase64KeyToFile(publicFile, publicKeyStr);
             
            String privateFilePath = prefix+"private.txt";
            File privateFile= new File(privateFilePath);
            saveBase64KeyToFile(privateFile, privateKeyStr);
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return this;
    }
     
     
 
    /**
     * 用公钥加密
     * @param content
     * @return 加密后的16进制字符串
     */
    public String encryptByPublic(String content) {
        String encode = "";
        try {
            cipher = Cipher.getInstance(ALGORITHM_RSA);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            // 该密钥能够加密的最大字节长度
            int splitLength = publicKey.getModulus().bitLength() / 8 - 11;
            byte[][] arrays = splitBytes(content.getBytes(), splitLength);
            // 加密
            StringBuffer buffer = new StringBuffer();
            for (byte[] array : arrays) {
                buffer.append(bytesToHexString(cipher.doFinal(array)));
            }
            encode = buffer.toString();
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return encode;
    }
 
    /**
     * 用私钥加密
     *
     * @param content
     * @return 加密后的16进制字符串
     */
    public String encryptByPrivate(String content) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM_RSA);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            // 该密钥能够加密的最大字节长度
            int splitLength = ((RSAPrivateKey) privateKey).getModulus()
                    .bitLength() / 8 - 11;
            byte[][] arrays = splitBytes(content.getBytes(), splitLength);
            StringBuffer stringBuffer = new StringBuffer();
            for (byte[] array : arrays) {
                stringBuffer.append(bytesToHexString(cipher.doFinal(array)));
            }
            return stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 用私钥解密
     * @param content
     * @return 解密后的原文
     */
    public String decryptByPrivate(String content) {
        String decode = "";
        try {
            cipher = Cipher.getInstance(ALGORITHM_RSA);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
 
            // 该密钥能够加密的最大字节长度
            int splitLength = privateKey.getModulus().bitLength() / 8;
            byte[] contentBytes = hexStringToBytes(content);
 
            byte[][] arrays = splitBytes(contentBytes, splitLength);
            StringBuffer stringBuffer = new StringBuffer();
            for (byte[] array : arrays) {
                stringBuffer.append(new String(cipher.doFinal(array)));
            }
            decode = stringBuffer.toString();
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return decode;
    }
 
    /**
     * 用私钥解密
     *
     * @param content
     * @return 解密后的原文
     */
    public String decryptByPublic(String content) {
        String decode = "";
        try {
            cipher = Cipher.getInstance(ALGORITHM_RSA);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            // 该密钥能够加密的最大字节长度
            int splitLength = publicKey.getModulus().bitLength() / 8;
            byte[] contentBytes = hexStringToBytes(content);
 
            byte[][] arrays = splitBytes(contentBytes, splitLength);
            StringBuffer stringBuffer = new StringBuffer();
            for (byte[] array : arrays) {
                stringBuffer.append(new String(cipher.doFinal(array)));
            }
            decode = stringBuffer.toString();
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return decode;
    }
 
    /**
     * 根据限定的每组字节长度,将字节数组分组
     * @param bytes 等待分组的字节组
     * @param splitLength 每组长度
     * @return 分组后的字节组
     */
    public static byte[][] splitBytes(byte[] bytes, int splitLength) {
        // bytes与splitLength的余数
        int remainder = bytes.length % splitLength;
        // 数据拆分后的组数,余数不为0时加1
        int quotient = remainder > 0 ? bytes.length / splitLength + 1
                : bytes.length / splitLength;
        byte[][] arrays = new byte[quotient][];
        byte[] array = null;
        for (int i = 0; i < quotient; i++) {
            // 如果是最后一组(quotient-1),同时余数不等于0,就将最后一组设置为remainder的长度
            if (i == quotient - 1 && remainder != 0) {
                array = new byte[remainder];
                System.arraycopy(bytes, i * splitLength, array, 0, remainder);
            } else {
                array = new byte[splitLength];
                System.arraycopy(bytes, i * splitLength, array, 0, splitLength);
            }
            arrays[i] = array;
        }
        return arrays;
    }
 
    /**
     * 将字节数组转换成16进制字符串
     * @param bytes  即将转换的数据
     * @return 16进制字符串
     */
    public static String bytesToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer(bytes.length);
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(0xFF & bytes[i]);
            if (temp.length() < 2) {
                sb.append(0);
            }
            sb.append(temp);
        }
        return sb.toString();
    }
 
    /**
     * 将16进制字符串转换成字节数组
     *
     * @param hex
     *            16进制字符串
     * @return byte[]
     */
    public static byte[] hexStringToBytes(String hex) {
        int len = (hex.length() / 2);
        hex = hex.toUpperCase();
        byte[] result = new byte[len];
        char[] chars = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(chars[pos]) << 4 | toByte(chars[pos + 1]));
        }
        return result;
    }
 
    /**
     * 将char转换为byte
     *
     * @param c
     *            char
     * @return byte
     */
    private static byte toByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
 
    /**
     * 保存公钥到文件
     *
     * @param file
     * @return
     */
    public boolean savePublicKey(File file) {
        return saveKeyToFile(publicKey, file);
    }
 
    /**
     * 保存私钥到文件
     *
     * @param file
     * @return
     */
    public boolean savePrivateKey(File file) {
        return saveKeyToFile(privateKey, file);
    }
 
    /**
     * 保存密钥到文件
     * @param key 密钥
     * @param file 文件
     * @return
     */
    private boolean saveKeyToFile(Key key, File file) {
        boolean result = false;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            // 公钥默认使用的是X.509编码,私钥默认采用的是PKCS #8编码
            byte[] encode = key.getEncoded();
            // 注意,此处采用writeObject方法,读取时也要采用readObject方法
            oos.writeObject(encode);
            oos.close();
            result = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                 
                e.printStackTrace();
            }
        }
        return result;
    }
 
    private boolean saveBase64KeyToFile(File file, String key) {
 
        boolean result = false;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(key.getBytes());
            fos.close();
            result = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
     
    /**
     * 从BASE64文件中读取KEY值
     * @param fileName
     * @param keyType
     */
    public void getKeyFromBase64File(String fileName,String keyType) {
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResource(fileName).openStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] subByte = new byte[1024];
            int len = 0;
            while((len=inputStream.read(subByte))>0) {
                outStream.write(subByte,0,len);
            }
            inputStream.close();
            outStream.close();
            String base64Key = new String(outStream.toByteArray(), DEFAULT_ENCODING);
            byte[] keybyte = Base64Util.decode(base64Key);
             
            // 默认编码
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
             
            if (KEY_TYPE_PUBLIC.equals(keyType)) {
                X509EncodedKeySpec x509eks = new X509EncodedKeySpec(keybyte);
                publicKey = (RSAPublicKey) keyFactory.generatePublic(x509eks);
                System.out.println(publicKey.getAlgorithm());
            } else {
                PKCS8EncodedKeySpec pkcs8eks = new PKCS8EncodedKeySpec(keybyte);
                privateKey = (RSAPrivateKey) keyFactory
                        .generatePrivate(pkcs8eks);
            }
                 
              
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 从文件中得到公钥
     *
     * @param file
     */
    public void getPublicKey(File file) {
        getKey(file, KEY_TYPE_PUBLIC);
    }
 
    /**
     * 从文件中得到私钥
     *
     * @param file
     */
    public void getPrivateKey(File file) {
        getKey(file, KEY_TYPE_PRIVATE);
    }
 
    /**
     * 从文件中得到密钥
     *
     * @param file
     * @param keyType
     */
    private void getKey(File file, String keyType) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            byte[] keybyte = (byte[]) ois.readObject();
            // 关闭资源
            ois.close();
            // 默认编码
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
            if (KEY_TYPE_PUBLIC.equals(keyType)) {
                X509EncodedKeySpec x509eks = new X509EncodedKeySpec(keybyte);
                publicKey = (RSAPublicKey) keyFactory.generatePublic(x509eks);
                System.out.println(publicKey.getAlgorithm());
            } else {
                PKCS8EncodedKeySpec pkcs8eks = new PKCS8EncodedKeySpec(keybyte);
                privateKey = (RSAPrivateKey) keyFactory
                        .generatePrivate(pkcs8eks);
            }
 
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
}  

代码中涉及到的Base64Util如下:

  

测试类:

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
public class RSATest {
    @Test
    public void test() {
        RSAGenerator rsaGenerator = new RSAGenerator().generateKeyPair();
        String str="数表的质数又称素数。指整数在一个大于1的自然数中,除了1和此整数自身外,没法被其他自然数整除的数";
        String encode = rsaGenerator.encryptByPublic(str);
        System.out.println(encode);
        System.out.println(rsaGenerator.decryptByPrivate(encode));
         
        System.out.println("用私钥加密公钥解密");
        String encrypt = rsaGenerator.encryptByPrivate(str);
        System.out.println(encrypt);
        System.out.println(rsaGenerator.decryptByPublic(encrypt));
    }
     
    @Test
    public void readKeyFromBase64File(){
        //从BASE64文件中读取KEY值
        RSAGenerator rsaGenerator = new RSAGenerator();
        rsaGenerator.getKeyFromBase64File("private.txt", RSAGenerator.KEY_TYPE_PRIVATE);
        rsaGenerator.getKeyFromBase64File("public.txt", RSAGenerator.KEY_TYPE_PUBLIC);
        String str="数表的质数又称素数。指整数在一个大于1的自然数中,除了1和此整数自身外,没法被其他自然数整除的数";
        String encode = rsaGenerator.encryptByPublic(str);
        System.out.println(encode);
        System.out.println(rsaGenerator.decryptByPrivate(encode));
    }
}

 以上代码大部分都是参考自网络,感谢网友的分享