Generating the key through SecureRandom.getInstanceStrong()?
-
How to create a secret key with SecureRandom.getInstanceStrong()?
Through this code, I'm getting a lot of Byte. Is there any other way to generating the key of the given length?256 Battery, for example, of a given data type (int, Stringand the intended 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()); }
}
We'll get something like this out:
Key: 8fcea84897f48f575c22441ece4e7ddb43ac08cd2c1a83fca46c080768468059
-
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(); }