create AES Key - Java Security

Java examples for Security:AES

Description

create AES Key

Demo Code


//package com.java2s;

import java.io.File;

import java.io.FileOutputStream;

import java.security.SecureRandom;

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

public class Main {
    public static void createKey(String keyFile) throws Exception {
        SecureRandom sr = new SecureRandom();
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(128, sr);//w ww  .  j  a  v a  2  s.c  om
        SecretKey key = kg.generateKey();
        File f = new File(keyFile);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        f.createNewFile();
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(key.getEncoded());
    }
}

Related Tutorials