Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Licensed to the Apache Software Foundation (ASF) under one or more
    * contributor license agreements.  See the NOTICE file distributed with
    * this work for additional information regarding copyright ownership.
    * The ASF licenses this file to You under the Apache License, Version 2.0
    * (the "License"); you may not use this file except in compliance with
    * the License.  You may obtain a copy of the License at
    * 
    *      http://www.apache.org/licenses/LICENSE-2.0
   * 
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  
  package org.apache.catalina.realm;
  
  
  import static org.jboss.web.CatalinaMessages.MESSAGES;
  
  
  
Simple implementation of Realm that reads an XML file to configure the valid users, passwords, and roles. The file format (and default file location) are identical to those currently supported by Tomcat 3.X.

Author(s):
Craig R. McClanahan
Version:
$Revision: 1943 $ $Date: 2012-02-03 16:22:01 +0100 (Fri, 03 Feb 2012) $
  
  
  public abstract class RealmBase
      implements LifecycleRealmMBeanRegistration {
  
      // ----------------------------------------------------- Instance Variables
  

    
The Container with which this Realm is associated.
  
      protected Container container = null;


    
Container log
  
      protected Logger containerLog = null;


    
Digest algorithm used in storing passwords in a non-plaintext format. Valid values are those accepted for the algorithm name by the MessageDigest class, or null if no digesting should be performed.
  
      protected String digest = null;

    
The encoding charset for the digest.
  
     protected String digestEncoding = null;


    
Descriptive information about this Realm implementation.
 
     protected static final String info =
         "org.apache.catalina.realm.RealmBase/1.0";


    
The lifecycle event support for this component.
 
     protected LifecycleSupport lifecycle = new LifecycleSupport(this);


    
The MessageDigest object for digesting user credentials (passwords).
 
     protected MessageDigest md = null;


    
The MD5 helper object for this class.
 
     protected static final MD5Encoder md5Encoder = new MD5Encoder();


    
MD5 message digest provider.
 
     protected static MessageDigest md5Helper;


    
Has this component been started?
 
     protected boolean started = false;


    
The property change support for this component.
 
     protected PropertyChangeSupport support = new PropertyChangeSupport(this);


    
Should we validate client certificate chains when they are presented?
 
     protected boolean validate = true;

    
    
The all role mode.
 
     protected AllRolesMode allRolesMode = AllRolesMode.toMode(System.getProperty("org.apache.catalina.realm.RealmBase.ALL_ROLES_MODE"
             ..));
     
 
     // ------------------------------------------------------------- Properties
 

    
Return the Container with which this Realm has been associated.
 
     public Container getContainer() {
 
         return ();
 
     }


    
Set the Container with which this Realm has been associated.

Parameters:
container The associated Container
 
     public void setContainer(Container container) {
 
         Container oldContainer = this.;
         this. = container;
         .firePropertyChange("container"oldContainerthis.);
 
     }

    
Return the all roles mode.
 
     public String getAllRolesMode() {
 
         return .toString();
 
     }


    
Set the all roles mode.
 
     public void setAllRolesMode(String allRolesMode) {
 
         this. = AllRolesMode.toMode(allRolesMode);
 
     }

    
Return the digest algorithm used for storing credentials.
 
     public String getDigest() {
 
         return ;
 
     }


    
Set the digest algorithm used for storing credentials.

Parameters:
digest The new digest algorithm
 
     public void setDigest(String digest) {
 
         this. = digest;
 
     }

    
Returns the digest encoding charset.

Returns:
The charset (may be null) for platform default
 
     public String getDigestEncoding() {
         return ;
     }

    
Sets the digest encoding charset.

Parameters:
charset The charset (null for platform default)
 
     public void setDigestEncoding(String charset) {
          = charset;
     }

    
Return descriptive information about this Realm implementation and the corresponding version number, in the format <description>/<version>.
 
     public String getInfo() {
 
         return ;
 
     }


    
Return the "validate certificate chains" flag.
 
     public boolean getValidate() {
 
         return (this.);
 
     }


    
Set the "validate certificate chains" flag.

Parameters:
validate The new validate certificate chains flag
 
     public void setValidate(boolean validate) {
 
         this. = validate;
 
     }
 
 
     // --------------------------------------------------------- Public Methods
 

    
    
Add a property change listener to this component.

Parameters:
listener The listener to add
 
     public void addPropertyChangeListener(PropertyChangeListener listener) {
 
         .addPropertyChangeListener(listener);
 
     }


    
Return the Principal associated with the specified username and credentials, if there is one; otherwise return null.

Parameters:
username Username of the Principal to look up
credentials Password or other credentials to use in authenticating this username
 
     public Principal authenticate(String usernameString credentials) {
 
         String serverCredentials = getPassword(username);
 
         boolean validated ;
         if ( serverCredentials == null ) {
             validated = false;
         } else if(hasMessageDigest()) {
             validated = serverCredentials.equalsIgnoreCase(digest(credentials));
         } else {
             validated = serverCredentials.equals(credentials);
         }
         if(! validated ) {
             if (.isTraceEnabled()) {
                 .trace(.userNotAuthenticated(username));
             }
             return null;
         }
         if (.isTraceEnabled()) {
             .trace(.userAuthenticated(username));
         }
 
         return getPrincipal(username);
     }


    
Return the Principal associated with the specified username and credentials, if there is one; otherwise return null.

Parameters:
username Username of the Principal to look up
credentials Password or other credentials to use in authenticating this username
 
     public Principal authenticate(String usernamebyte[] credentials) {
 
         return (authenticate(usernamecredentials.toString()));
 
     }


    
Return the Principal associated with the specified username, which matches the digest calculated using the given parameters using the method described in RFC 2069; otherwise return null.

Parameters:
username Username of the Principal to look up
clientDigest Digest which has been submitted by the client
nOnce Unique (or supposedly unique) token which has been used for this request
realm Realm name
md5a2 Second MD5 digest used to calculate the digest : MD5(Method + ":" + uri)
 
     public Principal authenticate(String usernameString clientDigest,
                                   String nOnceString ncString cnonce,
                                   String qopString realm,
                                   String md5a2) {
 
         String md5a1 = getDigest(usernamerealm);
         if (md5a1 == null)
             return null;
         String serverDigestValue;
         if (qop == null) {
             serverDigestValue = md5a1 + ":" + nOnce + ":" + md5a2;
         } else {
             serverDigestValue = md5a1 + ":" + nOnce + ":" + nc + ":" +
             cnonce + ":" + qop + ":" + md5a2;
         }
 
         byte[] valueBytes = null;
         if(getDigestEncoding() == null) {
             valueBytes = serverDigestValue.getBytes();
         } else {
             try {
                 valueBytes = serverDigestValue.getBytes(getDigestEncoding());
             } catch (UnsupportedEncodingException uee) {
                 throw .illegalDigestEncoding(getDigestEncoding(), uee);
             }
         }
 
         String serverDigest = null;
         // Bugzilla 32137
         synchronized() {
             serverDigest = .encode(.digest(valueBytes));
         }
 
         if (..isDebugEnabled()) {
             ..debug("Digest : " + clientDigest + " Username:" + username 
                     + " ClientSigest:" + clientDigest + " nOnce:" + nOnce 
                     + " nc:" + nc + " cnonce:" + cnonce + " qop:" + qop 
                     + " realm:" + realm + "md5a2:" + md5a2 
                     + " Server digest:" + serverDigest);
         }
         
         if (serverDigest.equals(clientDigest))
             return getPrincipal(username);
         else
             return null;
     }



    
Return the Principal associated with the specified chain of X509 client certificates. If there is none, return null.

Parameters:
certs Array of client certificates, with the first one in the array being the certificate of the client itself.
 
     public Principal authenticate(X509Certificate certs[]) {
 
         if ((certs == null) || (certs.length < 1))
             return (null);
 
         // Check the validity of each certificate in the chain
             ..debug("Authenticating client certificate chain");
         if () {
             for (int i = 0; i < certs.lengthi++) {
                 if (..isDebugEnabled())
                     ..debug(" Checking validity for '" +
                         certs[i].getSubjectDN().getName() + "'");
                 try {
                     certs[i].checkValidity();
                 } catch (Exception e) {
                     if (..isDebugEnabled())
                         ..debug("  Validity exception"e);
                     return (null);
                 }
             }
         }
 
         // Check the existence of the client Principal in our database
         return (getPrincipal(certs[0]));
 
     }

    
    
Execute a periodic task, such as reloading, etc. This method will be invoked inside the classloading context of this container. Unexpected throwables will be caught and logged.
 
     public void backgroundProcess() {
     }


    
Return the SecurityConstraints configured to guard the request URI for this request, or null if there is no such constraint.

Parameters:
request Request we are processing
context Context the Request is mapped to
 
     public SecurityConstraint [] findSecurityConstraints(Request request,
                                                          Context context) {
 
         ArrayList results = null;
         // Are there any defined security constraints?
         SecurityConstraint constraints[] = context.findConstraints();
         if ((constraints == null) || (constraints.length == 0)) {
             if (..isDebugEnabled())
                 ..debug("  No applicable constraints defined");
             return (null);
         }
 
         // Check each defined security constraint
         String uri = request.getRequestPathMB().toString();
         
         String method = request.getMethod();
         int i;
         boolean found = false;
         for (i = 0; i < constraints.lengthi++) {
             SecurityCollection [] collection = constraints[i].findCollections();
                      
             // If collection is null, continue to avoid an NPE
             // See Bugzilla 30624
             if ( collection == null) {
 		continue;
             }
 
             if (..isDebugEnabled()) {
                 ..debug("  Checking constraint '" + constraints[i] +
                     "' against " + method + " " + uri + " --> " +
                     constraints[i].included(urimethod));
 	    }
 
             for(int j=0; j < collection.lengthj++){
                 if(collection[j].findMethodOmission(method)) {
                     continue;
                 }
                 String [] patterns = collection[j].findPatterns();
  
                 // If patterns is null, continue to avoid an NPE
                 // See Bugzilla 30624
                 if ( patterns == null) {
 		    continue;
                 }
 
                 for(int k=0; k < patterns.lengthk++) {
                     if(uri.equals(patterns[k])) {
                         found = true;
                         if(collection[j].findMethod(method)) {
                             if(results == null) {
                                 results = new ArrayList();
                             }
                             results.add(constraints[i]);
                         }
                     }
                 }
             }
         }
 
         if(found) {
             return resultsToArray(results);
         }
 
         int longest = -1;
 
         for (i = 0; i < constraints.lengthi++) {
             SecurityCollection [] collection = constraints[i].findCollections();
             
             // If collection is null, continue to avoid an NPE
             // See Bugzilla 30624
             if ( collection == null) {
 		continue;
             }
 
             if (..isDebugEnabled()) {
                 ..debug("  Checking constraint '" + constraints[i] +
                     "' against " + method + " " + uri + " --> " +
                     constraints[i].included(urimethod));
 	    }
 
             for(int j=0; j < collection.lengthj++){
                 if(collection[j].findMethodOmission(method)) {
                     continue;
                 }
                 String [] patterns = collection[j].findPatterns();
 
                 // If patterns is null, continue to avoid an NPE
                 // See Bugzilla 30624
                 if ( patterns == null) {
 		    continue;
                 }
 
                 boolean matched = false;
                 int length = -1;
                 for(int k=0; k < patterns.lengthk++) {
                     String pattern = patterns[k];
                     if(pattern.startsWith("/") && pattern.endsWith("/*") && 
                        pattern.length() >= longest) {
                             
                         if(pattern.length() == 2) {
                             matched = true;
                             length = pattern.length();
                         } else if(pattern.regionMatches(0,uri,0,
                                                         pattern.length()-1) ||
                                   (pattern.length()-2 == uri.length() &&
                                    pattern.regionMatches(0,uri,0,
                                                         pattern.length()-2))) {
                             matched = true;
                             length = pattern.length();
                         }
                     }
                 }
                 if(matched) {
                     if(length > longest) {
                         found = false;
                         if(results != null) {
                             results.clear();
                         }
                         longest = length;
                     }
                     if(collection[j].findMethod(method)) {
                         found = true;
                         if(results == null) {
                             results = new ArrayList();
                         }
                         results.add(constraints[i]);
                     }
                 }
             }
         }
 
         if(found) {
             return  resultsToArray(results);
         }
 
         for (i = 0; i < constraints.lengthi++) {
             SecurityCollection [] collection = constraints[i].findCollections();
 
             // If collection is null, continue to avoid an NPE
             // See Bugzilla 30624
             if ( collection == null) {
 		continue;
             }
             
             if (..isDebugEnabled()) {
                 ..debug("  Checking constraint '" + constraints[i] +
                     "' against " + method + " " + uri + " --> " +
                     constraints[i].included(urimethod));
 	    }
 
             boolean matched = false;
             int pos = -1;
             for(int j=0; j < collection.lengthj++){
                 String [] patterns = collection[j].findPatterns();
                 if(collection[j].findMethodOmission(method)) {
                     continue;
                 }
 
                 // If patterns is null, continue to avoid an NPE
                 // See Bugzilla 30624
                 if ( patterns == null) {
 		    continue;
                 }
 
                 for(int k=0; k < patterns.length && !matchedk++) {
                     String pattern = patterns[k];
                     if(pattern.startsWith("*.")){
                         int slash = uri.lastIndexOf("/");
                         int dot = uri.lastIndexOf(".");
                         if(slash >= 0 && dot > slash &&
                            dot != uri.length()-1 &&
                            uri.length()-dot == pattern.length()-1) {
                             if(pattern.regionMatches(1,uri,dot,uri.length()-dot)) {
                                 matched = true;
                                 pos = j;
                             }
                         }
                     }
                 }
             }
             if(matched) {
                 found = true;
                 if(collection[pos].findMethod(method)) {
                     if(results == null) {
                         results = new ArrayList();
                     }
                     results.add(constraints[i]);
                 }
             }
         }
 
         if(found) {
             return resultsToArray(results);
         }
 
         for (i = 0; i < constraints.lengthi++) {
             SecurityCollection [] collection = constraints[i].findCollections();
             
             // If collection is null, continue to avoid an NPE
             // See Bugzilla 30624
             if ( collection == null) {
 		continue;
             }
 
             if (..isDebugEnabled()) {
                 ..debug("  Checking constraint '" + constraints[i] +
                     "' against " + method + " " + uri + " --> " +
                     constraints[i].included(urimethod));
 	    }
 
             for(int j=0; j < collection.lengthj++){
                 String [] patterns = collection[j].findPatterns();
 
                 // If patterns is null, continue to avoid an NPE
                 // See Bugzilla 30624
                 if ( patterns == null) {
 		    continue;
                 }
 
                 boolean matched = false;
                 for(int k=0; k < patterns.length && !matchedk++) {
                     String pattern = patterns[k];
                     if(pattern.equals("/")){
                         matched = true;
                     }
                 }
                 if(matched) {
                     if(results == null) {
                         results = new ArrayList();
                     }                    
                     results.add(constraints[i]);
                 }
             }
         }
 
         if(results == null) {
             // No applicable security constraint was found
             if (..isDebugEnabled())
                 ..debug("  No applicable constraint located");
         }
         return resultsToArray(results);
     }
 
    
Convert an ArrayList to a SecurityContraint [].
 
     private SecurityConstraint [] resultsToArray(ArrayList results) {
         if(results == null || results.size() == 0) {
             return null;
         }
         SecurityConstraint [] array = new SecurityConstraint[results.size()];
         results.toArray(array);
         return array;
     }

    
    
Perform access control based on the specified authorization constraint. Return true if this constraint is satisfied and processing should continue, or false otherwise.

Parameters:
request Request we are processing
response Response we are creating
constraints Security constraint we are enforcing
context The Context to which client of this class is attached.
Throws:
java.io.IOException if an input/output error occurs
 
     public boolean hasResourcePermission(Request request,
                                          Response response,
                                          SecurityConstraint []constraints,
                                          Context context)
         throws IOException {
 
         if (constraints == null || constraints.length == 0)
             return (true);
 
         // Which user principal have we already authenticated?
         Principal principal = request.getPrincipal();
         boolean status = false;
         boolean denyFromAll = false;
         for(int i=0; i < constraints.lengthi++) {
             SecurityConstraint constraint = constraints[i];
 
             String roles[];
             if (constraint.getAllRoles()) {
                 // * means all roles defined in web.xml
                 roles = request.getContext().findSecurityRoles();
             } else {
                 roles = constraint.findAuthRoles();
             }
 
             if (roles == null)
                 roles = new String[0];
 
             if (..isDebugEnabled())
                 ..debug("  Checking roles " + principal);
 
             if (roles.length == 0 && !constraint.getAllRoles()) {
                 if(constraint.getAuthConstraint()) {
                     if..isDebugEnabled() )
                         ..debug("No roles ");
                     status = false// No listed roles means no access at all
                     denyFromAll = true;
                     break;
                 } else {
                     if(..isDebugEnabled())
                         ..debug("Passing all access");
                     status = true;
                 }
             } else if (principal == null) {
                 if (..isDebugEnabled())
                     ..debug("  No user authenticated, cannot grant access");
             } else {
                 for (int j = 0; j < roles.lengthj++) {
                     if (hasRole(principalroles[j])) {
                         status = true;
                         if..isDebugEnabled() )
                             ..debug"Role found:  " + roles[j]);
                     } else {
                         if..isDebugEnabled() )
                             ..debug"No role found:  " + roles[j]);
                     }
                 }
             }
         }
 
         if (!denyFromAll &&  != . && !status && principal != null) {
             if (..isDebugEnabled()) {
                 ..debug("Checking for all roles mode: " + );
             }
             // Check for an all roles(role-name="*")
             for (int i = 0; i < constraints.lengthi++) {
                 SecurityConstraint constraint = constraints[i];
                 String roles[];
                 // If the all roles mode exists, sets
                 if (constraint.getAllRoles()) {
                     if ( == .) {
                         if (..isDebugEnabled()) {
                             ..debug("Granting access for role-name=*, auth-only");
                         }
                         status = true;
                         break;
                     }
                     
                     // For AllRolesMode.STRICT_AUTH_ONLY_MODE there must be zero roles
                     roles = request.getContext().findSecurityRoles();
                     if (roles.length == 0 &&  == .) {
                         if (..isDebugEnabled()) {
                             ..debug("Granting access for role-name=*, strict auth-only");
                         }
                         status = true;
                         break;
                     }
                 }
             }
         }
         
         // Return a "Forbidden" message denying access to this resource
         if(!status) {
             response.sendError(..forbiddenAccess());
         }
         return status;
 
     }
    
    
    
Return true if the specified Principal has the specified security role, within the context of this Realm; otherwise return false. This method can be overridden by Realm implementations, but the default is adequate when an instance of GenericPrincipal is used to represent authenticated Principals from this Realm.

Parameters:
principal Principal for whom the role is to be checked
role Security role to be checked
 
     public boolean hasRole(Principal principalString role) {
 
         // Should be overriten in JAASRealm - to avoid pretty inefficient conversions
         if ((principal == null) || (role == null) ||
             !(principal instanceof GenericPrincipal))
             return (false);
 
         GenericPrincipal gp = (GenericPrincipalprincipal;
         if (!(gp.getRealm() == this)) {
             if(..isDebugEnabled())
                 ..debug("Different realm " + this + " " + gp.getRealm());//    return (false);
         }
         boolean result = gp.hasRole(role);
         if (..isDebugEnabled()) {
             String name = principal.getName();
             if (result)
                 ..debug(.userHasRole(namerole));
             else
                 ..debug(.userDoesNotHaveRole(namerole));
         }
         return (result);
 
     }

    
    
Enforce any user data constraint required by the security constraint guarding this request URI. Return true if this constraint was not violated and processing should continue, or false if we have created a response already.

Parameters:
request Request we are processing
response Response we are creating
constraints Security constraint being checked
Throws:
java.io.IOException if an input/output error occurs
 
     public boolean hasUserDataPermission(Request request,
                                          Response response,
                                          SecurityConstraint []constraints)
         throws IOException {
 
         // Is there a relevant user data constraint?
         if (constraints == null || constraints.length == 0) {
             if (..isDebugEnabled())
                 ..debug("  No applicable security constraint defined");
             return (true);
         }
         for(int i=0; i < constraints.lengthi++) {
             SecurityConstraint constraint = constraints[i];
             String userConstraint = constraint.getUserConstraint();
             if (userConstraint == null) {
                 if (..isDebugEnabled())
                     ..debug("  No applicable user data constraint defined");
                 return (true);
             }
             if (userConstraint.equals(.)) {
                 if (..isDebugEnabled())
                     ..debug("  User data constraint has no restrictions");
                 return (true);
             }
 
         }
         // Validate the request against the user data constraint
         if (request.getRequest().isSecure()) {
             if (..isDebugEnabled())
                 ..debug("  User data constraint already satisfied");
             return (true);
         }
         // Initialize variables we need to determine the appropriate action
         int redirectPort = request.getConnector().getRedirectPort();
 
         // Is redirecting disabled?
         if (redirectPort <= 0) {
             if (..isDebugEnabled())
                 ..debug("  SSL redirect is disabled");
             response.sendError
                 (.,
                  request.getRequestURI());
             return (false);
         }
 
         // Redirect to the corresponding SSL port
         StringBuilder file = new StringBuilder();
         String protocol = "https";
         String host = request.getServerName();
         // Protocol
         file.append(protocol).append("://").append(host);
         // Host with port
         if(redirectPort != 443) {
             file.append(":").append(redirectPort);
         }
         // URI
         file.append(request.getRequestURI());
         String requestedSessionId = request.getRequestedSessionId();
         if ((requestedSessionId != null) &&
             request.isRequestedSessionIdFromURL()) {
             file.append(request.getContext().getSessionCookie().getPathParameterName());
             file.append(requestedSessionId);
         }
         String queryString = request.getQueryString();
         if (queryString != null) {
             file.append('?');
             file.append(queryString);
         }
             ..debug("  Redirecting to " + file.toString());
         response.sendRedirect(file.toString());
         return (false);
 
     }
    
    
    
Remove a property change listener from this component.

Parameters:
listener The listener to remove
 
     public void removePropertyChangeListener(PropertyChangeListener listener) {
 
         .removePropertyChangeListener(listener);
 
     }
 
 
     // ------------------------------------------------------ Lifecycle Methods
 

    
Add a lifecycle event listener to this component.

Parameters:
listener The listener to add
 
     public void addLifecycleListener(LifecycleListener listener) {
 
         .addLifecycleListener(listener);
 
     }


    
Get the lifecycle listeners associated with this lifecycle. If this Lifecycle has no listeners registered, a zero-length array is returned.
 
 
         return .findLifecycleListeners();
 
     }


    
