After searching in Google and watching a few posts in StackOverflow ( Java hashing passwords , Hashing Password ). I try not to duplicate questions and looking for the answers by myself, but as you can appreciate, this was not the case.
I'm creating a simple library in Java to hash passwords using SHA256 algorithm.
Everytime I create a hash the password generated is different. This happens with SHA256 and MD5 algorithms.
Why is this happening? I think that passwords generated should be the same. I may be totally wrong and confused about how hashing works.
The hashing method:
CipherString.java
public static String cipherPassword(String pwd, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException
{
MessageDigest d = MessageDigest.getInstance("SHA-256");
d.update(salt.getBytes("UTF-8"));
byte[] hash = d.digest(pwd.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for(int i=0; i< hash.length ;i++)
{
sb.append(Integer.toString((hash[i] & 0xff) + 0x100, 16).substring(1));
}
String pwdCifrada = sb.toString();
return pwdCifrada;
}
EDIT:
Old Main.java (bugged code)
String username = txtUsername.getText();
char[] password = txtPassword.getPassword();
String hashedPassword = cipherPassword(password.toString(), username);
New Main.java (fixed/solved code)
String username = txtUsername.getText();
char[] password = txtPassword.getPassword();
String hashedPassword = cipherPassword(new String(password), username);
I have deleted all the models, view and controllers which are unneeded.
Thank you all.