Java MD5 String MD5(String text)

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

Description

This nethod is used for encrypt String to MD5

License

Apache License

Parameter

Parameter Description
text String

Return

String

Declaration

public static String MD5(String text) 

Method Source Code

//package com.java2s;
/**// w ww.j av a 2s .  c om
 * Copyright 2011 Virtual Think Team
 * 
 * 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 {
    /**
     * This nethod is used for encrypt String to MD5
     * @param text String
     * @return String
     */
    public static String MD5(String text) {
        String output = null;
        try {
            MessageDigest dg = MessageDigest.getInstance("MD5");
            dg.reset();
            dg.update(stringToBytes(text));
            byte[] hasher = new byte[32];
            hasher = dg.digest();
            return bytesToHexString(hasher);
        } catch (NoSuchAlgorithmException e) {
            System.out.println("There is No MessageDigest Instance of MD5");
            System.exit(1);
        }
        return output;
    }

    /**
     * This method used for converting string to bytes
     * @param str String
     * @return byte[]
     */
    public static byte[] stringToBytes(String str) {
        int len = str.length();
        byte[] out = new byte[len];
        for (int i = 0; i < len; i++)
            out[i] = (byte) (str.charAt(i) & 0xFF);
        return out;
    }

    /**
     * This method used for converting byte array to hex string
     * 
     * @param hasher byte[]
     * @return String
     */
    public static String bytesToHexString(byte[] hasher) {
        String HEXES = "0123456789abcdef";
        StringBuilder hex = new StringBuilder(2 * hasher.length);
        for (final byte b : hasher) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }
}

Related

  1. MD5(String text)
  2. MD5(String text)
  3. MD5(String text)
  4. md5(String text)
  5. md5(String text)
  6. md5(String text)
  7. md5(String text)
  8. md5(String text)
  9. md5(String text, String charset)