I'm trying to store a hash of a password into a .txt
file in my apps file directory, however all that seems to be getting stored or read is the memory location rather than the actual hash.
This is the function that takes care of hashing the password:
private void hashPassword(String pass)throws UnsupportedEncodingException, NoSuchAlgorithmException {
//Hashed password is a global String
hashedPassword = hasher.hash(pass);
}
This is the Hasher class method called above to create a SHA-256 hash of the password:
public String hash(String text) throws UnsupportedEncodingException, NoSuchAlgorithmException {
byte[] b = text.getBytes(StandardCharsets.UTF_8);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return new String(digest.digest(b));
}
This is the function I use to set up the files for writing to:
//Set up a file in the directory path of the app and give it the name pass.txt and pubKey.txt
private void setUpFiles(String typeSetup) {
//Check to see if it's setting up the pass file or key file
if(typeSetup.equals("pass")){
//passFile is a global file object object
passFile = new File(makeId.this.getApplicationContext().getFilesDir(),"pass.txt");
} else if (typeSetup.equals("key")){
encryptionKeyFile = new File(makeId.this.getApplicationContext().getFilesDir(),"pubKey.txt");
}
}
And finally, this is the function that handles storing the pass:
//Store the login info provided by the user
private boolean storeLogin() throws IOException {
//Store the hashed password in a text file
setUpFiles("pass");
//Create objects to handle file writing
FileWriter pw = new FileWriter(passFile);
BufferedWriter bw = new BufferedWriter(pw);
//Write the hashed password to the file
bw.write(new String(hashedPassword));
//Close resources
bw.close();
pw.close();
//Return if the file was created or not
return passFile.exists();
}
Those were the functions to store a hashed password into a text file, below are the functions used by another activity to read from the file, store and display the hash.
public void loadPassHash() throws FileNotFoundException {
//File that should contain the hash of the password
File passFile = new File(c.getFilesDir(),"pass.txt");
//Create a textview object
tv = (TextView) findViewById(R.id.viewer);
//Create a scanner object to read the file
Scanner myScan = new Scanner(passFile);
//Initialize the text variable to store the contents of the file
String text = null;
//Loop the file and set the text to it
while (myScan.hasNext()) {
text=myScan.next();
}
//If there is something in the file
if (text!=null) {
//Set the global passHash string to the value of text
passHash=text;
//Display the hashed password for development
tv.setText(passHash);
//Close the scanner
myScan.close();
} else {
finish();
}
}
The results of this is that only a memory location is displayed and I am unable to compare the password hashes and validate the login. Any help would be appreciated.