How to generate secrete key in Java

To generate secrete key we can use the Java KeyGenerator class which provides the functionality of a secret (symmetric) key generator. Key generators are constructed using one of the getInstance class methods of this class.

getInstance method of KeyGenerator takes parameter name of the algorithm and Returns a KeyGenerator object that generates secret keys for the specified algorithm. This method traverses the list of registered security Providers, starting with the most preferred Provider. You can give the provider name as the second parameter of the overloaded method.

After getting an instance of KeyGenerator class, you have to specify key size using the init method and call generateKey method which returns a secrete key.

Example for generating random secrete key using AES and HMAC

Example using AES

public static byte[] generateSecretKey() throws NoSuchAlgorithmException,
        NoSuchProviderException {
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    SecretKey secretKey = keyGen.generateKey();
    return secretKey.getEncoded();

Example using HmacSHA256

	public static byte[] generateSecretKey() {
		SecretKey hmacKey;
		try {
			hmacKey = KeyGenerator.getInstance("HmacSha256").generateKey();
		} catch (Exception ex) {
			throw new IllegalStateException(ex);
		return hmacKey.getEncoded();