Example usage for javax.crypto KeyGenerator generateKey

List of usage examples for javax.crypto KeyGenerator generateKey

Introduction

In this page you can find the example usage for javax.crypto KeyGenerator generateKey.

Prototype

public final SecretKey generateKey() 

Source Link

Document

Generates a secret key.

Usage

From source file:org.geoserver.security.GeoServerSecurityManager.java

/**
 * Determines if strong encryption is available.
 * <p>/*from   w  ww .j  av a  2 s  . c  o  m*/
 * This method does the determination by trying to encrypt a value with AES 256 Bit encryption.
 * </p>
 * 
 * @return True if strong encryption avaialble, otherwise false.
 */
public boolean isStrongEncryptionAvailable() {
    if (strongEncryptionAvaialble != null)
        return strongEncryptionAvaialble;

    KeyGenerator kgen;
    try {
        kgen = KeyGenerator.getInstance("AES");
        kgen.init(256);
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        cipher.doFinal("This is just an example".getBytes());
        strongEncryptionAvaialble = true;
        LOGGER.info("Strong cryptograhpy is available");
    } catch (InvalidKeyException e) {
        strongEncryptionAvaialble = false;
        LOGGER.warning("Strong cryptograhpy is NOT available"
                + "\nDownload and install of policy files recommended"
                + "\nfrom http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html");
    } catch (Exception ex) {
        LOGGER.log(Level.WARNING, "Strong cryptograhpy is NOT available, unexpected error", ex);
        strongEncryptionAvaialble = false; //should not happen
    }
    return strongEncryptionAvaialble;
}