Java Key Pair Create generateKey(final String password, final byte salt[])

Here you can find the source of generateKey(final String password, final byte salt[])

Description

Generates a key using the specified password and salt.

License

Open Source License

Parameter

Parameter Description
password a parameter
salt a parameter

Exception

Parameter Description
Exception an exception

Declaration

public static SecretKey generateKey(final String password, final byte salt[]) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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 {
    public static final int KEY_SIZE = 128;
    public static final int SALT_LENGTH = 8;

    /**/*from  w  ww  . j  a  va  2 s.  c  o m*/
     * Generates a key using the specified password and salt.
     * @param password
     * @param salt
     * @return
     * @throws Exception
     */
    public static SecretKey generateKey(final String password, final byte salt[]) throws Exception {
        if (salt.length < SALT_LENGTH) {
            throw new Exception("Need a salt at least length " + SALT_LENGTH + ".");
        }
        return generateKey(password.toCharArray(), salt);
    }

    /**
     * Generates a key using the specified password and salt.
     * @param password
     * @param salt
     * @return
     * @throws Exception
     */
    public static SecretKey generateKey(final char password[], final byte salt[]) throws Exception {
        if (salt.length != 8) {
            throw new Exception("Invalid salt length.");
        }

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password, salt, 65536, KEY_SIZE);
        SecretKey tmp = factory.generateSecret(spec);
        return new SecretKeySpec(tmp.getEncoded(), "AES");
    }
}

Related

  1. generateKey()
  2. generateKey(byte[] keyBytes)
  3. generateKey(byte[] keyBytes)
  4. generateKey(char[] password)
  5. generateKey(final SecureRandom srand)
  6. generateKey(SecureRandom sr, int size)
  7. generateKey(String algom, int keylength)
  8. generateKey(String algorithm, int keySize)
  9. generateKey(String algorithm, int size)