Jesus Gonzalez
Jesus Gonzalez

Reputation: 411

Java Hashing Password Doesn't Match

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.

Upvotes: 0

Views: 1118

Answers (1)

tbraun
tbraun

Reputation: 2666

I strongly recommend using a library to handle this for you.

Consider Apache Commons Codec library:

import org.apache.commons.codec.digest.DigestUtils;

public class HashTest {
    public static String cipher(String pwd, String salt) {
        return DigestUtils.sha256Hex(pwd+salt);
    }
    public static void main(String[] args) {
        String p = "password";
        String s = "randomSalt";
        String c = cipher(p, s);
        System.out.println(c);
    }
}

This will always print

a0494b0d7ef89bba60f9703e2c438465cd1241cc440a8fc20f4330639d2c9c2f

If you are using Maven to manage your dependencies you can check the latest version here: http://mvnrepository.com/artifact/commons-codec/commons-codec

Or use the current latest:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>

Upvotes: 1

Related Questions