Java 生成 RSA 密钥对并使用 Base64 编码保存

以下代码展示了使用 Java 生成 RSA 密钥对,并使用 Base64 编码将公钥和私钥分别保存到指定路径的方法。

public static void generateKey(String pubPath, String priPath) {
    try {
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance('RSA');
        // 初始化密钥对生成器,密钥大小为96-1024位
        keyPairGen.initialize(1024, new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        if (pubPath != null) {
            FileUtils.writeStringToFile(new File(pubPath), publicKeyString, String.valueOf(StandardCharsets.UTF_8));
        }
        if (priPath != null) {
            FileUtils.writeStringToFile(new File(priPath), privateKeyString, String.valueOf(StandardCharsets.UTF_8));
        }
    } catch (NoSuchAlgorithmException | IOException e) {
        e.printStackTrace();
    }
}

代码生成的 RSA 密钥格式

代码生成的 RSA 密钥格式是 Base64 编码后的字符串。其中,公钥和私钥都是以字符串形式保存,并分别保存在指定的公钥路径和私钥路径中。在生成过程中,使用了 RSA 算法和 1024 位的密钥大小。

Java 生成 RSA 密钥对并使用 Base64 编码保存

原文地址: https://www.cveoy.top/t/topic/nTlq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录