001/*
002 *  Copyright 2013 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.web.cache.monitoring.process.access;
017
018import java.io.UnsupportedEncodingException;
019import java.security.MessageDigest;
020import java.security.NoSuchAlgorithmException;
021
022import org.apache.commons.codec.binary.Hex;
023import org.slf4j.Logger;
024import org.slf4j.LoggerFactory;
025
026/**
027 * Utility methods used when dealing with <code>ResourceAccess</code> object.
028 */
029public final class ResourceAccessUtils
030{
031    private static final Logger __LOGGER = LoggerFactory.getLogger(ResourceAccessUtils.class);
032
033    private ResourceAccessUtils()
034    {
035        // empty private constructor
036    }
037
038    /**
039     * Computes the SHA-256 hash for a string.
040     * @param str The string to be hashed.
041     * @return The hashed string.
042     */
043    public static String toHash(String str)
044    {
045        MessageDigest md;
046        byte[] hash;
047
048        try
049        {
050            md = MessageDigest.getInstance("SHA-256");
051            hash = md.digest(str.getBytes("UTF-8"));
052        }
053        catch (NoSuchAlgorithmException e)
054        {
055            __LOGGER.error("Cannot get the message digest instance for SHA-256", e);
056            return null;
057        }
058        catch (UnsupportedEncodingException e)
059        {
060            __LOGGER.error("UnsupportedEncodingException UTF-8", e);
061            return null;
062        }
063
064        return Hex.encodeHexString(hash);
065    }
066}