使用KeyPairGenertaor生成公钥和密钥,并保存在文件中

1、导入依赖
2、实现代码

 <dependencies>
        <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.6version>
        dependency>
    dependencies>
private static void generateKeyToFile(String algorithm, String pubPath, String priPath) throws Exception{
        //获取密钥对生成器
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        //获取密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        //获取公钥
        PublicKey publicKey = keyPair.getPublic();
        //获取私钥
        PrivateKey privateKey = keyPair.getPrivate();
        //获取byte数组
        byte[] publicKeyEncode = publicKey.getEncoded();
        byte[] privateKeyEncoded = privateKey.getEncoded();
        //进行Base64编码
        String publicKeyStr = Base64.encode(publicKeyEncode);
        String privateKeyStr = Base64.encode(privateKeyEncoded);
        //保存文件
        FileUtils.writeStringToFile(new File(pubPath),publicKeyStr, Charset.forName("UTF-8"));
        FileUtils.writeStringToFile(new File(priPath),privateKeyStr, Charset.forName("UTF-8"));
    }

你可能感兴趣的:(使用KeyPairGenertaor生成公钥和密钥,并保存在文件中)