Remove a lifecycle event listener from this component.

Parameters:
listener The listener to remove
 
     public void removeLifecycleListener(LifecycleListener listener) {
 
         .removeLifecycleListener(listener);
 
     }

    
Prepare for the beginning of active use of the public methods of this component. This method should be called before any of the public methods of this component are utilized. It should also send a LifecycleEvent of type START_EVENT to any registered listeners.

Throws:
org.apache.catalina.LifecycleException if this component detects a fatal error that prevents this component from being used
    public void start() throws LifecycleException {
        // Validate and update our current component state
        if () {
            if(..isInfoEnabled())
            return;
        }
        if( ! ) {
            init();
        }
         = true;
        // Create a MessageDigest instance for credentials, if desired
        if ( != null) {
            try {
                 = MessageDigest.getInstance();
            } catch (NoSuchAlgorithmException e) {
                throw new LifecycleException(.invalidMessageDigest(), e);
            }
        }
    }


    
Gracefully terminate the active use of the public methods of this component. This method should be the last one called on a given instance of this component. It should also send a LifecycleEvent of type STOP_EVENT to any registered listeners.

Throws:
org.apache.catalina.LifecycleException if this component detects a fatal error that needs to be reported
    public void stop()
        throws LifecycleException {
        // Validate and update our current component state
        if (!) {
            if(..isInfoEnabled())
                ..info(.realmNotStarted());
            return;
        }
         = false;
        // Clean up allocated resources
         = null;
        
        destroy();
    
    }
    
    public void destroy() {
    
            // unregister this realm
            if ( !=null ) {   
                try {   
                    Registry.getRegistry(nullnull).unregisterComponent(); 
                    if(..isDebugEnabled())
                        ..debug"unregistering realm " +  );   
                } catchException ex ) {
                    ..failedRealmJmxUnregistration(ex);   
                }      
            }
        }
          
    }
    // ------------------------------------------------------ Protected Methods


    
