1 package org.columba.ristretto.auth.mechanism; 2 3 import java.io.IOException ; 4 import java.util.Hashtable ; 5 import java.util.logging.Logger ; 6 7 import javax.security.auth.callback.Callback ; 8 import javax.security.auth.callback.CallbackHandler ; 9 import javax.security.auth.callback.NameCallback ; 10 import javax.security.auth.callback.PasswordCallback ; 11 import javax.security.auth.callback.TextOutputCallback ; 12 import javax.security.auth.callback.UnsupportedCallbackException ; 13 14 import org.columba.ristretto.auth.AuthenticationException; 15 import org.columba.ristretto.auth.AuthenticationMechanism; 16 import org.columba.ristretto.auth.AuthenticationServer; 17 18 public class CramMD5Mechanism implements AuthenticationMechanism, CallbackHandler { 19 20 21 private static final Logger LOG = Logger.getLogger("org.columba.ristretto.auth.mechanism"); 22 23 private String username; 24 private char[] password; 25 26 SaslWrapper sasl; 27 28 29 32 public void authenticate(AuthenticationServer server, String user, 33 char[] password) throws IOException , AuthenticationException { 34 35 this.username = user; 36 this.password = password; 37 try { 38 sasl = new SaslWrapper(); 39 sasl.createClient(new String []{"CRAM-MD5"}, 40 user, server.getService(), server.getHostName(), 41 new Hashtable (), this); 42 byte[] serverChallenge = server.authReceive(); 43 LOG.fine(new String (serverChallenge)); 44 45 byte[] response = sasl.evaluateChallenge(serverChallenge); 46 LOG.fine(new String (response)); 47 server.authSend(response); 48 } catch (Exception e) { 49 if( e.getCause() instanceof IOException ) throw (IOException )e.getCause(); 50 else throw new AuthenticationException(e.getCause()); 51 } 52 } 53 54 57 public void handle(Callback [] callbacks) throws IOException , UnsupportedCallbackException { 58 for (int i = 0; i < callbacks.length; i++) { 59 if (callbacks[i] instanceof TextOutputCallback ) { 60 TextOutputCallback toc = (TextOutputCallback ) callbacks[i]; 62 switch (toc.getMessageType()) { 63 case TextOutputCallback.INFORMATION : 64 LOG.info(toc.getMessage()); 65 break; 66 case TextOutputCallback.ERROR : 67 LOG.severe(toc.getMessage()); 68 break; 69 case TextOutputCallback.WARNING : 70 LOG.warning(toc.getMessage()); 71 break; 72 default : 73 LOG.fine(toc.getMessage()); 74 } 75 } else if (callbacks[i] instanceof NameCallback ) { 76 NameCallback nc = (NameCallback ) callbacks[i]; 77 nc.setName(username); 78 } else if (callbacks[i] instanceof PasswordCallback ) { 79 PasswordCallback pc = (PasswordCallback ) callbacks[i]; 80 pc.setPassword(password); 81 } else if (sasl.handle(callbacks[i]) ) { 82 } else { 83 throw new UnsupportedCallbackException (callbacks[i], 84 "Unrecognized Callback"); 85 } 86 } 87 } 88 89 } 90 | Popular Tags |