Java MD5 String MD5_HEX(String source)

Here you can find the source of MD5_HEX(String source)

Description

MHEX

License

Apache License

Declaration

public static String MD5_HEX(String source) 

Method Source Code


//package com.java2s;
/*//from   w w  w .ja  v a 2 s . c  o m
 * Copyright (c) 2016 yunmle.com(????????).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

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

public class Main {
    public static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
            'f' };

    public static String MD5_HEX(String source) {
        try {
            return digest("MD5", source);
        } catch (NoSuchAlgorithmException ignore) {
        }
        return null;
    }

    public static String MD5_HEX(byte[] bytes) {
        try {
            return digest("MD5", bytes);
        } catch (NoSuchAlgorithmException ignore) {
        }
        return null;
    }

    private static String digest(String name, String source) throws NoSuchAlgorithmException {
        if (source != null) {
            final MessageDigest md = MessageDigest.getInstance(name);
            md.update(source.getBytes());
            return toHexString(md.digest());
        }
        return null;
    }

    private static String digest(String name, byte[] bytes) throws NoSuchAlgorithmException {
        if (bytes != null) {
            final MessageDigest md = MessageDigest.getInstance(name);
            md.update(bytes);
            return toHexString(md.digest());
        }
        return null;
    }

    public static String toHexString(final byte[] bs) {
        final int len;
        if (bs != null && (len = bs.length) != 0) {
            final char[] cs = new char[len << 1];
            final char[] myDigits = DIGITS;
            byte b;
            for (int i = 0, j = 0; i < len; i++) {
                cs[j++] = myDigits[((b = bs[i]) >>> 4) & 0xF];
                cs[j++] = myDigits[b & 0xF];
            }
            return String.valueOf(cs);
        }
        return null;
    }
}

Related

  1. md5(String value)
  2. md5(String value)
  3. md5(String... args)
  4. MD5(String... texts)
  5. md52(String string)
  6. md5AsHexString(String text, String charset)
  7. md5Base64(String str)
  8. md5ByHex(String src)
  9. md5crypt(String s)