...
Code Block | ||
---|---|---|
| ||
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public final class HashExamples { private String salt = "ia0942980234241sadfaewvo32"; //Randomly generated private void setPassword(String pass) throws Exception { MessageDigest sha_1 = MessageDigest.getInstance("SHA-1"); byte[] hashVal = sha_1.digest((pass+salt).getBytes()); //encode the string and salt saveBytes(hashVal,"credentials.pw"); //save the hash value to credentials.pw } private boolean checkPassword(String pass) throws Exception { MessageDigest sha_1 = MessageDigest.getInstance("SHA-1"); byte[] hashVal1 = sha_1.digest((pass+salt).getBytes()); //encode the string and salt byte[] hashVal2 = loadBytes("credentials.pw"); //load the hash value stored in credentials.pw return Arrays.equals(hashVal1, hashVal2); } } |
This code example examples implements the SHA-1 hash function through the MessageDigest class in order to compare hash values instead of cleartext strings. While this fixes the above decryption problem, however it at runtime this code may inadvertently store the passwords as cleartext. This is because due to the fact that the pass
arguments may not be cleared from memory by the Java garbage collector until much later. See "MSC10-J. Limit the lifetime of sensitive data", for more information.
...