-
-
Save jonentropy/503f0a3c44058c2e2fa1 to your computer and use it in GitHub Desktop.
How to use a PublickeyAuthenticator with Apache MINA SSHD
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment