Search code examples
javarsapublic-key-encryption

Java: Converting between Key type and String


Is it possible to take a public key that I have generated, convert it into a string, reverse the process and use it as a key again?

    generator = KeyPairGenerator.getInstance("RSA");
    generator.initialize(2048);

    KeyPair keyPair = generator.generateKeyPair();

    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

Then convert this to a string:

String public = someMethod(publicKey)

and then Reverse it at a later time:

RSAPublicKey newPublicKey = someMethod(public)

Solution

  • You can convert the Public Key to a String as follows.

    String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
    

    Then that String can be converted back to a public key as follows.

    byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey publicKey2 = keyFactory.generatePublic(spec);