Java MD5 String md5(String data)

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

Description

Calculates the MD5 digest and returns the value as a 16 element byte[].

License

Open Source License

Parameter

Parameter Description
data data to digest

Return

MD5 digest

Declaration

public static byte[] md5(String data) 

Method Source Code


//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    /**/*from w w w  .  j av  a2  s .  c  o  m*/
     * Calculates the MD5 digest and returns the value as a 16 element <code>byte[]</code>.
     * @param data data to digest
     * @return MD5 digest
      */
    public static byte[] md5(String data) {
        return md5(getBytesUtf8(data));
    }

    /**
     * Calculates the MD5 digest and returns the value as a 16 element <code>byte[]</code>.
     * @param data data to digest
     * @return MD5 digest
      */
    public static byte[] md5(byte[] data) {
        return getMd5Digest().digest(data);
    }

    /**
     * Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte
     * array.
     *
     * @param string
     *            the String to encode, may be {@code null}
     * @return encoded bytes, or {@code null} if the input string was {@code null}
     */
    public static byte[] getBytesUtf8(String string) {
        try {
            return string == null ? null : string.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            // Should never happen with UTF-8
            // If it does - ignore & return null
        }
        return null;
    }

    /**
     * Returns an MD5 MessageDigest.
     * @return An MD5 digest instance.
      */
    public static MessageDigest getMd5Digest() {
        return getDigest("MD5");
    }

    /**
     * Returns a <code>MessageDigest</code> for the given <code>algorithm</code>.
     * @param algorithm
     * @return An MD5 digest instance.
     * @throws IllegalArgumentException
      */
    public static MessageDigest getDigest(String algorithm) {
        try {
            return MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException var2) {
            throw new IllegalArgumentException(var2);
        }
    }
}

Related

  1. md5(Path path)
  2. md5(String content)
  3. md5(String content)
  4. md5(String content)
  5. md5(String d)
  6. md5(String data)
  7. md5(String data)
  8. md5(String data)
  9. md5(String data)