Skip to content

Instantly share code, notes, and snippets.

@jdennaho
Last active April 18, 2021 14:23
Show Gist options
  • Save jdennaho/5492130 to your computer and use it in GitHub Desktop.
Save jdennaho/5492130 to your computer and use it in GitHub Desktop.
How to use a PublickeyAuthenticator with Apache MINA SSHD
private static final String knownKey = "{SSH2.PUBLIC.KEY}";
public void start() {
SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(22999);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
public boolean authenticate(String username, PublicKey key, ServerSession session) {
if(key instanceof RSAPublicKey) {
String s1 = new String(encode((RSAPublicKey) key));
String s2 = new String(Base64.decodeBase64(knownKey.getBytes()));
return s1.equals(s2); //Returns true if the key matches our known key, this allows auth to proceed.
}
return false; //Doesn't handle other key types currently.
}
});
}
//Converts a Java RSA PK to SSH2 Format.
public static byte[] encode(RSAPublicKey key) {
try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
byte[] name = "ssh-rsa".getBytes("US-ASCII");
write(name, buf);
write(key.getPublicExponent().toByteArray(), buf);
write(key.getModulus().toByteArray(), buf);
return buf.toByteArray();
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
private static void write(byte[] str, OutputStream os) throws IOException {
for (int shift = 24; shift >= 0; shift -= 8)
os.write((str.length >>> shift) & 0xFF);
os.write(str);
}
@darcyllingyan
Copy link

Hi,
I have a question, whether the knownKey is the public keys in ~/.ssh/authorized_keys?
When client use ssh -i privateFile to connect the Server, how does the client find the publicKey and pass it to the server, i.e., the parameter of Public Key in the function: public boolean authenticate(String username, PublicKey key, ServerSession session), thanks very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment