Frage

I have am trying to use PBKDF2 to store passwords. I am then using the code with the password hashes it generated on a different machine.

I am using this method to encrypt my passwords:

public  String pwdEncodePBKDF2(String unencryptedPassword,String salt)
{
try
{
        if(salt.isEmpty())
        {
            salt = generateSalt(SystemSecurity.SALTLENGTH);
        }
        String algorithm = "PBKDF2WithHmacSHA1";
        int derivedKeyLength = 160;
        int iterations = 1000;
        KeySpec spec = new PBEKeySpec(unencryptedPassword.toCharArray(), salt.getBytes(), iterations, derivedKeyLength);
        SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);
        StringBuffer hexString = new StringBuffer();
        byte[] mdbytes  =  f.generateSecret(spec).getEncoded();
        for (int i=0;i<mdbytes.length;i++)
        {
            hexString.append(Integer.toHexString(0xFF & mdbytes[i]));
        }
        String hashedPassword = hexString.toString();
        return hashedPassword  + salt;
    }
    catch(Exception e)
    {
        e.printStackTrace();
        throw new RuntimeException("Error computing hash: "+e.getMessage());
    }        
}

It works fine, but when I run it on a different machine (i.e. install my project on a different machine, with a database that has an encrypted of a default password from the machine I run on initially) I see that with the same salt and password it give me a different encryption. As far as I understand the SecretKeyFactory methods depend only on the inputs I give them, or do they depend on the machine I am running on as well?

If so, how can I save a default password for first installation with this security mechanism without running any extra code during installation?

Thank You!

War es hilfreich?

Lösung

I think the problem may be in different default String encodings.

Check that your strings use same encoding.

you can try to check bytes using

salt.getBytes()
  • it return bytes in default encoding, may be machines has different encodings.

You can just replace salt.getBytes(), with somethink like salt.getBytes("UTF-8"); may be it will help.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top