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

and*_*guy 2 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();
        }

    }
Run Code Online (Sandbox Code Playgroud)

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

Maa*_*wes 5

通常,如果要将文件存储在base 64中,则可以简单地对字节数组进行编码。您甚至可以在ObjectOutputStream和之间插入一个Base64流FileOutputStream(由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);
}
Run Code Online (Sandbox Code Playgroud)

这样可以将公钥保存为SubjectPublicKeyInfo格式,可以通过多种类型的软件和密码库进行读写。

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

  • @scottyseus 如果您已经知道答案,一切都是显而易见的 :) 如果您*不**知道答案,诀窍是找到解决方案。很高兴我能帮你找到它。 (2认同)