Java Hash Calculate getHash(final String text, final Charset charset, final MessageDigest algorithm)

Here you can find the source of getHash(final String text, final Charset charset, final MessageDigest algorithm)

Description

Computes the hash of a given text.

License

Open Source License

Parameter

Parameter Description
text the text to hash.
charset the charset of the text.
algorithm the algorithm to use for the hash.

Return

the hash of the text.

Declaration

public static String getHash(final String text, final Charset charset, final MessageDigest algorithm) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.nio.charset.Charset;
import java.security.MessageDigest;

public class Main {
    /**/*from  www  . j a va2  s .  c o  m*/
     * Computes the hash of a given text.<br />
     * @param text
     *        the text to hash.
     * @param charset
     *        the charset of the text.
     * @param algorithm
     *        the algorithm to use for the hash.
     * @return the hash of the text.
     */
    public static String getHash(final String text, final Charset charset, final MessageDigest algorithm) {
        final StringBuilder buffer = new StringBuilder();
        algorithm.reset();
        algorithm.update(text.getBytes(charset));

        final byte[] digest = algorithm.digest();
        for (final byte element : digest) {
            int value = element;
            if (value < 0) {
                value += Byte.MAX_VALUE - Byte.MIN_VALUE + 1;
            }
            // Add a zero in case of 'short' hash.
            final String hex = Integer.toHexString(value);
            if (hex.length() == 1) {
                buffer.append(0);
            }
            buffer.append(hex);
        }
        return buffer.toString();
    }
}

Related

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