jp.terasoluna.fw.util.HashUtil.java Source code

Java tutorial

Introduction

Here is the source code for jp.terasoluna.fw.util.HashUtil.java

Source

/*
 * Copyright (c) 2007 NTT DATA Corporation
 *
 * Licensed 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 jp.terasoluna.fw.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * ??
 * 
 * <p>
 *  java.security.MessageDigest?????
 *  ??<br>
 *  MD5?SHA1????????
 *  <strong></strong><br>
 *  <code><pre>
 *   
 *    // DB?????
 *    byte[] hash = HashUtil.hashMD5(userPassword);
 *   
 *  </pre></code>
 * </p>
 *
 */
public class HashUtil {

    /**
     * 
     */
    private static Log log = LogFactory.getLog(HashUtil.class);

    /**
     * ??????
     *
     * @param algorithm ?
     * @param str ????
     * @return ?
     * @throws NoSuchAlgorithmException ???????
     * 
     */
    public static byte[] hash(String algorithm, String str) throws NoSuchAlgorithmException {
        if (algorithm == null || str == null) {
            return null;
        }
        MessageDigest md = MessageDigest.getInstance(algorithm.toUpperCase());
        return md.digest(str.getBytes());
    }

    /**
     * MD5?????
     * 
     * @param str ????
     * @return ?
     */
    public static byte[] hashMD5(String str) {
        try {
            return hash("MD5", str);
        } catch (NoSuchAlgorithmException e) {
            log.error("The algorithm is not available" + " in the caller's environment.", e);
            return null; // can't happen
        }
    }

    /**
     * SHA1?????
     * 
     * @param str ????
     * @return ?
     */
    public static byte[] hashSHA1(String str) {
        try {
            return hash("SHA1", str);
        } catch (NoSuchAlgorithmException e) {
            log.error("The algorithm is not available" + " in the caller's environment.", e);
            return null; // can't happen
        }
    }
}