Calculates the MD5 hash of the string. - Java Security

Java examples for Security:MD5

Description

Calculates the MD5 hash of the string.

Demo Code

/*//ww w .  j a  va2 s.  co m
 * 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.
 */
//package com.java2s;

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 Tutorials