Constructs a AES_KEY_LEN byte AES key from a given seed - Java Security

Java examples for Security:AES

Description

Constructs a AES_KEY_LEN byte AES key from a given seed

Demo Code


//package com.java2s;

import java.security.*;

import javax.crypto.spec.*;

public class Main {
    public static final int AES_KEY_LEN = 16;

    /**//from  w ww .  j  a  v a2 s.  c  o m
     * Constructs a AES_KEY_LEN byte AES key from a given seed
     *
     * @param seed (array of bytes)
     * @return the resulting AES key
     */
    public static SecretKeySpec key_from_seed(byte[] seed) {
        // compute SHA-1 hash of the seed
        byte[] hashval = null;
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA1");
            hashval = sha1.digest(seed);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // extract 1st AES_KEY_LEN bytes for the key material
        byte[] key = new byte[AES_KEY_LEN];
        System.arraycopy(hashval, 0, key, 0, AES_KEY_LEN);

        // initialize the key
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

        return keySpec;
    }
}

Related Tutorials