6

I am working on a project where I need my app to generate a public/private RSA key for SSH login.

I have the following code so far to get the keys:

private void createKeyTest()
    {
        try
        {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(2048);
            KeyPair keyPair = kpg.genKeyPair();
            byte[] pri = keyPair.getPrivate().getEncoded();
            byte[] pub = keyPair.getPublic().getEncoded();

            String privateKey = new String(pri);
            String publicKey = new String(pub);

            Log.d("SSHKeyManager", "Private Key: " + privateKey);
            Log.d("SSHLeyManager", "Public Key: " + publicKey);
        }
        catch (NoSuchAlgorithmException ex)
        {
            Log.e("SSHKeyManager", ex.toString());
        }

When I print this out in Logcat I get random non textual characters when I am expecting the key to look something like:

-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQEAm8QDThbuEjAbQxbsdDltL2xdFkQOep3L0wseSJAxmDuvH6yB
9I2fEEmF+dcVoNo2DGCDZMw7EgdFsfQZNF+PzKdZwtvSUTDW/TmMHWux2wYimNU3
jhQ3kfxGmiLgMJHQHWLkESwd06rCr7s1yOnPObdPjTybt7Odbp9bu+E59U10Ri3W
JFxIhi9uYQvpRn4LT/VIfH/KBdglpbD9xBAneVbKFXW7....
-----END RSA PRIVATE KEY-----
halfer
  • 19,824
  • 17
  • 99
  • 186
Boardy
  • 35,417
  • 104
  • 256
  • 447
  • Have you considered that you are correctly getting the string contained within the `--- ---` section? – OneCricketeer Jul 17 '16 at 19:57
  • 1
    `new String()` on some byte array will not give you base-64 encoding of the bytes (or whatever encoding is used for those RSA files). – CommonsWare Jul 17 '16 at 20:00
  • Ah yes, I forgot that, I've tried base 64 encoding it, but the string always looks far shorter than when it is generated using the linux command ssh-keygen -t rsa on a linux box – Boardy Jul 17 '16 at 21:08
  • @Boardy - any solution for this meanwhile ? – Drahoš Maďar Aug 28 '17 at 14:48

1 Answers1

5
import android.util.Base64;

You can change

String privateKey = Base64.encodeToString(pri, Base64.DEFAULT);
String publicKey = Base64.encodeToString(pub, Base64.DEFAULT);

That will let you have Base64 version of public key and private key.

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

These format called PEM , you can custom add it or use library "bouncycastle".

Here is bouncycastle example:Export RSA public key to PEM String using java

heinousdog
  • 79
  • 2
  • 10