Java implementation of MD5 encryption and decryption code instance sharing

Source: Internet
Author: User
Tags md5 encryption md5 hash string format


Link: Http://www.jb51.net/article/86027.htmJava implementation of MD5 encryption and decryption code instance sharing


Xiamen University Chen Lidong font: [Increase decrease] Type: Reprint time: 2016-06-07 I want to comment


If the need for security is not too high, MD5 is still using a very convenient and pervasive encryption method, such as Java's own MessageDigest class to provide support, here is the Java implementation MD5 encryption and decryption code instance sharing:


Basis: Use of the MessageDigest class



In fact, in Java to complete the MD5 encryption, MessageDigest class most of them to help you achieve good, a few lines of code is sufficient:


/ **
  * Encrypt string md5
  *
  * @param str
  * @return
  * /
import java.security.MessageDigest;
public static String getMD5 (String str) {
  try {
  // Generate a MD5 encrypted calculation summary
  MessageDigest md = MessageDigest.getInstance ("MD5");
  // calculate md5 function
  md.update (str.getBytes ());
  // digest () finally determines to return the md5 hash value, and the return value is 8 as a string. Because the md5 hash value is a 16-bit hex value, it is actually an 8-bit character
  // The BigInteger function converts an 8-bit string into a 16-bit hex value, which is represented by a string; the hash value is obtained as a string
  return new BigInteger (1, md.digest ()). toString (16);
  } catch (Exception e) {
  throw new SpeedException ("MD5 encryption error");
  }
}


Advanced: Encryption and decryption classes
Java implements MD5 encryption and decryption classes, with test classes, see Code.



MD5 encryption decryption Class--mymd5util, the code is as follows


package com.zyg.security.md5;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;

public class MyMD5Util {
 
 private static final String HEX_NUMS_STR = "0123456789ABCDEF";
 private static final Integer SALT_LENGTH = 12;
 
 / **
 * Convert hexadecimal string to byte array
 * @param hex
 * @return
 * /
 public static byte [] hexStringToByte (String hex) {
 int len = (hex.length () / 2);
 byte [] result = new byte [len];
 char [] hexChars = hex.toCharArray ();
 for (int i = 0; i <len; i ++) {
 int pos = i * 2;
 result [i] = (byte) (HEX_NUMS_STR.indexOf (hexChars [pos]) << 4
 | HEX_NUMS_STR.indexOf (hexChars [pos + 1]));
 }
 return result;
 }

 
 / **
 * Convert the specified byte array into a hexadecimal string
 * @param b
 * @return
 * /
 public static String byteToHexString (byte [] b) {
 StringBuffer hexString = new StringBuffer ();
 for (int i = 0; i <b.length; i ++) {
 String hex = Integer.toHexString (b [i] & 0xFF);
 if (hex.length () == 1) {
 hex = ‘0’ + hex;
 }
 hexString.append (hex.toUpperCase ());
 }
 return hexString.toString ();
 }
 
 / **
 * Verify password is valid
 * @param password
 * @param passwordInDb
 * @return
 * @throws NoSuchAlgorithmException
 * @throws UnsupportedEncodingException
 * /
 public static boolean validPassword (String password, String passwordInDb)
 throws NoSuchAlgorithmException, UnsupportedEncodingException {
 // Convert password in hex string format into byte array
 byte [] pwdInDb = hexStringToByte (passwordInDb);
 // Declaring the salt variable
 byte [] salt = new byte [SALT_LENGTH];
 // Extract the salt from the password byte array stored in the database
 System.arraycopy (pwdInDb, 0, salt, 0, SALT_LENGTH);
 // Create a message summary object
 MessageDigest md = MessageDigest.getInstance ("MD5");
 // Pass the salt data into the message digest object
 md.update (salt);
 // Pass the password data to the message digest object
 md.update (password.getBytes ("UTF-8"));
 // Generate a message digest for the entered password
 byte [] digest = md.digest ();
 // Declare a variable that holds the password message digest in the database
 byte [] digestInDb = new byte [pwdInDb.length-SALT_LENGTH];
 // Get the message summary of the password in the database
 System.arraycopy (pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length);
 // Compare whether the message digest generated based on the input password and the message digest in the database are the same
 if (Arrays.equals (digest, digestInDb)) {
 // Password returns password match message correctly
 return true;
 } else {
 // Password is incorrect. Password mismatch is returned.
 return false;
 }
 }


