1

I am generating my keypair like this:

 KeyPair kp = null;
 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
 kpg.initialize(2048);
 kp = kpg.generateKeyPair();

and I get my public key like this:

    PublicKey publicKey = kp.getPublic();
    byte[] publicKeyBytes = publicKey.getEncoded();
    String publicKeyEncoded = new String(Base64.encode(publicKeyBytes, Base64.DEFAULT));

What I get in return is perfectly fine key, but the server is accepting keys in the format in which I need to have starting and ending tags

-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----

Should I add these tags myself in the encoded key or there is some method/format in Java that gives me the key in the following format?

Shubham
  • 2,627
  • 3
  • 20
  • 36

1 Answers1

1

Post the next answer because the headline and footline strings fails when these don't have the right characters:

public class KeyManager {

    public static final String TAG = KeyManager.class.getSimpleName();

    public static String getPublicKey(){
        KeyPair kp = generateRSAKeys();
        assert kp != null;
        PublicKey publicKey = kp.getPublic();
        String key = encodeKey(publicKey.getEncoded());
        return addHeaders(key);  // --> ADDED HEADERS FOR SERVER COMPATIBILITY
    }

    private static String getPrivateKey(){
        KeyPair kp = generateRSAKeys();
        assert kp != null;
        PrivateKey privateKey = kp.getPrivate();
        return encodeKey(privateKey.getEncoded());
    }

    private static KeyPair generateRSAKeys() {
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(2048);
            return kpg.generateKeyPair();

        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG,"[ENCRYPT] NoSuchAlgorithmException error: ");
            e.printStackTrace();
            return null;

        } catch (Exception e) {
            Log.e(TAG,"[ENCRYPT] generateRSAKeys error: ");
            e.printStackTrace();
            return null;
        }
    }

    private static String addHeaders(String key){
        String headline = "-----BEGIN PUBLIC KEY-----\n";
        String footline = "-----END PUBLIC KEY-----\n";
        return headline+key+footline;
    }

    private static String encodeKey(byte[] keyBytes) {
        return new String(Base64.encode(keyBytes, Base64.DEFAULT));
    }
}
Hpsaturn
  • 2,702
  • 31
  • 38