How to generate secrete key in Java

Java example to generate random secrete key using KeyGenerator class.

To generate secrete key we can use 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 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 provider name as second parameter of overloaded method.

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

Example for generating random secrete key

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