将 RSA 公钥转换为 base64,反之亦然

convert RSA Publickey to base64 and vice versa

我有一个 publicKey/privateKey 对从这个函数生成:

public static void generateKey() {
        try {
            final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
            keyGen.initialize(2048);
            final KeyPair key = keyGen.generateKeyPair();

            File privateKeyFile = new File(PRIVATE_KEY_FILE);
            File publicKeyFile = new File(PUBLIC_KEY_FILE);

            // Create files to store public and private key
            if (privateKeyFile.getParentFile() != null) {
                privateKeyFile.getParentFile().mkdirs();
            }
            privateKeyFile.createNewFile();

            if (publicKeyFile.getParentFile() != null) {
                publicKeyFile.getParentFile().mkdirs();
            }
            publicKeyFile.createNewFile();

            // Saving the Public key in a file
            ObjectOutputStream publicKeyOS = new ObjectOutputStream(
                    new FileOutputStream(publicKeyFile));
            publicKeyOS.writeObject(key.getPublic());
            publicKeyOS.close();

            // Saving the Private key in a file
            ObjectOutputStream privateKeyOS = new ObjectOutputStream(
                    new FileOutputStream(privateKeyFile));
            privateKeyOS.writeObject(key.getPrivate());
            privateKeyOS.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

现在我想在编写时将 publicKey 转换为 base64 并使用 base64 解码来取回 publicKey,该怎么做?

一般来说,如果您想以 base 64 格式存储文件,您只需对字节数组进行编码即可。您甚至可以在 ObjectOutputStreamFileOutputStream 之间放置一个 Base64 流(由 Java 8 中的 Base64 class 提供)。

但是,public 密钥和私钥具有默认编码,可以使用它们的 getEncoded 方法访问:

PublicKey publicKey = key.getPublic();
byte[] encodedPublicKey = publicKey.getEncoded();
String b64PublicKey = Base64.getEncoder().encodeToString(encodedPublicKey);

try (OutputStreamWriter publicKeyWriter =
        new OutputStreamWriter(
                new FileOutputStream(publicKeyFile),
                StandardCharsets.US_ASCII.newEncoder())) {
    publicKeyWriter.write(b64PublicKey);
}

这会以 SubjectPublicKeyInfo 格式保存 public 密钥,这种格式可以被多种类型的软件和加密库读取和写入。

例如,您可以 paste it in an online ASN.1 decoder(在线解码器本身会将其转换为十六进制,但它也会解析 base 64)。字节的格式是所谓的 ASN.1 / DER(这是一种通用格式,就像您可以在 XML 中编码多种类型的文件一样)。


如果您想要 OpenSSL 兼容格式的密钥(带有“PUBLIC KEY”页眉和页脚),您可以使用诸如 Bouncy Castle 之类的库(例如 org.bouncycastle.openssl.jcajce.JcaPEMWriter)。