Create RSA Private / Public Key pair for SSH login on Android

I am working on a project where I need an application to create a public / private RSA key to enter SSH.

I have the following code 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 in Logcat, I get random non-text characters when I expect the key to look something like this:

-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQEAm8QDThbuEjAbQxbsdDltL2xdFkQOep3L0wseSJAxmDuvH6yB
9I2fEEmF+dcVoNo2DGCDZMw7EgdFsfQZNF+PzKdZwtvSUTDW/TmMHWux2wYimNU3
jhQ3kfxGmiLgMJHQHWLkESwd06rCr7s1yOnPObdPjTybt7Odbp9bu+E59U10Ri3W
JFxIhi9uYQvpRn4LT/VIfH/KBdglpbD9xBAneVbKFXW7....
-----END RSA PRIVATE KEY-----

Thanks for any help you can provide.

+4
source share
1 answer
import android.util.Base64;

You can change

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

This will allow you to have a Base64 public key and private key.

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

This format is called PEM, you can add it or use the "bouncycastle" library.

bouncycastle: RSA PEM String java

+1

Source: https://habr.com/ru/post/1648172/


All Articles