Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert RSA Publickey to base64 and vice versa

I have a publicKey/privateKey pair generated from this function:

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();
        }

    }

Now I want to convert publicKey to base64 while writing and use that base64 decode to get publicKey back ,how can that be done?

like image 917
android_guy Avatar asked Feb 05 '23 09:02

android_guy


1 Answers

Generally if you want to store a file in base 64 you can simply encode the byte array. You can even put a Base64 stream in between the ObjectOutputStream and FileOutputStream (helpfully provided by the Base64 class within Java 8).

However, public keys and private keys have default encodings which can be accessed using their getEncoded methods:

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);
}

This saves the public key in SubjectPublicKeyInfo format, something that can be read and written by multiple types of software and cryptographic libraries.

For instance, you can paste it in an online ASN.1 decoder (the online decoder will itself convert it to hex, but it will parse base 64 as well). The format of bytes are in so called ASN.1 / DER (which is a generic format, just like you can encode multiple types of files in XML).


If you want to have the key in OpenSSL compatible format (with a "PUBLIC KEY" header and footer) you can use a library such as Bouncy Castle (e.g. org.bouncycastle.openssl.jcajce.JcaPEMWriter).

like image 84
Maarten Bodewes Avatar answered Feb 20 '23 21:02

Maarten Bodewes