Digest the password using the specified algorithm and convert the result to a corresponding hexadecimal string. If exception, the plain credentials string is returned.

Parameters:
credentials Password or other credentials to use in authenticating this username
    protected String digest(String credentials)  {
        // If no MessageDigest instance is specified, return unchanged
        if (hasMessageDigest() == false)
            return (credentials);
        // Digest the user credentials and return as hexadecimal
        synchronized (this) {
            try {
                .reset();
    
                byte[] bytes = null;
                if(getDigestEncoding() == null) {
                    bytes = credentials.getBytes();
                } else {
                    try {
                        bytes = credentials.getBytes(getDigestEncoding());
                    } catch (UnsupportedEncodingException uee) {
                        throw .illegalDigestEncoding(getDigestEncoding(), uee);
                    }
                }
                .update(bytes);
                return (HexUtils.convert(.digest()));
            } catch (Exception e) {
                ..errorDigestingCredentials(e);
                return (credentials);
            }
        }
    }
    protected boolean hasMessageDigest() {
        return !( == null);
    }

    
Return the digest associated with given principal's user name.
    protected String getDigest(String usernameString realmName) {
        if ( == null) {
            try {
                 = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                throw .noMD5Digest(e);
            }
        }
    	if (hasMessageDigest()) {
    		// Use pre-generated digest
    		return getPassword(username);
    	}
    	
        String digestValue = username + ":" + realmName + ":"
            + getPassword(username);
        byte[] valueBytes = null;
        if(getDigestEncoding() == null) {
            valueBytes = digestValue.getBytes();
        } else {
            try {
                valueBytes = digestValue.getBytes(getDigestEncoding());
            } catch (UnsupportedEncodingException uee) {
                throw .illegalDigestEncoding(getDigestEncoding(), uee);
            }
        }
        byte[] digest = null;
        // Bugzilla 32137
        synchronized() {
            digest = .digest(valueBytes);
        }
        return .encode(digest);
    }


    
