import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class Password {
private void setPassword(byte[] pass) throws Exception {
byte[] salt = generateSalt(12);
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(salt, "salt.bin");
saveBytes(hashVal,"password.bin"); // Save the hash value to password.bin
}
private boolean checkPassword(byte[] pass) throws Exception {
byte[] salt = loadBytes("salt.bin");
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("password.bin"); // Load the hash value stored in password.bin
return Arrays.equals(hashVal1, hashVal2);
}
private byte[] generateSalt(int n) {
// Generate a random byte array of length n
}
private byte[] appendArrays(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;
}
}
}
|