Java MD5 String md5(final String message)

Here you can find the source of md5(final String message)

Description

Generates de MD5 checksum for the specified message.

License

Apache License

Parameter

Parameter Description
message The message.

Return

The hexadecimal checksum.

Declaration

public static String md5(final String message) 

Method Source Code

//package com.java2s;
/*//from w  w w. ja  v a  2s . c  o  m
 * Copyright 2014 Feedzai
 *
 * 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.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    /**
     * Generates de MD5 checksum for the specified message.
     *
     * @param message The message.
     * @return The hexadecimal checksum.
     */
    public static String md5(final String message) {
        byte[] res;

        try {
            MessageDigest instance = MessageDigest.getInstance("MD5");
            instance.reset();
            instance.update(message.getBytes());
            res = instance.digest();

        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }

        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < res.length; i++) {
            hexString.append(Integer.toString((res[i] & 0xff) + 0x100, 16).substring(1));

        }

        return hexString.toString();
    }

    /**
     * Generates de MD5 checksum for the specified message.
     *
     * @param message The message.
     * @param nchar   The maximum number of chars for the result hash.
     * @return The hexadecimal checksum with the specified maximum number of chars.
     */
    public static String md5(final String message, final int nchar) {
        return md5(message).substring(0, nchar);
    }
}

Related

  1. md5(final InputStream in)
  2. md5(final String data)
  3. md5(final String inData)
  4. md5(final String input)
  5. md5(final String input)
  6. md5(final String s)
  7. md5(final String s)
  8. md5(final String str)
  9. md5(final String string)