|
Olá Alexandre,
Segue anexado vários códigos-fontes em
Java que usam sockets c/ SSL.
Valew !
Andrews Sobral
IT-Integration (www.itin.com.br)
Programador em Java e PHP
|
AuthenticationException.class
Description: Binary data
/**
* AuthenticationException
*
* Exception to throw if SSL Authentication fails.
*/
public class AuthenticationException extends Exception {
public AuthenticationException() {
super();
}
public AuthenticationException(String info) {
super(info);
}
}
ExampleAction.class
Description: Binary data
HamletAuthenticator.class
Description: Binary data
import javax.net.ssl.*;
import javax.security.cert.*;
/**
* HamletAuthenticator
*
* This class is an implementation of the SSLAuthenticator
* interface, and provides a mechanism for checking that the
* certificate used in SSLAuthentication is for an entity
* with the Common Name of Hamlet.
*
* Note that in the setup of the SSL Server, care should be taken
* to only allow specific CAs that will check the identity of an
* entity before granting a certificate with the Common Name of
* Hamlet.
*/
public class HamletAuthenticator implements SSLAuthenticator {
private SSLSession mSession;
public HamletAuthenticator (SSLSession session) {
mSession = session;
}
public void checkPermission() throws AuthenticationException {
System.out.println(mSession.getCipherSuite());
X509Certificate[] certChain = null;
try {
// Get the cert chain
certChain = mSession.getPeerCertificateChain();
} catch (SSLPeerUnverifiedException spue) {
// There isn't one!
throw new AuthenticationException("Peer unverified");
}
// Get the client's certificate
X509Certificate clientCert = certChain[0];
// Get the Principal corresponding to the client
java.security.Principal client = clientCert.getSubjectDN();
// Get the name of the client
String name = client.getName();
// The name should start with "CN=Hamlet,". If not,
// the user should not be allowed in.
if (name.indexOf("CN=Hamlet,")!=0) {
throw new AuthenticationException("Peer is not Hamlet");
}
//System.out.println("Client name: " + name);
}
}
HTTPSAuthServer.class
Description: Binary data
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
/**
* HTTPSAuthServer
*
* A very simple HTTPS Server, using the JSSE.
* It returns a success message over HTTPS.
*
* This version has been altered to require client authentication,
* through the use of a programmable Authenticator.
*
* In order to run this example, you will need to set the
* following System properties on the command-line:
*
* javax.net.ssl.keyStore
* javax.net.ssl.keyStorePassword
* javax.net.ssl.trustStore
* javax.net.ssl.trustStorePassword
*
* Here's an example (enter all on one line):
*
* java -Djavax.net.ssl.keyStore=.keystore
* -Djavax.net.ssl.keyStorePassword=password
* -Djavax.net.ssl.trustStore=.truststore
* -Djavax.net.ssl.trustStorePassword=password
* HTTPSServer
*
*/
public class HTTPSAuthServer {
public static void main(String[] args) throws IOException {
// First we need a SocketFactory that will create
// SSL server sockets.
SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
SSLServerSocket ss = (SSLServerSocket)ssf.createServerSocket(8080);
// Require client authentication
ss.setNeedClientAuth(true);
// Keep on accepting connections forever
while (true) {
try {
Socket s = ss.accept();
boolean allowed = false;
SSLSession session = ((SSLSocket)s).getSession();
// Check the client's authentication with the HamletAuthenticator.
// If we wanted to use a different Authenticator, we could just
// replace this line.
SSLAuthenticator authenticator = new HamletAuthenticator(session);
try {
authenticator.checkPermission();
allowed = true;
} catch (AuthenticationException ae) {
allowed = false;
System.out.println("Client denied access: "+ae);
}
// Get the input and output streams. These will be
// encrypted transparently.
OutputStream out = s.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
// Read through the input from the client,
// and display it to the screen.
String line = null;
while (((line = in.readLine())!= null) && (!("".equals(line)))) {
System.out.println(line);
}
System.out.println("");
// Construct a response
StringBuffer buffer = new StringBuffer();
buffer.append("<HTML>\n");
buffer.append("<HEAD><TITLE>HTTPS Server</TITLE></HEAD>\n");
buffer.append("<BODY>\n");
if (allowed) {
buffer.append("<H1>Success!</H1>\nWelcome, Hamlet.\n");
} else {
buffer.append("<H1>Failure!</H1>\nYou are not Hamlet.\n");
}
buffer.append("</BODY>\n");
buffer.append("</HTML>\n");
// HTTP requires a content-length.
String string = buffer.toString();
byte[] data = string.getBytes();
out.write("HTTP/1.0 200 OK\n".getBytes());
out.write(new String("Content-Length: "+data.length+"\n").getBytes());
out.write("Content-Type: text/html\n\n".getBytes());
out.write(data);
out.flush();
// Close the streams and socket.
out.close();
in.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
HTTPSClient.class
Description: Binary data
import java.io.*; import java.net.*; /** * HTTPSClient * * This class fetches an HTTPS url to illustrate * the use of HTTPS on the client. It requests * a URL and prints its content to standard out. * * If an argument is passed, it will use it as the URL * to connect to. Example: * * java HTTPSClient https://www.verisign.com * */ public class HTTPSClient { public static void main (String[] args) throws Exception { /** Begin by setting the URL handler so that it * will find the HTTPS classes. * This could also be done by setting the property * at runtime with: * * java -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol */ System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); // Here's the default URL String urlString = "https://www.verisign.com/"; // If an argument has been passed, use it // as the url to attach to. if (args.length > 0) { urlString = args[0]; } URL url = new URL(urlString); BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); } }
HTTPSServer.class
Description: Binary data
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class HTTPSServer {
public static void main(String[] args) throws IOException {
// First we need a SocketFactory that will create
// SSL server sockets.
SSLServerSocketFactory ssf =
(SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
ServerSocket ss = ssf.createServerSocket(8080);
// Keep on accepting connections forever
while (true) {
try {
Socket s = ss.accept();
// Get the input and output streams. These will be
// encrypted transparently.
OutputStream out = s.getOutputStream();
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
// Read through the input from the client,
// and display it to the screen.
String line = null;
while (((line = in.readLine())!= null)
&& (!("".equals(line)))) {
System.out.println(line);
}
System.out.println("");
// Construct a response
StringBuffer buffer = new StringBuffer();
buffer.append("<HTML>\n");
buffer.append(
"<HEAD><TITLE>HTTPS Server</TITLE></HEAD>\n");
buffer.append("<BODY>\n");
buffer.append("<H1>Success!</H1>\n");
buffer.append("</BODY>\n");
buffer.append("</HTML>\n");
// HTTP requires a content-length.
String string = buffer.toString();
byte[] data = string.getBytes();
out.write("HTTP/1.0 200 OK\n".getBytes());
out.write(new String(
"Content-Length: "+data.length+"\n").getBytes());
out.write("Content-Type: text/html\n\n".getBytes());
out.write(data);
out.flush();
// Close the streams and socket.
out.close();
in.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
} // End of while-loop
} // End of main()
}
HTTPSServerWithAuth.class
Description: Binary data
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
/**
* HTTPSServer
*
* A very simple HTTPS Server, using the JSSE.
* It returns a success message over HTTPS.
*
* This version has been altered to require client authentication.
*
* In order to run this example, you will need to set the
* following System properties on the command-line:
*
* javax.net.ssl.keyStore
* javax.net.ssl.keyStorePassword
* javax.net.ssl.trustStore
* javax.net.ssl.trustStorePassword
*
* Here's an example (enter all on one line):
*
* java -Djavax.net.ssl.keyStore=.keystore
* -Djavax.net.ssl.keyStorePassword=password
* -Djavax.net.ssl.trustStore=.truststore
* -Djavax.net.ssl.trustStorePassword=password
* HTTPSServer
*
*/
public class HTTPSServerWithAuth {
public static void main(String[] args) throws IOException {
// First we need a SocketFactory that will create
// SSL server sockets.
SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
SSLServerSocket ss = (SSLServerSocket)ssf.createServerSocket(8080);
// Require client authentication
ss.setNeedClientAuth(true);
// Keep on accepting connections forever
while (true) {
try {
Socket s = ss.accept();
// Get the input and output streams. These will be
// encrypted transparently.
OutputStream out = s.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
// Read through the input from the client,
// and display it to the screen.
String line = null;
while (((line = in.readLine())!= null) && (!("".equals(line)))) {
System.out.println(line);
}
System.out.println("");
// Construct a response
StringBuffer buffer = new StringBuffer();
buffer.append("<HTML>\n");
buffer.append("<HEAD><TITLE>HTTPS Server</TITLE></HEAD>\n");
buffer.append("<BODY>\n");
buffer.append("<H1>Success!</H1>\n");
buffer.append("</BODY>\n");
buffer.append("</HTML>\n");
// HTTP requires a content-length.
String string = buffer.toString();
byte[] data = string.getBytes();
out.write("HTTP/1.0 200 OK\n".getBytes());
out.write(new String("Content-Length: "+data.length+"\n").getBytes());
out.write("Content-Type: text/html\n\n".getBytes());
out.write(data);
out.flush();
// Close the streams and socket.
out.close();
in.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
JAASAuthorizationExample.class
Description: Binary data
import java.security.*;
import java.util.*;
import javax.security.auth.*;
import javax.security.auth.login.*;
public class JAASAuthorizationExample {
private static final String GENERIC_SECRET_TEXT = "secret word";
private static final String TEST_USER_SECRET_TEXT = "squeamish ossifrage";
/**
* We return a different string based on the user.
*/
public static String getSecretText() {
AccessControlContext context = AccessController.getContext();
Subject subject = Subject.getSubject(context);
if (subject == null) {
return GENERIC_SECRET_TEXT;
}
// Get all the principals that are instances of our PrincipalImpl class.
Set principals = subject.getPrincipals();
Iterator iterator = principals.iterator();
while (iterator.hasNext()) {
PrincipalImpl principal = (PrincipalImpl)iterator.next();
if (principal.getName().equals("testuser")) {
return TEST_USER_SECRET_TEXT;
}
}
return GENERIC_SECRET_TEXT;
}
/**
* Try to log a user in and then run ExampleAction.
*/
public static void main(String[] args) {
if (args.length != 2) {
System.err.println
("Usage: java JAASSampleApp username password");
System.exit(1);
}
LoginContext loginContext = null;
String username = args[0];
char[] password = args[1].toCharArray();
try {
loginContext = new LoginContext(
"Sample", new UsernamePasswordCallbackHandler
(username, password));
loginContext.login();
System.out.println("\nLogin succeeded");
} catch (LoginException le) {
System.out.println("\nLogin failed");
}
// Now we're logged in, so we can get the current subject.
Subject subject = loginContext.getSubject();
// Perform the example action as the authenticated subject.
subject.doAs(subject, new ExampleAction());
}
}
class ExampleAction implements PrivilegedAction {
public ExampleAction() {
}
public Object run() {
System.out.println("Secret text: " + JAASAuthorizationExample.getSecretText());
return null;
}
}
JAASSampleApp.class
Description: Binary data
import javax.security.auth.*;
import javax.security.auth.login.*;
import java.security.*;
public class JAASSampleApp extends Object {
public static void main(String[] args)
throws Exception {
if (args.length != 2) {
System.err.println
("Usage: java JAASSampleApp username password");
System.exit(1);
}
String username = args[0];
char[] password = args[1].toCharArray();
LoginContext loginContext = new LoginContext(
"Sample", new UsernamePasswordCallbackHandler
(username, password));
loginContext.login();
// Now we're logged in, so we can get the current subject.
Subject subject = loginContext.getSubject();
// Display the subject
System.out.println(subject);
}
}
PasswordLoginModule.class
Description: Binary data
import javax.security.auth.*;
import javax.security.auth.spi.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import java.io.*;
import java.security.*;
import java.util.*;
/**
* Login module that checks a username and password.
*/
public class PasswordLoginModule implements LoginModule {
private Subject mSubject;
private CallbackHandler mCallbackHandler;
private boolean mLoginSucceeded = false;
private boolean mCommitSucceeded = false;
private String mUsername;
private char[] mPassword;
private Principal mPrincipal;
/**
* Initialize this login module.
*/
public void initialize(Subject subject,CallbackHandler callbackHandler,
Map sharedState,Map options) {
mSubject = subject;
mCallbackHandler = callbackHandler;
mLoginSucceeded = false;
mCommitSucceeded = false;
mUsername = null;
clearPassword();
// We do not support shared state or options in this simple example.
}
/**
* Attempt to log a user in.
*
* In this sample, we accept:
* username: "testuser"
* password: "sasquatch"
*/
public boolean login() throws LoginException {
if (mCallbackHandler == null) {
throw new LoginException("No CallbackHandler defined");
}
// create two callbacks: one for username, one for password.
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("Username");
callbacks[1] = new PasswordCallback("Password", false);
try {
// Call the callback handler to fill out information
mCallbackHandler.handle(callbacks);
mUsername = ((NameCallback)callbacks[0]).getName();
char[] tempPassword = ((PasswordCallback)callbacks[1]).getPassword();
mPassword = new char[tempPassword.length];
System.arraycopy(tempPassword, 0, mPassword, 0, tempPassword.length);
// Clear out the password in the callback
((PasswordCallback)callbacks[1]).clearPassword();
} catch (IOException ioe) {
throw new LoginException(ioe.toString());
} catch (UnsupportedCallbackException uce) {
throw new LoginException(uce.toString());
}
// Now we need to check for the validity of the username and password.
// If we were using a database or a file, we would check against
// that resource.
if (
"testuser".equals(mUsername) &&
mPassword.length == 9 &&
mPassword[0] == 's' &&
mPassword[1] == 'a' &&
mPassword[2] == 's' &&
mPassword[3] == 'q' &&
mPassword[4] == 'u' &&
mPassword[5] == 'a' &&
mPassword[6] == 't' &&
mPassword[7] == 'c' &&
mPassword[8] == 'h'
) {
// username and password are correct.
mLoginSucceeded = true;
return true;
} else {
// Authentication failed. Clean up state and throw exception.
mLoginSucceeded = false;
mUsername = null;
clearPassword();
throw new FailedLoginException("Incorrect Password");
}
}
/**
* This is called if all logins succeeded.
*/
public boolean commit() throws LoginException {
if (mLoginSucceeded == false) {
return false;
}
// Login succeeded, so create a Principal and add it to the Subject.
mPrincipal = new PrincipalImpl(mUsername);
if (!(mSubject.getPrincipals().contains(mPrincipal))) {
mSubject.getPrincipals().add(mPrincipal);
}
// If we wanted our Subject to contain our credentials,
// now would be the time to add them. We don't need to
// do that for this simple example however.
// Clear out the username and password.
mUsername = null;
clearPassword();
mCommitSucceeded = true;
return true;
}
/**
* Called if overall login failed.
*/
public boolean abort() throws LoginException {
// If login failed, return false;
if (mLoginSucceeded == false) {
return false;
} else if (mLoginSucceeded == true && mCommitSucceeded == false) {
// Our login succeeded, but others failed.
mLoginSucceeded = false;
mUsername = null;
clearPassword();
mPrincipal = null;
} else {
// We committed, but someone else's failed.
logout();
}
return true;
}
/**
* Logout the user.
*/
public boolean logout() throws LoginException {
// Need to remove the principal from the Subject.
mSubject.getPrincipals().remove(mPrincipal);
mLoginSucceeded = false;
mCommitSucceeded = false;
mUsername = null;
clearPassword();
mPrincipal = null;
return true;
}
/**
* Clear out the password.
*/
private void clearPassword() {
if (mPassword == null) {
return;
}
for (int i=0;i<mPassword.length;i++) {
mPassword[i] = ' ';
}
mPassword = null;
}
}
PrincipalImpl.class
Description: Binary data
import java.io.Serializable;
import java.security.Principal;
/**
* Implementation of the Principal interface.
*/
public class PrincipalImpl implements Principal, Serializable {
private String mName;
public PrincipalImpl(String name) {
mName = name;
}
public boolean equals(java.lang.Object obj) {
if (!(obj instanceof PrincipalImpl)) {
return false;
}
PrincipalImpl other = (PrincipalImpl)obj;
if (mName.equals(other.getName())) {
return true;
}
return false;
}
public java.lang.String getName() {
return mName;
}
public int hashCode() {
return mName.hashCode();
}
public java.lang.String toString() {
return getName();
}
}
RMISSLClientSocketFactory.class
Description: Binary data
import java.io.*;
import java.net.*;
import java.rmi.server.*;
import javax.net.ssl.*;
public class RMISSLClientSocketFactory
implements RMIClientSocketFactory, Serializable {
public Socket createSocket(String host, int port)
throws IOException
{
SSLSocketFactory sf = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket)sf.createSocket(host, port);
return socket;
}
}
RMISSLServerSocketFactory.class
Description: Binary data
import java.io.*;
import java.net.*;
import java.rmi.server.*;
import javax.net.ssl.*;
public class RMISSLServerSocketFactory
implements RMIServerSocketFactory, Serializable {
public ServerSocket createServerSocket(int port)
throws IOException
{
SSLServerSocketFactory ssf = (SSLServerSocketFactory)
SSLServerSocketFactory.getDefault();
SSLServerSocket serverSocket = (SSLServerSocket)ssf.createServerSocket(port);
serverSocket.setNeedClientAuth(true);
return serverSocket;
}
}
SSLAuthenticator.class
Description: Binary data
/**
* SSLAuthenticator
*
* Defines an interface for determining if a client
* in an SSL session should be allowed
* to connect.
*/
public interface SSLAuthenticator {
public void checkPermission() throws AuthenticationException;
}
SSLSocketClient.class
Description: Binary data
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
/**
* SSLSocketClient
*
* This is a demonstration of using SSL over simple
* socket communication.
*
* The client opens a connection to localhost:8080 using SSL,
* and then sends each character typed to the other end,
* encrypted through SSL.
*/
public class SSLSocketClient {
private static final String HOST = "localhost";
private static final int PORT = 8080;
public static void main(String[] args) throws Exception {
// First we need a SocketFactory that will create
// SSL sockets.
SSLSocketFactory sf = (SSLSocketFactory)SSLSocketFactory.getDefault();
Socket s = sf.createSocket(HOST,PORT);
// Get the input and output streams. These will be
// encrypted transparently.
OutputStream out = s.getOutputStream();
out.write("\nConnection established.\n\n".getBytes());
System.out.print("\nConnection established.\n\n");
// Now send everything the user types
int theCharacter=0;
theCharacter = System.in.read();
while (theCharacter != '~') // The '~' is an escape character to exit
{
out.write(theCharacter);
out.flush();
theCharacter = System.in.read();
}
out.close();
s.close();
}
}
SSLSocketServer.class
Description: Binary data
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
/**
* SSLSocketServer
*
* This is a demonstration of using SSL over simple
* socket communication.
*
* The server opens a server socket on port8080 using SSL,
* and waits for a connection. Once a connection is made,
* it displays everything sent to the server.
*/
public class SSLSocketServer {
private static final int PORT = 8080;
public static void main (String[] args) throws Exception {
// First we need a SocketFactory that will create
// SSL server sockets.
SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
ServerSocket ss = ssf.createServerSocket(PORT);
// Wait for a connection
Socket s = ss.accept();
// Get the input stream. These will be
// encrypted transparently.
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
// Read through the input from the client,
// and display it to the screen.
String line = null;
while (((line = in.readLine())!= null)) {
System.out.println(line);
}
in.close();
s.close();
}
}
SunSSLSocketClient.class
Description: Binary data
import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.ssl.*;
import com.sun.net.ssl.*;
/**
* SSLSocketClient
*
* This is a demonstration of using SSL over simple
* socket communication.
*
* The client opens a connection to localhost:8080 using SSL,
* and then sends each character typed to the other end,
* encrypted through SSL.
*
* This example uses the com.sun.net.ssl classes to avoid
* having to pass keystore information on the command-line.
*/
public class SunSSLSocketClient {
private static final String HOST = "localhost";
private static final int PORT = 8080;
public static void main(String[] args) throws Exception {
// First we need to load a keystore
char[] passphrase = "sasquatch".toCharArray();
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream(".keystore"), passphrase);
// Now we initialize a TrustManagerFactory with the KeyStore
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(keystore);
// Now we create an SSLContext and initialize it with
// TrustManagers from the TrustManagerFactory
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = tmf.getTrustManagers();
context.init(null, trustManagers, null);
// First we need a SocketFactory that will create
// SSL sockets.
SSLSocketFactory sf = context.getSocketFactory();
// Open a connection
Socket s = sf.createSocket(HOST,PORT);
// Get the input and output streams. These will be
// encrypted transparently.
OutputStream out = s.getOutputStream();
out.write("\nConnection established.\n\n".getBytes());
System.out.print("\nConnection established.\n\n");
// Now send everything the user types
int theCharacter=0;
theCharacter = System.in.read();
while (theCharacter != '~') // The '~' is an escape character to exit
{
out.write(theCharacter);
out.flush();
theCharacter = System.in.read();
}
out.close();
s.close();
}
}
SunSSLSocketServer.class
Description: Binary data
import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.ssl.*;
import com.sun.net.ssl.*;
/**
* SSLSocketServer
*
* This is a demonstration of using SSL over simple
* socket communication.
*
* The server opens a server socket on port8080 using SSL,
* and waits for a connection. Once a connection is made,
* it displays everything sent to the server.
*
* This example uses the com.sun.net.ssl classes to open
* a keystore for use by the SSLSockets.
*/
public class SunSSLSocketServer {
private static final int PORT = 8080;
public static void main (String[] args) throws Exception {
// First we need to load a keystore
char[] passphrase = "sasquatch".toCharArray();
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream(".keystore"), passphrase);
// Now we initialize a KeyManagerFactory with the KeyStore
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, passphrase);
// Now we create an SSLContext and initialize it with
// KeyManagers from the KeyManagerFactory
SSLContext context = SSLContext.getInstance("TLS");
KeyManager[] keyManagers = kmf.getKeyManagers();
context.init(keyManagers, null, null);
// First we need a SocketFactory that will create
// SSL server sockets.
SSLServerSocketFactory ssf = context.getServerSocketFactory();
ServerSocket ss = ssf.createServerSocket(PORT);
// Wait for a connection
Socket s = ss.accept();
// Get the input stream. These will be
// encrypted transparently.
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
// Read through the input from the client,
// and display it to the screen.
String line = null;
while (((line = in.readLine())!= null)) {
System.out.println(line);
}
in.close();
s.close();
}
}
TimeClient.class
Description: Binary data
import java.rmi.*;
public class TimeClient {
private static String host = "localhost";
public static void main (String[] args) {
// If we received any arguments, then the first one
// is the host to connect to.
if (args.length > 0) {
host = args[0];
}
if (System.getSecurityManager()==null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
TimeServer remoteTimeServer = (TimeServer)Naming.lookup("//"+host+"/TimeServer");
System.out.println(remoteTimeServer.getTime());
} catch (Exception e) {
e.printStackTrace();
}
}
}
TimeServer.class
Description: Binary data
import java.rmi.*;
import java.util.*;
public interface TimeServer extends Remote {
public Date getTime() throws RemoteException;
}
TimeServerImpl.class
Description: Binary data
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
public class TimeServerImpl extends UnicastRemoteObject implements TimeServer {
public TimeServerImpl() throws RemoteException {
super();
}
public Date getTime() {
Date theTime = new Date();
System.out.println("Time requested: "+theTime);
return theTime;
}
public static void main (String[] args) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
TimeServerImpl self = new TimeServerImpl();
Naming.rebind("//localhost/TimeServer", self);
System.out.println("TimeServer bound in registry");
} catch (Exception e) {
System.out.println("Error binding to the registry:");
e.printStackTrace();
}
}
}
TimeServerImpl_Stub.class
Description: Binary data
TimeServerSSLImpl.class
Description: Binary data
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
public class TimeServerSSLImpl extends UnicastRemoteObject implements TimeServer {
public TimeServerSSLImpl() throws RemoteException {
super(0, new RMISSLClientSocketFactory(),
new RMISSLServerSocketFactory());
}
public Date getTime() {
Date theTime = new Date();
System.out.println("Time requested: "+theTime);
return theTime;
}
public static void main (String[] args) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
TimeServerSSLImpl self = new TimeServerSSLImpl();
Naming.rebind("//localhost/TimeServer", self);
System.out.println("TimeServer bound in registry");
} catch (Exception e) {
System.out.println("Error binding to the registry:");
e.printStackTrace();
}
}
}
TimeServerSSLImpl_Stub.class
Description: Binary data
UsernamePasswordCallbackHandler.class
Description: Binary data
import java.io.*;
import java.security.*;
import javax.security.auth.*;
import javax.security.auth.callback.*;
/**
* CallbackHandler that handles usernames and passwords.
*/
public class UsernamePasswordCallbackHandler
implements CallbackHandler {
private String mUsername;
private char[] mPassword;
/**
* We need a stateful handler to return the username and password.
*/
public UsernamePasswordCallbackHandler(String username, char[] password) {
mUsername = username;
mPassword = password;
}
/**
* Handle each callback. We support only NameCallbacks
* and PasswordCallbacks.
*/
public void handle(Callback[] callbacks)
throws UnsupportedCallbackException {
// Step through the callbacks
for(int i=0;i<callbacks.length;i++) {
Callback callback = callbacks[i];
// Handle the callback based on its type.
if (callback instanceof NameCallback) {
NameCallback nameCallback = (NameCallback)callback;
nameCallback.setName(mUsername);
} else if (callback instanceof PasswordCallback) {
PasswordCallback passwordCallback = (PasswordCallback)callback;
passwordCallback.setPassword(mPassword);
} else {
throw new UnsupportedCallbackException(callback, "Unsupported Callback Type");
}
}
}
}
--------------------------------------------------------------------- Para cancelar a subscri��o, envie mensagem para: [EMAIL PROTECTED] Para comandos adicionais, envie mensagem para: [EMAIL PROTECTED]