Return a short name for this Realm implementation, for use in log messages.
    protected abstract String getName();


    
Return the password associated with the given principal's user name.
    protected abstract String getPassword(String username);


    
Return the Principal associated with the given certificate.
    protected Principal getPrincipal(X509Certificate usercert) {
        return(getPrincipal(usercert.getSubjectDN().getName()));
    }
    

    
Return the Principal associated with the given user name.
    protected abstract Principal getPrincipal(String username);


    
Return the Server object that is the ultimate parent for the container with which this Realm is associated. If the server cannot be found (eg because the container hierarchy is not complete), null is returned.
    protected Server getServer() {
        Container c = ;
        if (c instanceof Context) {
            c = c.getParent();
        }
        if (c instanceof Host) {
            c = c.getParent();
        }
        if (c instanceof Engine) {
            Service s = ((Engine)c).getService();
            if (s != null) {
                return s.getServer();
            }
        }
        return null;
    }
    // --------------------------------------------------------- Static Methods


    
Digest password using the algorithm especificied and convert the result to a corresponding hex string. If exception, the plain credentials string is returned

Parameters:
credentials Password or other credentials to use in authenticating this username
algorithm Algorithm used to do the digest
encoding Character encoding of the string to digest
    public final static String Digest(String credentialsString algorithm,
                                      String encoding) {
        try {
            // Obtain a new message digest with "digest" encryption
            MessageDigest md =
                (MessageDigest) MessageDigest.getInstance(algorithm).clone();
            // encode the credentials
            // Should use the digestEncoding, but that's not a static field
            if (encoding == null) {
                md.update(credentials.getBytes());
            } else {
                md.update(credentials.getBytes(encoding));                
            }
            // Digest the credentials and return as hexadecimal
            return (HexUtils.convert(md.digest()));
        } catch(Exception ex) {
            return credentials;
        }
    }


    
