Java Reference
In-Depth Information
saveBytes(hashVal,"password.bin");
}
boolean checkPassword(String pass) throws Exception {
byte[] salt = loadBytes("salt.bin");
MessageDigest msgDigest = MessageDi-
gest.getInstance("SHA-256");
// Encode the string and salt
byte[] hashVal1 = msgDigest.digest((pass+salt).getBytes());
// Load the hash value stored in password.bin
byte[] hashVal2 = loadBytes("password.bin");
return Arrays.equals(hashVal1, hashVal2);
}
private byte[] generateSalt(int n) {
// Generate a random byte array of length n
}
}
Even when an attacker knows that the program stores passwords using SHA-256 and a
12-byte salt, he or she will be unable to retrieve the actual password from password.bin
and salt.bin .
Althoughthisapproachsolvesthedecryptionproblemfromthepreviousnoncompliant
codeexample,thisprogrammayinadvertentlystorethepasswordsascleartextinmemory.
Java String objects are immutable, and can be copied and internally stored by the Java
VirtualMachine.Consequently,Javalacksamechanismtosecurelyeraseapasswordonce
it has been stored in a String . See Guideline 1 , “ Limit the lifetime of sensitive data ,” for
more information.
Compliant Solution
This compliant solution addresses the problems from the previous noncompliant code ex-
ample by using a byte array to store the password:
Click here to view code image
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class Password {
private void setPassword(byte[] pass) throws Exception {
byte[] salt = generateSalt(12);
Search WWH ::




Custom Search