Friday 3 July 2015

Generate secret AES key in Java

Step 1: Get KeyGenerator object that generates secret keys for AES.
KeyGenerator keyGen = KeyGenerator.getInstance("AES");

Step 2: Initialize key generator to specific key size.
keyGen.init(256);

Step 3: Generate a secret key.
SecretKey secretKey = keyGen.generateKey();

import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SecretKeyGen {

 public static SecretKey generateSecretKey() {
  KeyGenerator keyGen = null;
  try {
   /*
    * Get KeyGenerator object that generates secret keys for the
    * specified algorithm.
    */
   keyGen = KeyGenerator.getInstance("AES");
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }

  /* Initializes this key generator for key size to 256. */
  keyGen.init(256);

  /* Generates a secret key */
  SecretKey secretKey = keyGen.generateKey();

  return secretKey;
 }

 public static void main(String args[]) {
  SecretKey secretKey = generateSecretKey();
  String encodedKey = Base64.getEncoder().encodeToString(
    secretKey.getEncoded());
  System.out.println(encodedKey);
 }
}



No comments:

Post a Comment