All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.kanejin.commons.util.MD5Utils Maven / Gradle / Ivy

The newest version!
package cn.kanejin.commons.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密算法
 */
public class MD5Utils {
	/**
	 * 对字符串进行MD5加密
	 * 
	 * @param rawText 明文
	 * 
	 * @return 密文
	 */
	public static String md5(String rawText) {
		try {
			return md5(rawText.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(
					"System doesn't support your  EncodingException.");
		}
	}

	/**
	 * 对二进制码进行MD5加密
	 *
	 * @param rawData 明文二进制码
	 *
	 * @return
	 */
	public static String md5(byte[] rawData) {
		return new String(encodeHex(encryt(rawData)));
	}

	private static byte[] encryt(byte[] rawData) {
		MessageDigest msgDigest = null;

		try {
			msgDigest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			throw new IllegalStateException(
					"System doesn't support MD5 algorithm.");
		}

		msgDigest.update(rawData);

		return msgDigest.digest();
	}

	// Used building output as Hex
	private static final char[] DIGITS = "0123456789abcdef".toCharArray();
	private static char[] encodeHex(byte[] data) {

		int l = data.length;

		char[] out = new char[l << 1];

		// two characters form the hex value.
		for (int i = 0, j = 0; i < l; i++) {
			out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
			out[j++] = DIGITS[0x0F & data[i]];
		}

		return out;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy