kpg.initialize(1024);
KeyPair kp = kpg.generateKeyPair();
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(kp.getPrivate());
final PublicKey publickey = kp.getPublic();
final SSHPublicKey pkey = new SSHRSAPublicKey(
((RSAPublicKey)kp.getPublic()).getModulus(),
((RSAPublicKey)kp.getPublic()).getPublicExponent());
UserAuthPublicKeyOk uapkok = new UserAuthPublicKeyOk();
uapkok.setAlgorithm("ssh-rsa");
uapkok.setPubkey(pkey.encode());
UserAuthSuccessMessage uasm = new UserAuthSuccessMessage();
when(transport.readMessage("publickey")).thenReturn(uapkok).thenReturn(uasm);
when(transport.getSessionId()).thenReturn(new byte[20]);
// When
AuthenticationResult res = authMgr.authenticate("user", pkey, signature);
// Then
InOrder inorder = inOrder(transport);
inorder.verify(transport, times(1)).writeMessage(any(SSHMessage.class));
inorder.verify(transport, times(1)).writeMessage(any(SSHMessage.class));
inorder.verify(transport, times(1)).writeMessage(argThat(new ArgumentMatcher<SSHMessage>() {
@Override
public boolean matches(Object arg)
{
UserAuthRequestMessage msg = (UserAuthRequestMessage)arg;
assertTrue(msg.getAuthenticationData() instanceof PublicKeyMethodData);
assertEquals("publickey", msg.getMethod());
PublicKeyMethodData md = (PublicKeyMethodData)msg.getAuthenticationData();
assertEquals("ssh-rsa", md.getAlgorithm());
assertArrayEquals(pkey.encode(), md.getPubkey());
assertNotNull(md.getSignature());
try {
Signature verify = Signature.getInstance("SHA1withRSA");
verify.initVerify(publickey);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Utils.encodeBytes(out, new byte[20]);
out.write((byte)50);
Utils.encodeString(out, "user");
Utils.encodeString(out, "ssh-connection");
Utils.encodeString(out, "publickey");
Utils.encodeBoolean(out, true);
Utils.encodeString(out, "ssh-rsa");
Utils.encodeBytes(out, pkey.encode());
verify.update(out.toByteArray());
assertTrue("Signature should be verified", verify.verify(md.getSignature()));
} catch (InvalidKeyException ike) {
fail(ike.getMessage());
} catch (NoSuchAlgorithmException nsae) {