1 //加密方式
 2     public static final String KEY_ALGORITHM = "RSA";
 3     //公钥
 4     public static final String PUBLIC_KEY = "RSAPublicKey";
 5     //私钥
 6     public static final String PRIVATE_KEY = "RSAPrivateKey";
 7     
 8     public static void main(String[] args) {
 9         
10         Map<String, Object> map;
11         try {
12             map=initKey();
13             String publicKey = getPublicKey(map);
14             System.out.println(publicKey);
15             String privateKey = getPrivateKey(map);
16             System.out.println(privateKey);
17         } catch (Exception e) {
18             e.printStackTrace();
19         }
20         
21     }
22     /**
23      * 获取公钥
24      * @param keyMap
25      * @return
26      */
27     public static String getPublicKey(Map<String, Object> keyMap){
28         //获取map中的公钥转化为key对象
29        Key key = (Key) keyMap.get(PUBLIC_KEY);
30        return encryptBASE64(key.getEncoded());
31     }
32 
33     
34     /**
35      * {@link Map}
36      * map中存放私钥和公钥
37      * @return
38      * @throws Exception
39      */
40     public static Map<String, Object> initKey() throws Exception{
41         //获得对象 KeyPairGenerator 参数 RSA 1024个字节
42         KeyPairGenerator key = KeyPairGenerator.getInstance(KEY_ALGORITHM);
43         key.initialize(1024);//这个地方官方文档说的必须初始化 可以参考一下jdk1.8官方文档
44         KeyPair generateKeyPair = key.generateKeyPair();
45       //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
46         RSAPublicKey publicKey = (RSAPublicKey) generateKeyPair.getPublic();
47         RSAPrivateKey privateKey = (RSAPrivateKey) generateKeyPair.getPrivate();
48         Map<String, Object> map =  new HashMap<String, Object>(2);
49         map.put(PUBLIC_KEY, publicKey);
50         map.put(PRIVATE_KEY, privateKey);
51         return map;
52     }
53     
54     /**
55      * 获取私钥
56      * @param keyMap
57      * @return
58      */
59     public static String getPrivateKey(Map<String, Object> keyMap){
60         //获取map中的公钥转化为key对象
61        Key key = (Key) keyMap.get(PRIVATE_KEY);
62        return encryptBASE64(key.getEncoded());
63     }
64 
65     /**
66      * 解码返回字节数组
67      * @param key
68      * @return
69      * @throws IOException
70      */
71     public static byte[] decryptBASE64(String key) throws IOException {
72         return new BASE64Decoder().decodeBuffer(key);
73     }
74     /**
75      * 编码返回字符串
76      * @param encoded
77      * @return
78      */
79     public static String encryptBASE64(byte[] encoded) {
80         return new BASE64Encoder().encodeBuffer(encoded);
81     }