The Maverick Legacy Client API now contains an Agent implementation that allows you to load and store keys for use in authentication. The Agent is typically used by users to cut down the number of times they have to enter their passphrase. The agent loads the key once and makes it available for authentication attempts for the lifetime of the agent.
The Code
To setup an agent you need to create an SshAgentSocketListener to host requests for key services. Using the following will start the agent on a random port.
SshAgentSocketListener agentListener = new SshAgentSocketListener("localhost:0", new KeyStore()); agentListener.start();
This sets up a socket with a new KeyStore that you can now connect to and add keys. To connect to the agent you must use the SshAgentClient.
SshAgentClient agentClient = SshAgentClient.connectLocalAgent("Test", agentListener.getLocation(), AgentSocketType.TCPIP);
Once you have an SshAgentClient running you can add keys as follows:
SshPrivateKeyFile pkfile = SshPrivateKeyFileFactory.parse(
new FileInputStream(reader.readLine())); SshKeyPair pair; if(pkfile.isPassphraseProtected()) { System.out.print("Passphrase: "); pair = pkfile.toKeyPair(reader.readLine()); } else { pair = pkfile.toKeyPair(null); }
agentClient.addKey(pair.getPrivateKey(), pair.getPublicKey(),
"Key loaded for Agent example", new KeyConstraints());
Then simply setup your Maverick Legacy Client to authenticate with the Ssh2AgentAuthentication implementation
Ssh2AgentAuthentication pk = new Ssh2AgentAuthentication(agentClient);
if(ssh.authenticate(pk)!=SshAuthentication.COMPLETE) {
throw new Exception("Agent authentication failed");
}
The obvious implications of this is that you can have one process host the keys with an SshAgentSocketListener and then many processes using SshAgentClient to authenticate their connections.