-1

I'm attempting to hash a password for storage in a database, I keep getting an arrayIndexOutOfBounds error though.

I call signup("Test","password") and the output is Test 35.. can anyone point me in the right direction please, thank you!

public static void signup(String username, String password) {
    String saltedPassword = SALT + password;
    String hashedPassword = generateHash(saltedPassword);
    DB.put("username", hashedPassword);
}

public static String generateHash(String input){
    StringBuilder hash= new StringBuilder();
    try {
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] hashedBytes = sha.digest(input.getBytes());
        char [] digits = {'0','1','2','3','4','5','6','a','b','c','d','e','f'};
        for (int idx = 0; idx<hashedBytes.length; idx++) {
            byte b = hashedBytes[idx];
            hash.append(digits[(b & 0xf0)>>4]);
            hash.append(digits[b & 0x0f]);   //<<<<<<<------ Error on this line.
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return hash.toString();     
}
dur
  • 15,689
  • 25
  • 79
  • 125
Chance212
  • 31
  • 6

2 Answers2

4

You are missing some hex digits so the array indexes (at expected length 16) fail. This

char [] digits = {'0','1','2','3','4','5','6','a','b','c','d','e','f'};

should include 7,8 and 9 like

char [] digits = {'0','1','2','3','4','5','6','7','8','9',
        'a','b','c','d','e','f'};
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Thank you! I am trying to a login page for a user in a web application, the only way I can figure out to do it is to perform the same hashing method to a password they enter and compare it to the stored one, if the entered password hash and stored password hash match then allow access... Do you think this would be sufficient? – Chance212 Apr 11 '16 at 21:24
0

Your array index is going to be out of bounds. You're trying to access the 16th element of an array that holds only 13 elements.

I suspect you've simply missed 7, 8 and 9 from your digits array.

char [] digits = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
ManoDestra
  • 6,325
  • 6
  • 26
  • 50