Java MD5 String md5(String txt)

Here you can find the source of md5(String txt)

Description

md

License

Open Source License

Parameter

Parameter Description
txt a parameter

Return

MD5 hash of txt (32 hex digits). MD5 has known security flaws. But it is fast & good for non-security uses.<br> See http://www.javamex.com/tutorials/cryptography/ hash_functions_algorithms.shtml

Declaration

public static String md5(String txt) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.UnsupportedEncodingException;

public class Main {
    public static final String ENCODING_UTF8 = "UTF8";

    /**/*from  www. ja va 2  s .  c  om*/
     * @param txt
     * @return MD5 hash of txt (32 hex digits). MD5 has known security flaws. But it is fast &
     *         good for non-security uses.<br>
     * 
     *         See http://www.javamex.com/tutorials/cryptography/
     *         hash_functions_algorithms.shtml
     * @see #sha1(String)
     */
    public static String md5(String txt) {
        return hash("MD5", txt);
    }

    /**
     * 
     * @param hashAlgorithm e.g. "MD5"
     * @param txt
     * @return
     */
    public static String hash(String hashAlgorithm, String txt) {
        if ("SHA256".equals(hashAlgorithm))
            hashAlgorithm = "SHA-256";
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance(hashAlgorithm);
            StringBuilder result = new StringBuilder();
            try {
                for (byte b : md.digest(txt.getBytes(ENCODING_UTF8))) {
                    result.append(Integer.toHexString((b & 0xf0) >>> 4));
                    result.append(Integer.toHexString(b & 0x0f));
                }
            } catch (UnsupportedEncodingException e) {
                for (byte b : md.digest(txt.getBytes())) {
                    result.append(Integer.toHexString((b & 0xf0) >>> 4));
                    result.append(Integer.toHexString(b & 0x0f));
                }
            }
            return result.toString();
        } catch (java.security.NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }
}

Related

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