Java - Generating a random salt isn't random

放肆的年华 提交于 2019-11-30 10:58:19

You are printing out the byte array itself, not its contents. You need to loop through the array to see what it contains.

Edit:

Also changed getSalt to return a byte array. It is not safe to return a String constructed from the byte array (with new String(salt)) as the byte sequence may not form a valid String.

import java.security.*;

public class Salt {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        getSalt();
    }
    private static byte[] getSalt() throws NoSuchAlgorithmException {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[16];
        sr.nextBytes(salt);
        for(int i = 0; i<16; i++) {
            System.out.print(salt[i] & 0x00FF);
            System.out.print(" ");
        }
        return salt;
    }
}

salt.toString is not returning content of the byte array but hashCode

If you replace to the sr.nextInt() on every request you will receive different value. If you print content of the byte array you will notice difference

SpaceTrucker

From the javadoc of java.security.SecureRandom.getInstance(String):

The returned SecureRandom object has not been seeded. To seed the returned object, call the setSeed method.

So the obvious answer is to call setSeed. However this may have it's problems when just using the time, because the seed can be guessed easily.

Another approach would be to share the secure random instance (as it is thread safe)

You can use method

/**
 * Reseeds this random object, using the eight bytes contained
 * in the given <code>long seed</code>. The given seed supplements,
 * rather than replaces, the existing seed. Thus, repeated calls
 * are guaranteed never to reduce randomness.
 *
 * <p>This method is defined for compatibility with
 * <code>java.util.Random</code>.
 *
 * @param seed the seed.
 *
 * @see #getSeed
 */
public void setSeed(long seed)

passing e.g. current time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!