Java Key Pair Create generateKey(char[] password)

Here you can find the source of generateKey(char[] password)

Description

generate Key

License

Open Source License

Declaration

public static Key generateKey(char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException 

Method Source Code


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

import java.security.Key;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
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 Key generateKey(char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException {
        return generateKey(password, generateSalt(128));
    }// w w  w .  j  a va  2 s .c o m

    public static Key generateKey(char[] password, byte[] salt)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
        return secret;
    }

    public static byte[] generateSalt(int length) {
        byte[] salt = new byte[length];
        SecureRandom rnd = null;
        try {
            rnd = SecureRandom.getInstanceStrong();
        } catch (NoSuchAlgorithmException e) {
            rnd = new SecureRandom();
        }
        rnd.nextBytes(salt);
        return salt;
    }
}

Related

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