FileDocCategorySizeDatePackage
AuthAgent.javaAPI DocExample2268Tue Jan 20 21:00:26 GMT 1998dcj.examples.security

AuthAgent.java

package dcj.examples.security;

import java.lang.*;
import java.net.*;
import java.io.*;
import java.security.*;
import java.security.acl.*;

/**
 * Source code from "Java Distributed Computing", by Jim Farley.
 *
 * Class: AuthAgent
 * Example: 5-3
 * Description: An agent that authenticates incoming requests by requiring
 *      a digital signature.
 */

public class AuthAgent extends SimpleAgent {

  Identity remoteAgent = null;

  public AuthAgent(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 dataLen = din.readInt();
      byte[] data = new byte[dataLen];
      din.read(data);
      int sigLen = din.readInt();
      byte[] sig = new byte[sigLen];
      din.read(sig);

      if (!authenticate(agentId, data, sig)) {
        // 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[] data, byte[] sig) {
    boolean success = false;
    PublicKey key = lookupKey(id);
    try {
      // Set up a signature with the agent's public key
      Signature agentSig = Signature.getInstance(key.getAlgorithm());
      agentSig.initVerify(key);
      // Try to verify the signature message from the agent
      agentSig.update(data);
      success = agentSig.verify(sig);

      if (success) {
        // Agent checks out, so initialize an identity for it
        remoteAgent = null; //new Signer(id);
        remoteAgent.setPublicKey(key);
      }
    }
    catch (Exception e) {
      System.err.println("Failed to verify agent signature.");
      success = false;
    }

    return success;
  }

  protected PublicKey lookupKey(String name) {
    return null;
  }
}