Java Hash Calculate getHash(final byte[] data, final String hashAlgorithm)

Here you can find the source of getHash(final byte[] data, final String hashAlgorithm)

Description

get Hash

License

Open Source License

Declaration

private static String getHash(final byte[] data, final String hashAlgorithm) 

Method Source Code

//package com.java2s;
/**/*from   w w  w. j  a  va  2 s.  co m*/
 *
 *  BibSonomy-Common - Common things (e.g., exceptions, enums, utils, etc.)
 *
 *  Copyright (C) 2006 - 2011 Knowledge & Data Engineering Group,
 *                            University of Kassel, Germany
 *                            http://www.kde.cs.uni-kassel.de/
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

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

public class Main {
    private static String getHash(final byte[] data, final String hashAlgorithm) {
        if (data == null)
            return null;

        try {
            final MessageDigest md = MessageDigest.getInstance(hashAlgorithm);
            return toHexString(md.digest(data));
        } catch (final NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * Converts a buffer of bytes into a string of hex values.
     * 
     * @param buffer
     *            array of bytes which should be converted
     * @return hex string representation of buffer
     */
    public static String toHexString(byte[] buffer) {
        final StringBuilder result = new StringBuilder();
        for (int i = 0; i < buffer.length; i++) {
            String hex = Integer.toHexString(buffer[i]);
            if (hex.length() == 1) {
                hex = "0" + hex;
            }

            result.append(hex.substring(hex.length() - 2));
        }

        return result.toString();
    }
}

Related

  1. getHash(byte[] data, int offset, int length)
  2. getHash(byte[] inputBytes)
  3. getHash(byte[]... bytesToHash)
  4. getHash(File file)
  5. getHash(File file, String hashType)
  6. getHash(final String text, final Charset charset, final MessageDigest algorithm)
  7. getHash(InputStream in, String algorithm)
  8. getHash(InputStream is, String algorithm)
  9. getHash(int iterationNb, String password, byte[] salt)