 / **
 * Get encrypted hexadecimal password
 * @param password
 * @return
 * @throws NoSuchAlgorithmException
 * @throws UnsupportedEncodingException
 * /
 public static String getEncryptedPwd (String password)
 throws NoSuchAlgorithmException, UnsupportedEncodingException {
 // Declare the encrypted password array variable
 byte [] pwd = null;
 // random number generator
 SecureRandom random = new SecureRandom ();
 // Declaring a salt array variable
 byte [] salt = new byte [SALT_LENGTH];
 // Put a random number into a salt variable
 random.nextBytes (salt);

 // Declaration message summary object
 MessageDigest md = null;
 // Create a message summary
 md = MessageDigest.getInstance ("MD5");
 // Pass the salt data into the message digest object
 md.update (salt);
 // Pass the password data to the message digest object
 md.update (password.getBytes ("UTF-8"));
 // Get the byte array of the message summary
 byte [] digest = md.digest ();

 // Because salt is stored in the byte array of the password, add the byte length of the salt
 pwd = new byte [digest.length + SALT_LENGTH];
 // Copy the salt's bytes to the first 12 bytes of the generated encrypted password byte array, in order to remove the salt when verifying the password
 System.arraycopy (salt, 0, pwd, 0, SALT_LENGTH);
 // Copy the message digest to the byte of the encrypted password byte array starting from the 13th byte
 System.arraycopy (digest, 0, pwd, SALT_LENGTH, digest.length);
 // Convert the password encrypted in byte array format into a password in hexadecimal string format
 return byteToHexString (pwd);
 }
}


Test the class--client with the following code:


package com.zyg.security.md5;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class Client {
 private static Map users = new HashMap ();
 
 public static void main (String [] args) {
 String userName = "zyg";
 String password = "123";
 registerUser (userName, password);
 
 userName = "changong";
 password = "456";
 registerUser (userName, password);
 
 String loginUserId = "zyg";
 String pwd = "1232";
 try {
 if (loginValid (loginUserId, pwd)) {
 System.out.println ("Welcome to login !!!");
 } else {
 System.out.println ("Password is wrong, please re-enter !!!");
 }
 } catch (NoSuchAlgorithmException e) {
 // TODO Auto-generated catch block
 e.printStackTrace ();
 } catch (UnsupportedEncodingException e) {
 // TODO Auto-generated catch block
 e.printStackTrace ();
 }
 }
 
 / **
 * registered user
 *
 * @param userName
 * @param password
 * /
 public static void registerUser (String userName, String password) {
 String encryptedPwd = null;
 try {
 encryptedPwd = MyMD5Util.getEncryptedPwd (password);
 
 users.put (userName, encryptedPwd);
 
 } catch (NoSuchAlgorithmException e) {
 // TODO Auto-generated catch block
 e.printStackTrace ();
 } catch (UnsupportedEncodingException e) {
 // TODO Auto-generated catch block
 e.printStackTrace ();
 }
 }
 
 / **
 * Verify login
 *
 * @param userName
 * @param password
 * @return
 * @throws UnsupportedEncodingException
 * @throws NoSuchAlgorithmException
 * /
 public static boolean loginValid (String userName, String password)
 throws NoSuchAlgorithmException, UnsupportedEncodingException {
 String pwdInDb = (String) users.get (userName);
 if (null! = pwdInDb) {// The user exists
 return MyMD5Util.validPassword (password, pwdInDb);
 } else {
 System.out.println ("The user does not exist !!!");
 return false;
 }
 }
} 


PS: Here again to provide you with 2 MD5 encryption tools, interested friends can refer to:



MD5 Online Encryption Tool:



Http://tools.jb51.net/password/CreateMD5Password



Online md5/hash/sha-1/sha-2/sha-256/sha-512/sha-3/ripemd-160 Encryption Tool:



Http://tools.jb51.net/password/hash_md5_sha



Java implementation of MD5 encryption and decryption code instance sharing


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.