Search code examples
javapublic-key-encryptionencryption-symmetric

Trying to convert private and public keys to String format


import java.security.*;

public class MyKeyGenerator {

    private KeyPairGenerator keyGen;
    private KeyPair pair;
    private PrivateKey privateKey;
    private PublicKey publicKey;
    private Context context;

    public MyKeyGenerator(Context context, int length)throws Exception{
        this.context =context;
        this.keyGen = KeyPairGenerator.getInstance("RSA");
        this.keyGen.initialize(length);
    }

    public void createKeys(){
        this.pair = this.keyGen.generateKeyPair();
        this.privateKey = pair.getPrivate();
        this.publicKey = pair.getPublic();
    }

    public PrivateKey getPrivateKey(){
        return this.privateKey;
    }

    public PublicKey getPublicKey(){
        return this.publicKey;
    }

    public  String getPrivateKeyStr(){
        byte b [] = this.getPrivateKey().getEncoded();
          return new String(b));
    }

    public  String getPublicKeyStr(){
        byte b [] = this.getPublicKey().getEncoded();
        return new String(b));
    }


}

Hello, I have searched SO for how to convert or get the String representation of a public key or private key, most of the answers were very old and only for how to convert String pubKey ="...."; into a key. I tried to generate the keys and get the encoded bytes and I tried to convert the byte to String as my code shows above, but I am not sure if I am doing it in the right way by simply converting the encoded bytes into a String.


Solution

    1. The Private/Public Key bytes: byte[] theBytes = key.getEncoded();
    2. Using new String(theBytes) is not so good, because it uses the default Charset (based on OS). Better is to pass the Charset you want (e.g UTF-8) a be consistent in that.
    3. I would suggest to have a HEX representation of the Private/Public keys . There are multiple ways to convert a byte[] into HEX string ( Java code To convert byte to Hexadecimal ). Having the HEX format makes also the key easier to read in some UI. E.g: AA BB CC 22 24 C1 ..
    4. Other option is Base64 format e.g: Base64.getEncoder().encodeToString(theBytes). (Java 8)