You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by Valentin Nagacevschi <vn...@telemobil.ro> on 2000/08/02 10:56:12 UTC

Suggestion on JDBCRealm with non-plain password

Hi all,

I think that the easiest way to encrypt a password is to use the MD5 algorithm, already
found in the java.security package. I already modified the JDBCRealm class, and tested it,
and it works great and fast. The changes were just by adding a new method called MD5Encode
which takes the credentials as param and return the corresponding MD5 encrypted string,
and a small one in the authenticate method. Here is the source of the method:
    /**
     * Encode the credentials (password) using MD5 and
     * convert the result to a corresponding hex string.
     * If exception, the plain credentials string is returned
    * @param credentials Password or other credentials to use in
    *  authenticating this username
    */
    public String MD5Encode(String credentials) {
        String res = new String("");
        try {
            // Obtain a new message digest with MD5 encryption
            MessageDigest md = (MessageDigest)MessageDigest.getInstance("MD5").clone();
            // encode the credentials
            md.update(credentials.getBytes());
            // obtain the byte array from the digest
            byte[] dig = md.digest();
            // convert the byte array to hex string
            // Integer.toHexString doesn't put a leading 0 if the value is smaller than 16
            // ((dig[i])<<24)>>>24 ensures the unsign -:)
            for(int i=0;i<md.getDigestLength();i++)
                res = res + ((dig[i]>0 && dig[i]<16)?"0":"")+
                    Integer.toHexString(((dig[i])<<24)>>>24);
            return(res.toUpperCase());
        } catch( Exception ex ) {
                return credentials;
        }
    }
If an exception occurs, such as NoSuchAlgorithmException or CloneNotSupportedException
(this never has to happen), the plain credential is to be returned.
As you may observe, I convert the MD5 encoded string to hex string, but base64 or uuencode
methods could be used if desired.

The change in authenticate method:

            if (rs1.next()) {
                // if (credentials.equals(rs1.getString(1))) {
                if (MD5Encode(credentials).equals(rs1.getString(1))) {
                    if (debug >= 2)
                        log(sm.getString("jdbcRealm.authenticateSuccess",
                                 username));
                    return true;
                }
            }

Of course I import java.security.* package for the MessageDigest use.
If you consider this code ok, I appreciate if you will include it in the next distribution
of Tomcat.
Regards,

Valentin Nagacevschi