/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (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.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * 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 com.queplix.core.integrator.security;

import com.queplix.core.error.GenericSystemException;
import com.queplix.core.utils.StringHelper;

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

/**
 * Helper class for cryptographic operations.
 *
 * @author [DAG] Dmitry Gaponenko
 * @author [ONZ] Oleg N. Zhovtanyuk
 * @version $Revision: 1.1.1.1 $ $Date: 2005/09/12 15:30:52 $
 */
public final class CryptoHelper {

    // Private constuctor - blocks instantiation.
    private CryptoHelper() {
    }

    // ================================================================== Fields

    // Cached digest of the blank password.
    private static String blankPasswordDigest;

    // ================================================================= Methods

    /**
     * Calculates the message digest on the given string.
     * Current implementation uses the <b>SHA</b> digest generation algorithm.
     *
     * @param str message to calculate the digest on
     * @return message digest as hexadecimal converted to string
     */
    public static String getDigest(String str) {

        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(str.getBytes());
            byte[] dig = md.digest();
            int digL = dig.length;
            byte[] buf = new byte[digL << 1];
            for(int i = 0, j = 0; i < digL; i++) {
                byte b = dig[i];
                int hi = (b >> 4) & 0xf;
                int lo = b & 0xf;
                buf[j++] = (byte) ((hi > 9) ? ('A' + (hi - 10)):('0' + hi));
                buf[j++] = (byte) ((lo > 9) ? ('A' + (lo - 10)):('0' + lo));
            }

            return new String(buf);

        } catch (NoSuchAlgorithmException ex) {
            throw new GenericSystemException("Can't find SHA algorithm", ex);
        }
    }

    /**
     * Calculates the digest on the empty string (for password reset).
     *
     * @return message digest as hexadecimal converted to string
     * @see #getDigest(String)
     */
    public static String getBlankStringDigest() {
        if(blankPasswordDigest == null) {
            blankPasswordDigest = CryptoHelper.getDigest(
                    StringHelper.EMPTY_VALUE);
        }

        return blankPasswordDigest;
    }
}
