This article describes the AES key generation algorithm implemented by Java. Share it for your reference, as follows:
import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;public class Test { public static void main(String[] args) { getKey(); getKeyByPass(); } /** * Randomly generated secret key*/ public static void getKey() { try { KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(128); //To generate how many bits, just modify it here 128, 192 or 256 SecretKey sk = kg.generateKey(); byte[] b = sk.getEncoded(); String s = byteToHexString(b); System.out.println(s); System.out.println("The length of the hex key is "+s.length()); System.out.println("The length of the binary key is "+s.length()*4); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("No this algorithm."); } } /** * Use the specified string to generate the key*/ public static void getKeyByPass() { //Generate the key String password="testkey"; try { KeyGenerator kg = KeyGenerator.getInstance("AES"); // kg.init(128);//To generate how many bits, just modify it here 128, 192 or 256 //SecureRandom is to generate a safe random number sequence, password.getBytes() is a seed. As long as the seed is the same, the sequence is the same, so the generated key is the same. kg.init(128, new SecureRandom(password.getBytes())); SecretKey sk = kg.generateKey(); byte[] b = sk.getEncoded(); String s = byteToHexString(b); System.out.println(s); System.out.println("The length of the hex key is "+s.length()); System.out.println("The length of the binary key is "+s.length()*4); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("No this algorithm."); } } /** * byte array converted into hex string* @param bytes * @return */ public static String byteToHexString(byte[] bytes) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String strHex=Integer.toHexString(bytes[i]); if(strHex.length() > 3) { sb.append(strHex.substring(6)); } else { if(strHex.length() < 2) { sb.append("0" + strHex); } else { sb.append(strHex); } } } return sb.toString(); }}PS: Friends who are interested in encryption and decryption can also refer to the online tools of this site:
Password security online detection:
http://tools.VeVB.COM/password/my_password_safe
High-strength password generator:
http://tools.VeVB.COM/password/CreateStrongPassword
Thunder, Express, and Tornado URL encryption/decryption tools:
http://tools.VeVB.COM/password/urlrethunder
Online hash/hash algorithm encryption tool:
http://tools.VeVB.COM/password/hash_encrypt
Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 encryption tool:
http://tools.VeVB.COM/password/hash_md5_sha
Online sha1/sha224/sha256/sha384/sha512 encryption tool:
http://tools.VeVB.COM/password/sha_encode
I hope this article will be helpful to everyone's Java programming.