Java Reference
In-Depth Information
boolean checkPassword(byte[] pass) throws Exception {
// Load the encrypted password
byte[] encrypted = loadBytes("password.bin");
byte[] decrypted = decrypt(encrypted);
boolean arraysEqual = Arrays.equal(decrypted, pass);
clearArray(decrypted);
clearArray(pass);
return arraysEqual;
}
private void clearArray(byte[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = 0;
}
}
}
An attacker could potentially decrypt this file to discover the password, particularly
when the attacker has knowledge of the key and encryption scheme used by the program.
Passwords should be protected even from system administrators and privileged users.
Consequently, using encryption is only partly effective in mitigating password disclosure
threats.
Noncompliant Code Example
Thisnoncompliantcodeexampleusesthe
SHA-256
hashfunctionthroughthe
MessageDi-
gest
classtocomparehashvaluesinsteadofcleartextstrings,butitusesa
String
tostore
the password:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class Password {
private void setPassword(String pass) throws Exception {
byte[] salt = generateSalt(12);
MessageDigest msgDigest = MessageDi-
gest.getInstance("SHA-256");
// Encode the string and salt
byte[] hashVal = msgDigest.digest((pass+salt).getBytes());
saveBytes(salt, "salt.bin");
// Save the hash value to password.bin