package dcj.examples.security;
import java.lang.*;
import java.net.*;
import java.io.*;
import java.security.*;
public class CertAgent extends SimpleAgent {
Identity remoteAgent = null;
public CertAgent(String host, int port)
throws IllegalArgumentException {
super(host, port);
DataInputStream din = new DataInputStream(inStream);
// Try to authenticate the remote agent
try {
String agentId = din.readUTF();
int sigLen = din.readInt();
byte[] sigData = new byte[sigLen];
din.readFully(sigData);
if (!authenticate(agentId, sigData)) {
// Failed to authenticate, write error message, close socket and
// return
System.out.println("Failed to authenticate remote agent " + agentId);
closeConnection();
}
else {
// Remote agent is authenticated, first message is a welcome
addMsg("HELLO " + agentId);
}
}
catch (Exception e) {
closeConnection();
}
}
protected boolean authenticate(String id, byte[] sigMsg) {
boolean success = false;
PublicKey key = lookupKey(id);
try {
// Set up a signature with the agent's public key
Signature sig = Signature.getInstance("RSA");
sig.initVerify(key);
// Try to verify the signature message from the agent
sig.update(id.getBytes());
success = sig.verify(sigMsg);
if (success) {
// Agent checks out, so initialize an identity for it
remoteAgent = new Identity(id);
remoteAgent.setPublicKey(key);
}
}
catch (Exception e) {}
return success;
}
}
|