Java implementation MD5 encryption and decryption of code instance sharing _java

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

Foundation: The use of messagedigest classes

In fact, in Java to complete MD5 encryption, messagedigest most of the class to help you achieve good, a few lines of code enough:

/**
 * For string MD5 encryption
 *
 @param str
 * @return
/import java.security.MessageDigest;
public static string getMD5 (String str) {
 try {
 //Generate a MD5 Cryptographic Calculation digest
 messagedigest MD = Messagedigest.getinstance ("MD5");
 Compute the MD5 function
 md.update (str.getbytes ());
 Digest () finally determines that the MD5 hash value is returned and the return value is 8 as a string. Because the MD5 hash value is a 16-bit hex value, it is actually a 8-bit character
 //BigInteger function that converts a 8-bit string into a 16-bit hex value, represented by a string; hash value in string form return
 new BigInteger (1, Md.digest ()). ToString ();
 catch (Exception e) {
 throw new Speedexception ("MD5 encryption Error");
 }

Advanced: Encryption and Decryption class
Java Implementation MD5 encryption and decryption class, with the test class, see Code.

MD5 encryption decryption class--mymd5util, code 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; /** * Converts a 16-string into a byte array * @param hex * @return/public static byte[] Hexstringtobyte (string hex) {int len = (he
 X.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; /** * Converts the specified byte array to a 16-character string * @param b * @return/public static string bytetohexstring (byte[] b) {Stringbuffe
 R 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 U Nsupportedencodingexception */public static Boolean Validpassword (string password, string passwordindb) throws Nosucha Lgorithmexception, Unsupportedencodingexception {//convert 16 string format password to byte array byte[] pwdindb = Hexstringtobyte (passwordindb
 );
 Declare 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 digest object MessageDigest MD = messagedigest.getinstance ("MD5");
 The salt data is passed into the Message digest object Md.update (salt);
 Pass the password's data to the Message Digest object Md.update (Password.getbytes ("UTF-8"));
 Generates a message digest for the input password byte[] Digest = Md.digest ();
 Declares a variable byte[] that holds the password message digest in the database digestindb = new Byte[pwdindb.length-salt_length];
 Gets the message digest for the password in the database system.arraycopy (pwdindb, Salt_length, digestindb, 0, digestindb.length); ThanThe message digest based on the input password and the message digest in the database are the same if (Arrays.equals (Digest, DIGESTINDB)) {//password correctly returns the password matching message return true;
 else {//password incorrect return password mismatch message returns false; /** * Obtains encrypted 16-in-form password * @param password * @return * @throws nosuchalgorithmexception * @throws Unsupportedenco Dingexception */public static string Getencryptedpwd (string password) throws NoSuchAlgorithmException, Unsupportedenco
 dingexception {///declares the encrypted password array variable byte[] pwd = null;
 Random number generator SecureRandom random = new SecureRandom ();
 Declare salt array variable byte[] Salt = new Byte[salt_length];

 Put the random number into the salt variable random.nextbytes (salt);
 Declares a message digest object MessageDigest MD = NULL;
 Create message Digest MD = messagedigest.getinstance ("MD5");
 The salt data is passed into the Message digest object Md.update (salt);
 Pass the password's data to the Message Digest object Md.update (Password.getbytes ("UTF-8"));

 Gets the byte array of the message digest byte[] Digest = Md.digest ();
 Because you want to store the salt in the byte array of the password, add the byte length of the salt pwd = new Byte[digest.length + salt_length];
 Copies the byte of the salt to the first 12 bytes of the generated encrypted password byte array so that the salt system.arraycopy (salts, 0, pwd, 0, salt_length) are removed when the password is validated; Copy message digest to encrypted password byte array from 13th wordSection begins with Byte System.arraycopy (digest, 0, pwd, salt_length, digest.length);
 Converts the password in the encrypted byte array format to the password return bytetohexstring (PWD) in the 16 string format;

 }
}

Test class--client, code as follows:

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 error, please re-enter!!!
 ");
 The 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 * @thro WS NoSuchAlgorithmException */public static Boolean loginvalid (String username,string password) throws Nosuchalgorit
 Hmexception, unsupportedencodingexception{String pwdindb = (string) users.get (userName);
 if (NULL!=PWDINDB) {//the user exists return Mymd5util.validpassword (password, pwdindb); }else{System.out.println ("The user is not present!!!
 ");
 return false;
 }
 }
}

PS: Here again for you to provide 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

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.