Java Hash Calculate getHashMD5(String text)

Here you can find the source of getHashMD5(String text)

Description

Calculates the MD5 hash of the string.

License

Apache License

Parameter

Parameter Description
text a parameter

Return

md5 hash of the string

Declaration

public static String getHashMD5(String text) 

Method Source Code

//package com.java2s;
/*/*from   w ww  .ja  v a2  s  .com*/
 * Copyright (C) 2015 the original author or authors.
 *
 * 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.StandardCharsets;

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

public class Main {
    /**
     * Calculates the MD5 hash of the string.
     *
     * @param text
     * @return md5 hash of the string
     */
    public static String getHashMD5(String text) {
        byte[] bytes = text.getBytes(StandardCharsets.ISO_8859_1);
        return getHashMD5(bytes);
    }

    /**
     * Calculates the MD5 hash of the byte array.
     *
     * @param bytes
     * @return md5 hash of the byte array
     */
    public static String getHashMD5(byte[] bytes) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes, 0, bytes.length);
            byte[] digest = md.digest();
            return toHex(digest);
        } catch (NoSuchAlgorithmException t) {
            throw new RuntimeException(t);
        }
    }

    public static String toHex(byte[] bytes) {
        StringBuilder hash = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                hash.append('0');
            }
            hash.append(hex);
        }
        return hash.toString();
    }
}

Related

  1. getHashInstance(final String alg)
  2. getHashKey(String input)
  3. getHashMD5(File file)
  4. getHashMD5(String arg)
  5. getHashMD5(String str)
  6. getHashMDFive(String str)
  7. getHashOf(String s)
  8. getHashString()
  9. getHashString(byte[] data)