How to generate secret key using SecureRandom.getInstanceStrong()?
With this code I can receive byte array with random values. Is there any easy way to generate key of a given length (256 bits, for example), type (int, String) and 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());
}
}
Output:
Key: 8fcea84897f48f575c22441ece4e7ddb43ac08cd2c1a83fca46c080768468059
Aucun commentaire:
Enregistrer un commentaire