This article describes the MD5 digest algorithm implemented by Java. Share it for your reference, as follows:
package com.soufun.com;import java.io.UnsupportedEncodingException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;/** * @author WHD */public class MD5Test { // MD5 unidirectional encryption public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException { String str = "hellomd digest algorithm starts"; System.out.println("raw value" + str); System.out.println("encrypted" + MD5Test.afterMD5(str)); String digest = MD5Test.afterMD5(str); System.out.println(digest.equals(MD5Test.afterMD5(str))); } public static String afterMD5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException { // Get the MD5 encrypted object, and you can also get the SHA encrypted object MessageDigest md5 = MessageDigest.getInstance("MD5"); // Get the input information using the specified encoding method byte byte[] bytes = str.getBytes("UTF-8"); // Use the md5 class to get the digest, that is, the encrypted byte md5.update(bytes); byte[] md5encode = md5.digest(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < md5encode.length; i++) { // Use &0xff less than 24 high bits, because it only accounts for 8 low bits int val = ((int) md5encode[i]) & 0xff; if (val < 16) { buffer.append("0"); } // Returns the string representation of an integer parameter in hexadecimal (base 16) unsigned integer. buffer.append(Integer.toHexString(val)); } return buffer.toString(); }}Use org.apache.commons.codec.digest.DigestUtilsorg.apache.commons.codec.digest.DigestUtils to implement md5 encryption
Configuration in maven:
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.4</version></dependency>
Note here that the difference between version 1.2 and version 1.4 is very big, because there are many methods extended in 1.4.
The specific code is as follows:
public static String afterMd5(String str){ try { String md5 = DigestUtils.md5Hex(str.getBytes("UTF-8")); return md5; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null;}PS: Friends who are interested in encryption and decryption can also refer to the online tools of this site:
Password security online detection:
http://tools.VeVB.COM/password/my_password_safe
High-strength password generator:
http://tools.VeVB.COM/password/CreateStrongPassword
Thunder, Express, and Tornado URL encryption/decryption tools:
http://tools.VeVB.COM/password/urlrethunder
Online hash/hash algorithm encryption tool:
http://tools.VeVB.COM/password/hash_encrypt
Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 encryption tool:
http://tools.VeVB.COM/password/hash_md5_sha
Online sha1/sha224/sha256/sha384/sha512 encryption tool:
http://tools.VeVB.COM/password/sha_encode
I hope this article will be helpful to everyone's Java programming.