Java MD5 String MD5(String s)

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

Description

String md5 encoding

License

Apache License

Declaration

public static String MD5(String s) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.io.UnsupportedEncodingException;

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

public class Main {
    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    /** String md5 encoding */
    public static String MD5(String s) {
        try {// w w  w. j a  v a2s.  c om
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] md5bytes = messageDigest.digest(s.getBytes("UTF-8"));
            //            return ByteString.of(md5bytes).hex();
            return toHex(md5bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new AssertionError(e);
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError(e);
        }
    }

    public static byte[] getBytes(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /** Return hex encoded string from bytes */
    public static String toHex(byte... bs) {
        StringBuilder result = new StringBuilder(bs.length * 2);
        for (byte b : bs) {
            result.append(HEXDIGITS[(b >> 4) & 0xF]);
            result.append(HEXDIGITS[(b & 0xF)]);
        }
        return result.toString();
    }
}

Related

  1. md5(String plainText)
  2. MD5(String pwd)
  3. md5(String raw)
  4. md5(String s)
  5. md5(String s)
  6. md5(String s)
  7. md5(String s)
  8. md5(String s)
  9. md5(String s)