Java examples for Security:AES
get AES Key from password
//package com.java2s; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Base64; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class Main { public static void main(String[] argv) throws Exception { String pwd = "java2s.com"; System.out.println(getKey(pwd)); }// w ww. j a v a 2 s . co m private static final String KEY_ALGORITHM = "AES"; static String getKey(String pwd) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = new SecureRandom(); sr.setSeed(pwd.getBytes()); kgen.init(128, sr); System.out.println("genkey1: " + Base64.getEncoder().encodeToString( kgen.generateKey().getEncoded())); System.out.println("genkey2: " + Base64.getEncoder().encodeToString( kgen.generateKey().getEncoded())); System.out.println("genkey3: " + Base64.getEncoder().encodeToString( kgen.generateKey().getEncoded())); return Base64.getEncoder().encodeToString( kgen.generateKey().getEncoded()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } private static SecretKey generateKey(String pwd) throws NoSuchAlgorithmException { KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM); kgen.init(128, new SecureRandom(pwd.getBytes())); SecretKey secretKey = kgen.generateKey(); return secretKey; } }