Add salt hash the correct way to save the password

Source: Internet
Author: User
Tags arrays constant diff hash

See a very good article, introduced the system in the password to save the various problems encountered and solutions.

Not much to say, directly on the code, the original link in the last

/* * Password Hashing with PBKDF2 (http://crackstation.net/hashing-security.htm).
 * Copyright (c), Taylor Hornby * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, is permitted provided that Following conditions is met: * * 1. Redistributions of source code must retain the above copyright notice, * This list of conditions and the following DISCL
 Aimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * This list of conditions and the following dis
 Claimer in the documentation * and/or and materials provided with the distribution. * * This software are provided by the COPYRIGHT holders and CONTRIBUTORS "as are" * and any EXPRESS OR implied warranties , including, LIMITED to, the * implied warranties of merchantability and FITNESS for A particular PURPOSE * AR E disclaimed. In NO EVENT shall the COPYRIGHT HOLDER OR CONTRIBUTORS is * liable for any DIRECT, INdirect, incidental, special, exemplary, OR * consequential damages (including, but not LIMITED to, procurement of * S) Ubstitute GOODS OR SERVICES; LOSS of Use, DATA, OR profits;  or business * interruption) however caused and on any theory of liability, WHETHER in * contract, STRICT liability, OR 
 TORT (including negligence OR OTHERWISE) * arising in any-out-of-the----the-software, even IF advised of the
 * Possibility of SUCH DAMAGE.
*/import Java.security.SecureRandom;
Import Javax.crypto.spec.PBEKeySpec;
Import Javax.crypto.SecretKeyFactory;
Import Java.math.BigInteger;
Import java.security.NoSuchAlgorithmException;

Import java.security.spec.InvalidKeySpecException;
 /* * PBKDF2 salted password hashing. * AUTHOR:HAVOC at Defuse.ca * www:http://crackstation.net/hashing-security.htm */public class PasswordHash {Publ

    IC static final String pbkdf2_algorithm = "PBKDF2WITHHMACSHA1"; The following constants may be changed without breaking existing haShes.
    public static final int salt_byte_size = 24;
    public static final int hash_byte_size = 24;

    public static final int pbkdf2_iterations = 1000;
    public static final int iteration_index = 0;
    public static final int salt_index = 1;

    public static final int pbkdf2_index = 2;
     /** * Returns A salted PBKDF2 hash of the password. * * @param password * The password to hash * @return A salted PBKDF2 hash of the password *
        /public static String CreateHash (string password) throws NoSuchAlgorithmException, Invalidkeyspecexception {
    Return CreateHash (Password.tochararray ());
     }/** * Returns a salted PBKDF2 hash of the password. * * @param password * The password to hash * @return A salted PBKDF2 hash of the password *
        /public static String CreateHash (char[] password) throws NoSuchAlgorithmException, Invalidkeyspecexception {
     Generate a random salt   SecureRandom random = new SecureRandom ();
        Byte[] Salt = new byte[salt_byte_size];

        Random.nextbytes (salt);
        Hash the password byte[] hash = PBKDF2 (password, salt, pbkdf2_iterations, hash_byte_size);
    Format Iterations:salt:hash return pbkdf2_iterations + ":" + tohex (salt) + ":" + tohex (hash);
     }/** * Validates a password using a hash. * * @param password * The password to check * @param correcthash * The hash of T He valid password * @return True if the password is correct, false if not */public static Boolean Validatep
        Assword (string password, string correcthash) throws NoSuchAlgorithmException, Invalidkeyspecexception {
    Return ValidatePassword (Password.tochararray (), Correcthash);
     }/** * Validates a password using a hash. * * @param password * The password to check * @param correcthash *            The hash of the valid password * @return True if the password is correct, false if not */public Static Boolean ValidatePassword (char[] password, String correcthash) throws NoSuchAlgorithmException, Invalid
        keyspecexception {//Decode the hash into its parameters string[] params = Correcthash.split (":");
        int iterations = Integer.parseint (Params[iteration_index]);
        byte[] Salt = Fromhex (Params[salt_index]);
        Byte[] hash = Fromhex (Params[pbkdf2_index]); Compute the hash of the provided password, using the same salt,//iteration count, and hash length byt
        e[] Testhash = PBKDF2 (password, salt, iterations, hash.length); Compare the hashes in constant time.
        The password is correct if//both hashes match.
    Return Slowequals (hash, testhash); }/** * Compares-byte arrays in length-constant time. This comparison method * was used so that password Hashes cannot is extracted from the on-line * system using a timing attack and then attacked off-line. * * @param A * The first byte array * @param b * The second byte array * @ Return true if both byte arrays is the same, false if not */private static Boolean slowequals (Byte[] A, byte[]
        b) {int diff = a.length ^ b.length;
        for (int i = 0; i < a.length && i < b.length; i++) diff |= A[i] ^ b[i];
    return diff = = 0;
     }/** * Computes the PBKDF2 hash of a password.
     * * @param password * The password to hash.
     * @param salt * The salt * @param iterations * The iteration count (slowness factor) * @param bytes * The length of the hash to compute in bytes * @return The PBDKF2 hash of the PAS Sword */private static byte[] PBKDF2 (char[] password, byte[] salt, int iterations, int bytes) throws NoSuchAlgorithmException, invalidkeyspecexception {pbekeyspec spec = new PB
        Ekeyspec (password, salt, iterations, bytes * 8);
        Secretkeyfactory SKF = secretkeyfactory.getinstance (pbkdf2_algorithm);
    return Skf.generatesecret (spec). getencoded ();
     }/** * Converts a string of hexadecimal characters into a byte array. * * @param hex * The hex String * @return the hex string decoded into a byte array */P
        Rivate static byte[] Fromhex (String hex) {byte[] binary = new Byte[hex.length ()/2]; for (int i = 0; i < binary.length; i++) {Binary[i] = (byte) integer.parseint (hex.substring (2 * I, 2 * i +
        2), 16);
    } return binary;
     }/** * Converts a byte array into a hexadecimal string. * * @param array * The byte array to convert * @return a length*2 character string encoding the
byte array */    private static String Tohex (byte[] array) {BigInteger bi = new BigInteger (1, array);
        String hex = bi.tostring (16);
        int paddinglength = (Array.Length * 2)-hex.length ();
        if (Paddinglength > 0) return String.Format ("%0" + Paddinglength + "D", 0) + hex;
    else return hex; }/** * Tests the basic functionality of the PasswordHash class * * @param args * Igno Red */public static void main (string[] args) {try {//Print out of hashes for
                (int i = 0; i < ten; i++)

            System.out.println (Passwordhash.createhash ("p\r\nassw0rd!"));
            Test Password Validation Boolean failure = false;
            System.out.println ("Running tests ...");
                for (int i = 0; i < i++) {String password = "" + I;
                String hash = createhash (password); String Secondhash= CreateHash (password);
                    if (Hash.equals (Secondhash)) {System.out.println ("failure:two hashes is equal!");
                Failure = true;
                } String Wrongpassword = "" + (i + 1); 
                    if (ValidatePassword (Wrongpassword, hash)) {System.out.println ("Failure:wrong PASSWORD accepted!");
                Failure = true; } if (!validatepassword (password, hash)) {System.out.println ("Failure:good password
                    Not accepted! ");
                Failure = true;
            }} if (failure) System.out.println ("TESTS failed!");
        else System.out.println ("TESTS passed!");
        } catch (Exception ex) {System.out.println ("ERROR:" + ex); }
    }

}

English original text
Chinese translation

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.