The Java Coding guidelines の#13 use hash functions to save password

Source: Internet
Author: User
Tags decrypt

PlainText Save password program in very many ways easy to cause password leak. Although the user enters the password in general, the plaintext form. However, the application must ensure that password is not stored in clear text.

One effective way to limit the password leakage crisis is to use a hash function. It makes it possible to indirectly compare the password of the user input to the original password, without having to save the plaintext or to decrypt the password. This approach minimizes the risk of password leaks and introduces no other drawbacks at the same time.


[Cryptographic hash Function]

The value generated by the hash function is called a hash or message hash, and the hash function computes a viable function, but the reverse is not feasible. In fact, password can be encoded as a hash value, but the hash value cannot be decoded to the corresponding password. The two password are equally capable of being inferred if their hash values are equal.

A good practice is to calculate the hash value after adding salt to the plaintext.

Salt is a unique sequence or a randomly generated piece of data. is usually stored with the hash value. The role of salt is to prevent brute-force cracking of hashes, provided that the salt is long enough to produce enough entropy (short salt values are not enough to reduce the rate of violent attacks).

Each password must have its own unique salt, assuming that multiple password share the same salt. Two users may have the same password.

The selection of the hash function and the length of the salt is a balance of safety and performance.

Choosing a high-intensity hash function to increase the difficulty of brute force is the same time that password verification is added. Increasing the length of the salt increases the difficulty of brute force, but adds additional storage space at the same time.

The Java MessageDigest class provides implementations of a variety of cryptographic hash functions. But avoid using defective hash functions, such as MD5. Hash functions such as SHA-1 and SHA-2, which are maintained by the NSA, are now safe. In practice. Very many applications use the SHA-256 hash function. Because this function takes care of both performance and security.


[Code Demo sample that does not meet security requirements]

The following code encrypts and decrypts the password stored in the Password.bin file using the symmetric encryption algorithm.

Public final class Password {private void SetPassword (byte[] pass) throws Exception {//arbitrary encryption schemebyte[] encryted = Encrypt (pass); Cleararray (pass);//encrypted password to password.binsavebytes (encrypted, "Password.bin"); Cleararray (encrypted);} Boolean Checkpassword (byte[] pass) throws Exception {//load the encrypted passwordbyte[] encrypted = loadbytes ("Password. Bin "); byte[] decrpyted = decrypt (encrypted); Boolean arraysequal = Arrays.equals (decrypted, pass); Cleararray (decrypted ); Cleararray (pass); return arraysequal;} private void Cleararray (byte[] a) {for (int i=0; i<a.length; ++i) {a[i] = 0;}}}

The above bin file may be decrypted by an attacker. Then get password, especially if the attacker knows the key and encryption method used in the program.

Password must not even be known to system administrators or privileged users.

Therefore, the use of encryption methods to prevent password leakage critical effect is limited.


[Non-compliant Code demo sample]

The following code uses the SHA-256 hash function to control a string based on the MessageDigest class. Instead of using clear text. However, it uses a string object to store the password.

public final Class Password {private void SetPassword (String pass) throws Exception {byte[] salt = generatesalt (12); MessageDigest msgdigest = messagedigest.getinstance ("SHA-256");//Encode the string and saltbyte[] Hashval = Msgdigest.di Gest (pass + salt) getBytes () savebytes (salt, "salt.bin");//Save the hash value to Password.binsavebytes (Hashval, " Password.bin ");} Boolean Checkpassword (String pass) throws Exception {byte[] salt = loadbytes ("Salt.bin"); MessageDigest msgdigest = messagedigest.getinstance ("SHA-256");//Encode the string and saltbyte[] HashVal1 = MSGDIGEST.D Igest (pass + salt). GetBytes ());//load the hash value stored in password.binbyte[] HashVal2 = loadbytes ("Password.bin"); r Eturn arrays.equals (HashVal1, hashVal2);} Private byte[] Generatesalt (int n) {//Generate a random byte array of length n}} 

Even if the attacker knew that the program was using the SHA-256 hash function and 12 bytes of salt, he could not get the real password from Password.bin and Salt.bin.

Although the above code overcomes the problem of password being decrypted, this code uses a string object to hold the password of the plaintext, so. See "#00 limits the life cycle of sensitive data" for improvements.


[Security-compliant solutions]

The following code uses a byte array to store the plaintext password.

Public final class Password {private void SetPassword (byte[] pass) throws Exception {byte[] salt = Generatesalt (n); byte[] Input = Appendarrays (pass, salt); MessageDigest msgdigest = messagedigest.getinstance ("SHA-256");//Encode the string and saltbyte[] Hashval = Msgdigest.di Gest (input); Cleararray (pass); Cleararray (input); Savebytes (Salt, "salt.bin");//Save the hash value to Password.binsavebytes (Hashval, "Password.bin"); Cleararray (salt); Cleararray (hashval);} Boolean Checkpassword (byte[] pass) throws Exception {byte[] salt = loadbytes ("Salt.bin"); byte[] input = appendarrays (pass , salt); MessageDigest msgdigest = messagedigest.getinstance ("SHA-256");//Encode the string and saltbyte[] HashVal1 = MSGDIGEST.D Igest (input); Cleararray (pass); Cleararray (input);//load the hash value stored in password.binbyte[] HashVal2 = loadbytes ("Password.bin"); Boolean arraysequal = Arrays.equals (HashVal1, HashVal2); Cleararray (HASHVAL1); Cleararray (HashVal2) ; return arraysequal;} Private byte[] Generatesalt (intN) {//Generate a random byte array of length n}private byte[] Appendarray (byte[] A, byte[] b) {//return a new array of a [] appended to b[]}private void Cleararray (byte[] a) {for (int i=0; i<a.length; ++i) {a[i] = 0;}}}

In the SetPassword () and Checkpassword () functions, the plaintext password emptied immediately after use.

As a result, an attacker would have to spend a lot of other effort to obtain plaintext password after clearing the plaintext password. Providing guaranteed password emptying is challenging, it can be platform-related, and may even be impractical because of replication garbage collection/dynamic paging/other platform mechanisms that execute under the Java language.


Applicability

Passwordeasy that are stored without a secure hash operation are acquired by an illegal user. Breach of this Treaty will result in the illegal use of procedural easy.

Applications such as the password Manager may need to obtain the original password and fill it into a third-party application. This is agreed, even if it violates this Treaty. The password manager is visited by a single user and is usually a user-licensed talent to save the user's password. At the same time according to the requirements of the password display.

Therefore, the determining factor of security depends on the user's ability rather than the function of the program.


--Welcome reprint. Please specify the source http://blog.csdn.net/asce1885 , not for commercial use without my permission, thank you--

The Java Coding guidelines の#13 use hash functions to save password

Related Article

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.