Digest password using the algorithm especificied and convert the result to a corresponding hex string. If exception, the plain credentials string is returned
    public static void main(String args[]) {
        String encoding = null;
        int firstCredentialArg = 2;
        
        if (args.length > 4 && args[2].equalsIgnoreCase("-e")) {
            encoding = args[3];
            firstCredentialArg = 4;
        }
        
        if(args.length > firstCredentialArg && args[0].equalsIgnoreCase("-a")) {
            for(int i=firstCredentialArgi < args.length ; i++){
                ..print(args[i]+":");
                ..println(Digest(args[i], args[1], encoding));
            }
        } else {
            ..println
                ("Usage: RealmBase -a <algorithm> [-e <encoding>] <credentials>");
        }
    }
    // -------------------- JMX and Registration  --------------------
    protected String type;
    protected String domain;
    protected String host;
    protected String path;
    protected String realmPath = "/realm0";
    protected ObjectName oname;
    protected ObjectName controller;
    protected MBeanServer mserver;
    public ObjectName getController() {
        return ;
    }
    public void setController(ObjectName controller) {
        this. = controller;
    }
    public ObjectName getObjectName() {
        return ;
    }
    public String getDomain() {
        return ;
    }
    public String getType() {
        return ;
    }
    public String getRealmPath() {
        return ;
    }
    
    public void setRealmPath(String theRealmPath) {
         = theRealmPath;
    }
    public ObjectName preRegister(MBeanServer server,
                                  ObjectName namethrows Exception {
        =name;
        =server;