Java – Loads a private key from a string or resource in Java JSch for an Android application

Loads a private key from a string or resource in Java JSch for an Android application… here is a solution to the problem.

Loads a private key from a string or resource in Java JSch for an Android application

I’m writing an application that is supposed to SSH my private server using JSch. Because I’ve set up public key authentication, I want this app to authenticate in the same way. I’ll be the only one using this app, so I’d like to store my key directly in the app (e.g. hardcoded) or somewhere separate in my phone’s home directory. Which storage is best, perhaps as a resource file in the project? Since I’m new to Android development, I’m not sure what the best approach is.

I tried :

// [...]
String user = "my_user";
String ssh_pwd = "my_pwd";
String host = "my_host";
 stored as OpenSSH key - file not found error - where shoud I move this file?
String private_key = "./my_pk";

int port = 22;

 basic SSH connection stuff
JSch jsch = new JSch();
session = jsch.getSession(user, host, port);
jsch.addIdentity(private_key, ssh_pwd.getBytes());

Another way:

// [...]
 private key in OpenSSH format as a plain string
String private_key = "xyz123abc456def789ghi012..."; 
 public key in OpenSSH format as a plain string
String public_key = "a1b2c3d4e5..."; 
// [...]
jsch.addIdentity("id_rsa", private_key.getBytes(), public_key.getBytes(), ssh_pwd.getBytes());

The latter results in an “invalid private key” error. Other than that, I’m not sure which of the two is a safer way to work.

Thanks in advance.

Solution

String private_key = "xyz123abc456def789ghi012...";  private key in OpenSSH format as a plain string
String public_key = "a1b2c3d4e5...";  public key in OpenSSH format as a plain string

JSch.addIdentity (And the final .) KeyPair.load ) takes a buffer containing ssh-keygen > by (in the latest version of OpenSSH The contents of the key pair file generated with -m pem).

The format is this:

-----BEGIN RSA PRIVATE  .KEY-----
MIIEpAIBAAKCAQEAvc04a8wViYV5Kb4jX+MxEqN1vi9q9C7mPhf6DV+mb1ADNAiR
YeLqPMLCYUF2ViobcGfarb51gz7iB2TgkDmhQNK9XDCOUaGYN/FeZcN0JpzkjEjZ
ApbRfshj1h9qKQUW+38XKnltMtf4dxiuxkXph8P6IMVveTDs3sSbBPq560bdJ1AD
...
PEyVxlat2I4ShuLQiO1QIuS8ABu5yDM2EouB6vlxtGEBpIJItp7cyA==
-----END RSA PRIVATE KEY-----
ssh-rsa  AAAAB3NzaC1yc2EAAAADAQABAAABAQC9zThrzBWJhXkpviNf4zESo3W+L2r0LuY+F/oNX6ZvUAM0CJFh4uo8wsJhQXZWKhtwZ9qtvnWDPuIHZOCQOaFA0r1cMI5RoZg38V5lw3QmnOSMSNkCltF+ yGPWH2opBRb7fxcqeW0y1/h3GK7GRemHw/ogxW95MOzexJsE+rnrRt0nUAOu4hHjL6G/nlvdJ1jjZ06NwhYkbAxRoJkHUJTtMT2IL5ZmdAf37KHSPqZS32pLxQDmPutZxpIwlhz4aR78ZGp4+ 57mR069Y4at09GF0UmgtIiLjlKUexMf5sueVQ8LKhME6vOupMzTbiFEB3UJNq8d9Yx5i+c/IRHUIcI1 marti@MartinuvOmen

This is not your format in private_key and public_key.


See also JSch to add private key from a string.

Related Problems and Solutions