且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

RSA 生成公钥、私钥对

更新时间:2021-07-24 18:51:11


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
  /** 指定key的大小 */
    private static int          KEYSIZE       = 1024;
    // 字符集
    private final static String CHARACTER_SET = "UTF-8";
    // rsa 加密方式
    public static final String  RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";
 
    /**
     
     * 描述:RSA 生成公钥、私钥对
     
     * @return
     * @throws Exception
     * @author yangyongchuan 2016年11月8日 上午10:16:56
     * @version 1.0
     */
    public static Map<String, String> generateKeyPair() throws Exception {
        /** RSA算法要求有一个可信任的随机数源 */
        SecureRandom sr = new SecureRandom();
        /** 为RSA算法创建一个KeyPairGenerator对象 */
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
        kpg.initialize(KEYSIZE, sr);
        /** 生成密匙对 */
        KeyPair kp = kpg.generateKeyPair();
        /** 得到公钥 */
        Key publicKey = kp.getPublic();
        byte[] publicKeyBytes = publicKey.getEncoded();
        String pub = new String(Base64.encodeBase64(publicKeyBytes), CHARACTER_SET);
        /** 得到私钥 */
        Key privateKey = kp.getPrivate();
        byte[] privateKeyBytes = privateKey.getEncoded();
        String pri = new String(Base64.encodeBase64(privateKeyBytes), CHARACTER_SET);
 
        Map<String, String> map = new HashMap<String, String>();
        map.put("publicKey", pub);
        map.put("privateKey", pri);
        RSAPublicKey rsp = (RSAPublicKey) kp.getPublic();
        BigInteger bint = rsp.getModulus();
        byte[] b = bint.toByteArray();
        byte[] deBase64Value = Base64.encodeBase64(b);
        String retValue = new String(deBase64Value);
        map.put("modulus", retValue);
        return map;
    }

RSA 生成公钥私钥对。在map中获取"publicKey","privateKey"。







      本文转自建波李 51CTO博客,原文链接:http://blog.51cto.com/jianboli/1910744,如需转载请自行联系原作者