How to correctly generate the secret key using SecureRandom. getInstanceStrong () ?

Through this code, I get an array of bytes. Are there any other ways to generate a key of a given length ( 256 bits, for example), a given data type ( int, String ) and a given format ( hex , bin, dec)?

package com.company; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class KeyGen { public void generate() throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstanceStrong(); byte[] values = new byte[32]; // 256 bit random.nextBytes(values); StringBuilder sb = new StringBuilder(); for (byte b : values) { sb.append(String.format("%02x", b)); } System.out.print("Key: "); System.out.println(sb.toString()); } } 

At the output, we get something like this:

Key: 8fcea84897f48f575c22441ece4e7ddb43ac08cd2c1a83fca46c080768468059

    1 answer 1

     public static String createHash(final char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException { final SecureRandom random = new SecureRandom(); final byte[] salt = new byte[256]; random.nextBytes(salt); final byte[] hash = pbkdf2(password, salt, 1000, 256); return "sha1:" + 1000 + ':' + toBase64(salt) + ':' + toBase64(hash); } private static byte[] pbkdf2(final char[] password, final byte[] salt, final int iterations, final int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException { final KeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); final SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); return skf.generateSecret(spec).getEncoded(); } 
    • Please try to write more detailed answers. I am sure the author of the question would be grateful for your expert commentary on the code above. - Nicolas Chabanovsky