Java XML Hash hash(final String text, final String algorithm)

Here you can find the source of hash(final String text, final String algorithm)

Description

calculates a cryptographic hash function (message digest).

License

Apache License

Parameter

Parameter Description
text the text to hash
algorithm the hash algorithm to use

Exception

Parameter Description
UnsupportedOperationException if the given hash algorithm is not available

Declaration

public static String hash(final String text, final String algorithm) 

Method Source Code

//package com.java2s;
/*/*from   w w  w . j a  va  2 s.c  o  m*/
   Copyright 2014-now by Alain Stalder. Made in Switzerland.
    
   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.
*/

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

import javax.xml.bind.DatatypeConverter;

public class Main {
    /**
     * UTF-8 character set
     * 
     * @since 1.0
     */
    public static final Charset CHARSET_UTF_8 = Charset.forName("UTF-8");

    /**
     * calculates a cryptographic hash function (message digest).
     * <p>
     * The given text is first UTF-8 encoded to bytes, then the given hash
     * is calculated and finally returned as a hex string.
     * 
     * @param text the text to hash
     * @param algorithm the hash algorithm to use
     * @throws UnsupportedOperationException if the given hash algorithm is not available
     * 
     * @since 1.0
     */
    public static String hash(final String text, final String algorithm) {
        MessageDigest hash;
        try {
            hash = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new UnsupportedOperationException("No message digest " + algorithm + ".", e);
        }
        byte[] digestBytes = null;
        digestBytes = hash.digest(text.getBytes(CHARSET_UTF_8));
        String digest = DatatypeConverter.printHexBinary(digestBytes);
        return digest;
    }
}

Related

  1. calculateHash(String password, String salt)
  2. createHash(String password)
  3. getHash(final byte[] data, MessageDigest algo)
  4. hash(byte[] bytes)
  5. hash(String data, String salt)
  6. hash512(byte[] data)
  7. hashPass(String plaintext)
  8. hashPassword(char[] password, String salt, String hashAlgo)