java-RSA 生成秘鑰和公鑰


 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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM