Java about Md5+salt Salt encryption verification

Source: Internet
Author: User
Tags string format



I. State the Workflow:



1. According to the existing password string to generate a password + salt string, You can also store the salt of the encrypted string in the database (see requirements),



2. Verify that the submitted password string is encrypted and then obtained from the database with the existing salt combination cipher + salt string and existing validation


Package com.mi.util;

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

Public class Md5SaltTool {

    Private static final String HEX_NUMS_STR="0123456789ABCDEF";
    Private static final Integer SALT_LENGTH = 12;
       
    /**
     * Convert hexadecimal strings to byte arrays
     * @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 to a hex 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 that the password is legal
     * @param password
     * @param passwordInDb
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    Public static boolean validPassword(String password, String passwordInDb)
            Throws NoSuchAlgorithmException, UnsupportedEncodingException {
        / / Convert the hexadecimal string format password to a byte array
        Byte[] pwdInDb = hexStringToByte(passwordInDb);
        / / Declare the salt variable
        Byte[] salt = new byte[SALT_LENGTH];
        / / Extract the salt from the password byte array saved in the database
        System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH);
        / / Create a message summary object
        MessageDigest md = MessageDigest.getInstance("MD5");
        / / In the salt data into the message summary object
        Md.update(salt);
        / / Pass the password data to the message digest object
        Md.update(password.getBytes("UTF-8"));
        / / Generate a message digest of the input password
        Byte[] digest = md.digest();
        / / Declare a variable to save the password message summary 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 the message digest generated according to the input password and the message digest in the database are the same
        If (Arrays.equals(digest, digestInDb)) {
            / / Password correctly returns password matching message
            Return true;
        } else {
            / / Password incorrectly returns a password does not match the message
            Return false;
        }
    }
  
    /**
     * Obtain 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();
        / / Declare the salt array variable 12
        Byte[] salt = new byte[SALT_LENGTH];
        / / Put the random number into the salt variable
        random.nextBytes(salt);
  
        / / Declare the message summary object
        MessageDigest md = null;
        / / Create a message digest
        Md = MessageDigest.getInstance("MD5");
        / / In the salt data into the message summary 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 digest
        Byte[] digest = md.digest();
  
        / / Because the salt is stored in the byte array of the password, so add the length of the salt
        Pwd = new byte[digest.length + SALT_LENGTH];
        / / Copy the salt 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);
        For(int i=0;i<pwd.length;i++){
            System.out.print(pwd[i]);
        }
        / / Convert the password encrypted in byte array format to a password in hexadecimal string format
        Return byteToHexString(pwd);
    }
} 


The test classes are as Follows:


Package com.mi.util;

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

Public class Md5SaltTest {

      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!!!");
                }
            } 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 = Md5SaltTool.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 loginUserId = "zyg";
               String pwd = "1232";*/
            String pwdInDb = (String)users.get(userName);
            If(null!=pwdInDb){ // The user exists
                    Return Md5SaltTool.validPassword(password, pwdInDb);
            }else{
                System.out.println("There is no such user!!!");
                Return false;
            }
        }
} 





Java about Md5+salt Salt encryption verification


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.