Mainly used for plaintext password encryption string stored in the database . Thinking from prism gate . At present, most enterprises are plaintext password . Once broken . The harm is very great . Now the mainstream encryption technology is MD5 encryption . however MD5 There is a small probability of collision ( According to the definition of cryptography , If the content is different in plaintext , The result of hash algorithm ( Cryptography is called information digest ) identical , It's called happening “ Collision ”.). How to generate md5 The algorithm of collision http://www.infosec.sdu.edu.cn/paper/md5-attack.pdf. Some hackers break passwords in a way called “ Run the dictionary ” Methods . There are two ways to get a dictionary , One is the daily collection of string tables used as passwords , The other is generated by permutation and combination , First use MD5 The program calculates the MD5 value , Then use the target MD5 Values are retrieved in this dictionary . Even assuming that the maximum length of the password is 8, At the same time, the password can only be letters and numbers , common 26+26+10=62 Characters , The number of items in the dictionary is P(62,1)+P (62,2)….+P(62,8), That's a very astronomical number , Storing this dictionary requires TB Level disk group , And there's a premise to this approach , It's about getting the target account password MD5 Only when it's worth it . When the user's password is weak, it's dangerous .

PBKDF2WithHmacSHA1 Algorithm ratio MD5 The algorithm is more secure . It can generate different encryptions with the same password at different times Hash. Running dictionary will be invalid . Here's the algorithm Demo.

 package hashpassword;
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
{
public 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 = 10; public static final int ITERATION_INDEX = 0;
public static final int SALT_INDEX = 1;
public static final int PBKDF2_INDEX = 2; public static String createHash(String password)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
return createHash(password.toCharArray());
} /**
* Returns a salted PBKDF2 hash of the password.
* Return to a salted PBKDF2 The hash code
* @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 And then the salt sequence
SecureRandom random = new SecureRandom();
byte[] salt = new byte[SALT_BYTE_SIZE];
random.nextBytes(salt); // Hash the password Generate hash password
byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
// format iterations:salt:hash format The number of 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 the valid password
* @return true if the password is correct, false if not
*/
public static boolean validatePassword(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, InvalidKeySpecException
{
// 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
byte[] 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 two byte arrays in length-constant time. This comparison method
* is used so that password hashes cannot be extracted from an 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 are 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.
* Calculation PBKDF2 The hash code
* @param password the password to hash. Need encrypted plaintext password
* @param salt the salt Salt increases seasoning Increase the difficulty of password cracking
* @param iterations the iteration count (slowness factor) The number of iterations
* @param bytes the length of the hash to compute in bytes After calculating the password Hash length
* @return the PBDKF2 hash of the password
*/
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
PBEKeySpec spec = new PBEKeySpec(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
*/
private 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 ignored
*/
public static void main(String[] args)
{
try
{
// Print out 10 hashes
for(int i = 0; i < 10; 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 < 100; i++)
{
String password = ""+i;
String hash = createHash(password);
String secondHash = createHash(password);
if(hash.equals(secondHash)) {
System.out.println("FAILURE: TWO HASHES ARE 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);
}
} }

https://crackstation.net/hashing-security.htm

PBKDF2WithHmacSHA1 More articles on Algorithms

  1. How to generate a secure password Hash:MD5, SHA, PBKDF2, BCrypt Example

    password Hash The generation of value is the encrypted character sequence obtained by using a certain algorithm to calculate the password provided by the user . stay Java There are many things that have been proven to be effective in password security Hash Algorithm implementation , I'll discuss some of the algorithms in this article . Need to be ...

  2. keystore The algorithm used by the key file -PBKDF2WithHmacSHA1 and Scrypt

    PBKDF2 To put it simply, I will salted hash Do multiple repetitions , This number is optional . If the time required for a calculation is 1 Microsecond , Then calculate 1 A million times 1 Second . If you need to attack a password rainbow table ...

  3. java Encryption type and algorithm name

    There are various encryption methods in the project , But it has never been studied carefully . It's usually just copy. There are some problems these days , Took a look at the encryption code , I feel a little confused . We know jdk A lot of algorithms have been packaged for us . But what algorithms are packaged , How do I get rid of these algorithms ...

  4. B Trees —— Introduction to algorithms (25)

    B Trees 1. brief introduction Before we learned about the red black tree , Today I'll learn another kind of tree --B Trees . It has a lot in common with the red black tree , For example, they are all balanced search trees , But they are quite different in function and structure . functionally ,B Trees are designed for disks or other storage devices , ...

  5. Distributed series ——Paxos Algorithm principle and derivation

    Paxos Algorithms play a very important role in the field of distributed computing . however Paxos The algorithm has two obvious shortcomings :1. Difficult to understand 2. Engineering is more difficult . There are many explanations on the Internet Paxos Algorithm article , But the quality is uneven . Read a lot about Paxos The capital of ...

  6. 【Machine Learning】KNN Algorithm iris image recognition

    K- Nearest neighbor algorithm for iris image recognition author : Bai Ningchao 2017 year 1 month 3 Japan 18:26:33 Abstract : With the upsurge of machine learning and deep learning , All kinds of books come out one after another . However, most of them are the introduction of basic theoretical knowledge , Lack of deep understanding of implementation . This series of articles is the author's conclusion ...

  7. Red and black trees &mdash;&mdash; Introduction to algorithms (15)

    1. What is a red-black tree (1) brief introduction     In the last article, we introduced the basic dynamic set operation with time complexity of O(h) Binary search tree of . But unfortunately , Only when the height of the binary search tree is low , These set operations are faster : That is, when the height of the tree is high ( Even a kind of extreme ...

  8. Hash table (hash table)—— Introduction to algorithms (13)

    1. introduction Many applications require a dynamic set structure , It needs at least support Insert,search and delete Dictionary operation . Hash table (hash table) It is an effective data structure to realize dictionary operation . 2. Direct addressing table In introducing hash ...

  9. fictitious dom And diff Algorithm analysis

    A collection of good articles : Explain profound theories in simple language React( Four ): fictitious DOM Diff Algorithm analysis A comprehensive understanding of virtual DOM, Realize virtual DOM

Random recommendation

  1. Solve why every time you open Eclipse new workspace You need to update nexus-maven-repository-index problem

    Solve why every time you open Eclipse new workspace You need to update nexus-maven-repository-index problem Create a new one Eclipse Of workspace. open Window—>Pr ...

  2. js Flow control statement

    do...while sentence do...while Statement is a way to run first , Loop statement of post judgment . in other words , Whether or not the conditions are met , Run the loop at least once . var box = 1;                      ...

  3. Find pattern string [XDU1032]

    Problem 1032 - Find pattern string Time Limit: 1000MS   Memory Limit: 65536KB   Difficulty: Total Submit: 644  Acce ...

  4. MAT Use summary

    Recently, I encountered a memory leak when I was working on a project , Finally through MAT It's positioning the problem , Let me introduce you MAT Some basic concepts of : Shallow Heap: The size of the memory occupied by the object itself , Does not contain references to other objects , That is, object header plus member variable ( No ...

  5. install appuim

    One . As a software tester , Requirements for work habits and quality , Be sensitive to the problem , You can't let go of problems easily , Save in advance all the information that may be helpful to analyze and solve the problem , Not afraid of trouble , As comprehensive and detailed as possible , Don't miss the point . If the nerve is big , It's too much trouble , No ...

  6. python introduction (10) Use List and tuple

    python introduction (10) Use List and tuple list Python One of the built-in data types is list :list.list It's an orderly collection , You can add and remove elements at any time . such as , List the names of all the students in the class , Can be ...

  7. Map Collection , On the value and traversal of the relevant operations

    It's about myself map A small study of related operations of sets , Share with you . The main code content includes the following : 1,map Traversal of the set 2, according to key Values obtained value value 3, according to value Values obtained key value 4, Return to max value Value correspondence ...

  8. LeetCode Algorithm problem -Repeated Substring Pattern(Java Realization )

    This is the number one of Yuele book 236 Secondary update , The first 249 Original article 01 Reading and preparation Today's presentation is LeetCode Algorithm problem Easy Rank No. 103 topic ( Sequence question no 459). Given a non empty string, check if you can get its substring and add the substring ...

  9. Talk about right Python My cognition and expectation

    18 A freshman , I didn't know programming language before I went to university , In many language programming, only C Language has a name recognition . I first learned about last semester Python Language , The computer teacher said Python It's the computer language which is developing rapidly in the programming language ...

  10. 【cf849D】Rooter&#39;s Song( thinking )

    D. Rooter's Song The question x Axis .y There's... On the shaft n personal , The first i personal \(g_i==1\) Then the coordinates are \((p_i,0)\) otherwise \((0,p_i)\),\(t_i\) Seconds from the vertical axis , Reach the border x=w ...