...
Code Block | ||
---|---|---|
| ||
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public final class HashExamples { private byte[] salt = "ia0942980234241sadfaewvo32".getBytes(); //Randomly generated private void setPassword(byte[] pass) throws Exception { byte[] input = appendArrays(pass, salt); MessageDigest sha_1 = MessageDigest.getInstance("SHA-1"); byte[] hashVal = sha_1.digest(input); //encode the string and salt  clearArray(pass);  clearArray(input);  saveBytes(hashVal,"credentials.pw"); //save the hash value to credentials.pw } private boolean checkPassword(byte[] pass) throws Exception { byte[] input = appendArrays(pass, salt); MessageDigest sha_1 = MessageDigest.getInstance("SHA-1"); byte[] hashVal1 = sha_1.digest(input); //encode the string and salt clearArray(pass); clearArray(input); byte[] hashVal2 = loadBytes("credentials.pw"); //load the hash value stored in credentials.pw return Arrays.equals(hashVal1, hashVal2); } private appendArrays(byte[] a, byte[] b) { //Return a new array of a appended to b } private clearArray(byte[] a) { //set all of the elements in a to zero } } |
This solution fixes the vulnerabilities in the previous two noncompliant examples. In both setPassword and checkPassword, the cleartext representation of the password is erased as soon as it is converted into a hash value. After this happens, there is no way for an attacker to get the password as cleartext.