Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a RSA Private/Public Key pair for SSH login on Android

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-----
like image 383
Boardy Avatar asked Jul 17 '16 19:07

Boardy


Video Answer


1 Answers

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

like image 140
heinousdog Avatar answered Oct 05 '22 23:10

heinousdog