Generates a secret AES key - Android java.security

Android examples for java.security:AES

Description

Generates a secret AES key

Demo Code


//package com.java2s;

import java.security.spec.KeySpec;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    private static final int ITERATIONS = 1000;
    private static final int KEY_LENGTH = 256;
    private static final String SECRET_KEY_ALGORITHM = "PBKDF2WithHmacSHA1";
    private static final String KEY_ALGORITHM = "AES";

    /**/*  www  . ja  v a2s .c om*/
     * Generates a secret key
     * @param password passphrase for the key
     * @param salt a salt for the password
     */
    public static SecretKey generateSecretKey(char[] password, byte[] salt)
            throws Exception {
        final SecretKeyFactory secretKeyFactory = SecretKeyFactory
                .getInstance(SECRET_KEY_ALGORITHM);
        final KeySpec keySpec = new PBEKeySpec(password, salt, ITERATIONS,
                KEY_LENGTH);
        byte[] keyBytes = secretKeyFactory.generateSecret(keySpec)
                .getEncoded();
        return new SecretKeySpec(keyBytes, KEY_ALGORITHM);
    }
}

Related Tutorials