Java MD5 digestMD5(String text)

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

Description

Calculate the MD5 digest code for the text.

License

Open Source License

Parameter

Parameter Description
text Text to be digested.

Return

Digest text as by the MD5 code.

Declaration

public static String digestMD5(String text) 

Method Source Code

//package com.java2s;
/*/*from  w  ww .ja va2s  . com*/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
    
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    
Copyright (C) 2007 Marco Aurelio Graciotto Silva <magsilva@gmail.com>
 */

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

public class Main {
    /**
     * Calculate the MD5 digest code for the text.
     *
     * @param text Text to be digested.
     * @return Digest text as by the MD5 code.
     */
    public static String digestMD5(String text) {
        return digest(text, "MD5");
    }

    /**
     * Create the hash/digest code for a given text.
     *
     * @param text Text to be digested.
     * @param algorithm Digest code to be used (usually MD5 or SHA1).
     *
     * @return Digest code.
     * @throws IllegalArgumentException if an invalid text (null) is set.
     */
    public static String digest(String text, String algorithm) {
        if (text == null) {
            throw new IllegalArgumentException(new NullPointerException());
        }

        MessageDigest md;
        try {
            md = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        }
        byte[] hash = md.digest(text.getBytes());
        StringBuilder sb = new StringBuilder();

        for (byte b : hash) {
            String hex = Integer.toHexString(b);
            int len = hex.length();
            if (len == 1) {
                sb.append("0" + hex);
            } else {
                sb.append(hex.substring(len - 2, len));
            }
        }

        return sb.toString();
    }
}

Related

  1. digestMd5(final String value)
  2. digestMD5(String buffer, String key)
  3. digestMD5(String data)
  4. digestMD5(String login, String pass)
  5. digestMd5(String plain)
  6. encryptmd5(String str)
  7. generateMD5ByContent(String content)
  8. getFileMD5(String filePath)
  9. getHexMd5(byte[] bytes)