关于RSA密钥生成方法

随机密钥生成

// 随机生成密钥
    protected static Map<String, Object>  initKey(  ) throws Exception{
        //实例化密钥对生成器
        KeyPairGenerator keyPairGen=KeyPairGenerator.getInstance(KEY_ALGORITHM);
        // 初始化密钥对生成器
        keyPairGen.initialize(KEY_SIZE);
        // 生成密钥对
        KeyPair keyPair=keyPairGen.generateKeyPair();
        //公钥
        RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
        //私钥
        RSAPrivateKey privateKey=(RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥字符串
        String publicKeyString = Base64.encode(publicKey.getEncoded());
        // 得到私钥字符串
        String privateKeyString = Base64.encode(privateKey.getEncoded());
        System.out.println("PUBLIC_KEY:"+publicKeyString);
        System.out.println("PRIVATE_KEY:"+privateKeyString);
            // 封装密钥
                Map<String, Object> keyMap=new HashMap<String,Object>(2);
            keyMap.put(PUBLIC_KEY, publicKeyString);
            keyMap.put(PRIVATE_KEY, privateKeyString);

            return keyMap;

    }

// 根据信息生成 固定密钥
因为在初始化keyPairGen时候,需要传入一个随机数,如果不传底层应该默认了随机,如果有第二个参数应该根据这个参数生成密钥!只是猜测,但是如果第二个参数固定,密钥生成也是固定!亲测

    // 根据固定值生成 固定密钥对儿

    protected static Map<String, Object>  initKey2(  ) throws Exception{
         /** RSA算法要求有一个可信任的随机数源 */
        String str_deta=new String("12345678");
        SecureRandom secureRandom=new SecureRandom(str_deta.getBytes()); 
        System.out.println("secureRandom"+secureRandom.hashCode());
        //实例化密钥对生成器
        KeyPairGenerator keyPairGen=KeyPairGenerator.getInstance(KEY_ALGORITHM);
        // 初始化密钥对生成器
        //keyPairGen.initialize(KEY_SIZE);
        keyPairGen.initialize(KEY_SIZE, secureRandom);
        // 生成密钥对
        KeyPair keyPair=keyPairGen.generateKeyPair();
        //公钥
        RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
        //私钥
        RSAPrivateKey privateKey=(RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥字符串
        String publicKeyString = Base64.encode(publicKey.getEncoded());
        // 得到私钥字符串
        String privateKeyString = Base64.encode(privateKey.getEncoded());
        System.out.println("PUBLIC_KEY:"+publicKeyString);
        System.out.println("PRIVATE_KEY:"+privateKeyString);
            // 封装密钥
            Map<String, Object> keyMap=new HashMap<String,Object>(2);
            keyMap.put(PUBLIC_KEY, publicKeyString);
            keyMap.put(PRIVATE_KEY, privateKeyString);

            return keyMap;

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值