Writing a custom tomcat domain using bcrypt

I am working on a Java based web application using Tomcat 7.0 as an application server. After helpful answers to the previous question , I decided to use bcrypt to securely store passwords in my HSQLDB. However, the default implementation of Tomcat Realm cannot handle bcrypt, so I need to write my own; which is the only reason I write the user area, although, as in all other cases, JDBCRealm works. I searched the Internet and studied examples, and I'm a little confused by a couple of points.

First, should you distribute RealmBase or JDBCRealm? Most of the examples I found use RealmBase, but I have successfully used JDBCRealm for the application up to this point (since it is still under development, I started by storing passwords in plain text and just used JDBCRealm to handle authentication) and one answer to A question about Code Ranch recommended simply expanding this. I'm not quite sure which methods I need to override in this case. Just an authentication method or something else? If this would cause JDBCRealm to still be able to handle and manage user roles, getPrincipal and all that?

Secondly, in the above CodeRanch example, if I'm missing something, the getPassword method seems to return an unencrypted password. Since I am going to use bcrypt, that would be impossible, and it would seem to be impractical, I would think. In other examples, like this blog post , getPassword simply returns the password directly from the database. So which way is right? I cannot find what exactly getPassword is used for; the documentation does not say. Will it normally return the encrypted value stored in the database?

If anyone can tell me which class I should extend, which methods I should override, and what to get getPassword, I would really appreciate it.

+5
source share
1

, , . JDBCRealm , . BCrypt.java , , :

import java.security.Principal;
import org.apache.catalina.realm.JDBCRealm;
public class BCryptRealm extends JDBCRealm
{
  @Override
  public Principal authenticate(String username, String credentials)
  {
    String hashedPassword = getPassword(username);
    // Added this check after discovering checkpw generates a null pointer
    // error if the hashedPassword is null, which happens when the user doesn't
    // exist. I'm assuming returning null immediately would be bad practice as
    // it would let an attacker know which users do and don't exist, so I added
    // a call to hashpw. No idea if that completely solves the problem, so if
    // your application has more stringent security needs this should be
    // investigated further.
    if (hashedPassword == null)
    {
      BCrypt.hashpw("fakePassword", BCrypt.gensalt());
      return null;
    }
    if (BCrypt.checkpw(credentials, hashedPassword))
    {
      return getPrincipal(username);
    }
    return null;
  }
}
+4

All Articles