Question

I've set up a fairly basic password hashing and salting system for saving passwords in my database. It works fine, but I'm not so sure about how the salt is being stored.

At the moment I'm creating it in a byte[] array, then converting that to a String, which is then stored in the database.

My only concern is that every salt starts with [B@, for example: [B@b24f11 or [B@1e71a51

Is it ok to store it like this, or should I also be leaving it as a byte[] array and storing it as binary data in the database? Or even doing something else?

public class PasswordHasher {

    // calculates a hash, given a password and a salt
    public static String getHash(String pass, String salt) {
        String hashedPassword = null;
        try{
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(salt.getBytes()); //update digest to include salt
            byte[] hashedBytes = md.digest(pass.getBytes());

            // convert byte array to hex
            StringBuilder sb = new StringBuilder();
            for (int i=0;i<hashedBytes.length;i++) {
            sb.append(Integer.toHexString((int) hashedBytes[i] & 0xFF));
        }
            hashedPassword = sb.toString();

        }catch(NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        return hashedPassword;
    }

    // calculates a hash, then returns both hash and salt to store in DB
    public static String[] registerHashAndSalt(String pass){
        String salt = getSalt();
        String hashedPassword = getHash(pass, salt);

        String[] hashAndSalt = {hashedPassword, salt};
        return hashAndSalt;
    }

    // creates a random salt
    private static String getSalt(){
    SecureRandom sr = new SecureRandom();
    byte[] salt = new byte[16];
    sr.nextBytes(salt);
    return salt.toString();
    }
}
Was it helpful?

Solution

You're not transforming the bytes to a string. You're calling toString() on a byte[], which returns the type of the array ([B) followed by the @ symbol and by the hashCode of the array.

Use base 64 or Hex encoding to transform bytes to a printable string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top