将RSA Publickey转换为base64,反之亦然

时间:2017-01-07 21:35:20

标签: java cryptography rsa

我有一个从这个函数生成的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,怎么办呢?

1 个答案:

答案 0 :(得分:4)

通常,如果要将文件存储在base 64中,则可以简单地对字节数组进行编码。您甚至可以在ObjectOutputStreamFileOutputStream之间放置一个Base64流(由Java 8中的Base64类提供帮助)。

但是,公钥和私钥具有默认编码,可以使用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格式保存公钥,这种格式可以由多种类型的软件和加密库读取和写入。

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

相关问题