1

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)

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Surely the base64-decoder accepts a String argument?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.