Java Key Pair Create generateKey()

Here you can find the source of generateKey()

Description

generate Key

License

Open Source License

Declaration

public static SecretKey generateKey() 

Method Source Code


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

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    private static final SecureRandom random = new SecureRandom();
    /**/*from   w w  w.  j av  a 2  s . c o m*/
     * The salt used for deriving the KeyParameter from the credentials in AES encryption for wallets
     */
    public static final byte[] SCRYPT_SALT = new byte[] { (byte) 0x35, (byte) 0x51, (byte) 0x03, (byte) 0x80,
            (byte) 0x75, (byte) 0xa3, (byte) 0xb0, (byte) 0xc5 };

    public static SecretKey generateKey(char[] password) {
        try {
            SecretKeyFactory kf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            PBEKeySpec spec = new PBEKeySpec(password, SCRYPT_SALT, 8192, 256);
            SecretKey tmp = kf.generateSecret(spec);
            return new SecretKeySpec(tmp.getEncoded(), "AES");
        } catch (Exception e) {
            // should never happen but...
            throw new IllegalArgumentException("failed to generate AES key from password", e);
        }
    }

    public static SecretKey generateKey() {
        KeyGenerator gen;
        try {
            gen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("Failed to get generator for algorithm", e);
        }

        gen.init(random);
        return gen.generateKey();
    }
}

Related

  1. generateKey()
  2. generateKey()
  3. generateKey()
  4. generateKey()
  5. generateKey()
  6. generateKey(byte[] keyBytes)
  7. generateKey(byte[] keyBytes)
  8. generateKey(char[] password)
  9. generateKey(final SecureRandom srand)