14

Can someone give me an example of using SSHJ for Public Key Authentication? I realise this question is essentially identical to ssh example of private/public key authentication, however the answer by the author https://stackoverflow.com/users/126346/shikhar refers to a google user group that no longer exists, and I am having trouble getting it to work.

Thanks! Phil

Community
  • 1
  • 1
Obiphil
  • 361
  • 1
  • 6
  • 17

2 Answers2

14

We built the overthere framework on top of SSHJ. Which can connect also connect using key files. The following piece of code should work, but make sure you add the bouncycastle library to your classpath.

SSHClient client = new SSHClient();
String username = "johndoe";
File privateKey = new File("~/.ssh/id_rsa");
KeyProvider keys = client.loadKeys(privateKey.getPath());
client.authPublickey(username, keys);

Hope that helps.

Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
Hiery Nomus
  • 17,429
  • 2
  • 41
  • 37
  • Hi, thanks for responding! Is this definitely your code? I attempted to code it and got the error that SSHClient.loadKeys doesn't accept a file as an argument, which according to http://schmizz.net/sshj/javadoc/0.5.0/net/schmizz/sshj/SSHClient.html is correct. I have previously tried providing location as a string to loadKeys, to no avail. Am I misreading your code? – Obiphil Sep 28 '11 at 10:37
  • I forgot to add the getPath(). Stripped quite a bit of framework code to give you a concise answer ;) – Hiery Nomus Sep 30 '11 at 13:12
  • Alas, that's essentially what I did, and it did not work. I have given up on SSHJ for now, using JSch instead, as it seems to provide equivalent functionality, but that I can actually get working. Thanks for your help! – Obiphil Oct 04 '11 at 12:11
  • Could you elaborate on what part of it didn't work? Exceptions? error messages? – Hiery Nomus Oct 04 '11 at 12:26
  • Using code above, i got error `Could not verify 'ssh-rsa' host key with fingerprint '' for '' on port <22>`. When I added line `client.addHostKeyVerifier(new PromiscuousVerifier());`, i get `Exhausted available authentication methods`. – Greg Oct 22 '15 at 21:14
  • Using debug logging you should see which authentication methods it tries. Is your server setup for private key authentication? – Hiery Nomus Oct 23 '15 at 13:09
  • 1
    should be `client.authPublickey` with lower case 'k' :) – Andrew Lohr May 02 '18 at 21:00
  • 2
    don't forget to add the `client.connect("199.xxx.xxx.xxx", port);` line before `client.authPublickey(username, keys);` or you will not connect... – seinecle Oct 03 '18 at 10:39
1

I just had this issue as well. I ended up changing

client.authPublickey(user, "id_rsa.pub")

to

client.authPublickey(user, client.loadKeys("id_rsa"))
sirolf2009
  • 819
  • 8
  • 15