I'm writing an app which is supposed to access my private server via SSH using JSch. Since I have set up public key authentication I want this app to authenticate the same way. I will be the only one using this app so I want to store my key either directly inside the app (e.g. hard-coded) or separated somewhere inside the home directory of my phone. Which would be the best way to store it, maybe as a resource file inside the project? Since I'm pretty new to Android development I'm not sure about what's the best way for this.
What I've 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 resulted in an "invalid privatekey" error. Besides that, I'm not sure which of both is the more secure way to work with.
Thanks in advance.
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
The JSch.addIdentity
(and ultimately KeyPair.load
) takes a buffer that contains a contents of key pair files as generated by ssh-keygen
(with -m pem
in recent versions of OpenSSH).
The formats are like 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 the format you have in private_key
and public_key
.
See also JSch to add private key from a string.
来源:https://stackoverflow.com/questions/56758040/loading-private-key-from-string-or-resource-in-java-jsch-in-android-app