Java Salt Value Create generateSalt()

Here you can find the source of generateSalt()

Description

Returns a salt.

License

Open Source License

Return

salt as string

Declaration

public static String generateSalt() 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.math.BigInteger;

import java.security.SecureRandom;

import java.util.Random;

public class Main {
    /**/*from w w  w .j a v a  2  s . c  om*/
     * Returns a salt.
     * <p>
     * !!!Remember to store this with the password!!!
     * If you do not, you will be sad.
     *
     * @return salt as string
     */
    public static String generateSalt() {
        final Random r = new SecureRandom();
        byte[] salt = new byte[8];
        r.nextBytes(salt);
        //byte[] saltEncoded = Base64.getEncoder().encode(salt);
        //System.out.println("GENERATED SALT: " + toHex(salt));
        return toHex(salt);
    }

    /**
     * This converts Bytes to hex strings. Written by jtan189@Github.
     * [https://gist.github.com/jtan189/3804290]
     *
     * @param array salt or hash to convert
     * @return hex string that can be stored in a database.
     */
    private static String toHex(byte[] array) {
        BigInteger bi = new BigInteger(1, array);
        String hex = bi.toString(16);
        int paddingLength = (array.length * 2) - hex.length();
        if (paddingLength > 0)
            return String.format("%0" + paddingLength + "d", 0) + hex;
        else
            return hex;
    }
}

Related

  1. generateSalt()
  2. generateSalt()
  3. generateSalt()
  4. generateSalt()
  5. generateSalt()
  6. generateSalt()
  7. generateSalt()
  8. generateSalt()
  9. generateSalt()