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.codice.ddf.configuration.migration.CipherUtils.java

/**
 * Creates a secret key and stores it in a file
 *
 * @param keyPath the path for storing the secret key
 * @throws MigrationException when an invalid key algorithm is used
 * @throws MigrationException when the key can not be written to a file
 * @throws NoSuchAlgorithmException when an invalid algorithm is used for the {@link KeyGenerator}
 * @return a {@link SecretKey}/*from  ww w .  ja  v a 2s .  c o m*/
 */
private SecretKey createSecretKey(Path keyPath) throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator;
    try {
        keyGenerator = KeyGenerator.getInstance(MigrationZipConstants.KEY_ALGORITHM);
        keyGenerator.init(128);
        secretKey = keyGenerator.generateKey();
        char[] hexKey = encodeHex(secretKey.getEncoded());
        writeStringToFile(keyPath.toFile(), String.valueOf(hexKey), Charsets.UTF_8);
        return secretKey;
    } catch (IOException e) {
        throw new MigrationException(String.format(MigrationZipConstants.FILE_IO_ERROR, keyPath, e));
    }
}

From source file:org.apache.ws.security.message.EncryptionAlgorithmSuiteTest.java

@org.junit.Test
public void testSymmetricEncryption() throws Exception {

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);//from  w w  w  . j  a v a2 s.c  om
    SecretKey key = keyGen.generateKey();
    byte[] keyData = key.getEncoded();

    WSSecEncrypt builder = new WSSecEncrypt();
    builder.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
    builder.setSymmetricKey(key);
    builder.setEncryptSymmKey(false);

    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    Document encryptedDoc = builder.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = XMLUtils.PrettyDocumentToString(encryptedDoc);
        LOG.debug(outputString);
    }

    byte[] encodedBytes = WSSecurityUtil.generateDigest(keyData);
    String identifier = Base64.encode(encodedBytes);
    SecretKeyCallbackHandler secretKeyCallbackHandler = new SecretKeyCallbackHandler();
    secretKeyCallbackHandler.addSecretKey(identifier, keyData);

    Element securityHeader = WSSecurityUtil.getSecurityHeader(encryptedDoc, null);
    AlgorithmSuite algorithmSuite = createAlgorithmSuite();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    RequestData data = new RequestData();
    data.setDecCrypto(crypto);
    data.setCallbackHandler(secretKeyCallbackHandler);

    data.setAlgorithmSuite(algorithmSuite);

    algorithmSuite.addEncryptionMethod(WSConstants.AES_128);
    secEngine.processSecurityHeader(securityHeader, data);

    algorithmSuite.setMinimumSymmetricKeyLength(256);
    try {
        secEngine.processSecurityHeader(securityHeader, data);
        fail("Expected failure as a 128 bit key is not allowed");
    } catch (WSSecurityException ex) {
        // expected
    }

    algorithmSuite.setMinimumSymmetricKeyLength(64);
    algorithmSuite.setMaximumSymmetricKeyLength(120);
    try {
        secEngine.processSecurityHeader(securityHeader, data);
        fail("Expected failure as a 128 bit key is not allowed");
    } catch (WSSecurityException ex) {
        // expected
    }
}

From source file:com.POLIS.licensing.common.license.AbstractSerializationBasedLicense.java

@Override
public String getEncryptedLicense(PublicKey targetKey) throws SystemStateException, OperationException {
    byte[] licenseAsBytes;
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutput out = new ObjectOutputStream(bos)) {
        out.writeObject(this);
        licenseAsBytes = bos.toByteArray();
    } catch (IOException ex) {
        throw new OperationException("An error occured while serializing the license", ex);
    }/*from  w ww. ja v  a2 s.com*/
    SecureRandom random = new SecureRandom();
    Cipher aescipher;
    Cipher rsacipher;

    KeyGenerator aesgenerator;
    Key symkey;
    try {
        aesgenerator = KeyGenerator.getInstance(symmetricKeyType, provider);
        aesgenerator.init(128, random);
        symkey = aesgenerator.generateKey();
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SystemStateException("The specified symkey could not be generated.", ex);
    }

    try {
        aescipher = Cipher.getInstance(symmetricEncoding, provider);
        rsacipher = Cipher.getInstance(asymmetricEncoding, provider);

        aescipher.init(Cipher.ENCRYPT_MODE, symkey);
        rsacipher.init(Cipher.ENCRYPT_MODE, targetKey);
    } catch (NoSuchAlgorithmException | NoSuchProviderException
            | /*InvalidKeySpecException |*/ NoSuchPaddingException | InvalidKeyException ex) {
        throw new SystemStateException("The specified encryption provider or algorithm was not found", ex);
    }

    String encryptedLicense;
    try {
        byte[] encryptedsymkey = rsacipher.doFinal(symkey.getEncoded());

        byte[] encryptedlicense = aescipher.doFinal(licenseAsBytes);
        byte[] licenseWithKey = new byte[encryptedsymkey.length + encryptedlicense.length];
        System.arraycopy(encryptedsymkey, 0, licenseWithKey, 0, encryptedsymkey.length);
        System.arraycopy(encryptedlicense, 0, licenseWithKey, encryptedsymkey.length, encryptedlicense.length);
        encryptedLicense = Base64.encodeBase64String(licenseWithKey);
    } catch (IllegalBlockSizeException | BadPaddingException ex) {
        throw new OperationException("Could not encode to base64", ex);
    }
    return encryptedLicense;

}

From source file:org.lsc.utils.security.SymmetricEncryption.java

/**
 * Generate a random key file.//ww  w . j  a v a 2 s  .  co m
 * @param keyPath The filename where to write the key
 * @param algo The supported algorithm to use
 * @param strength The encryption strength
 * @return boolean false if an error occurred
 * @throws NoSuchAlgorithmException 
 * @throws NoSuchProviderException 
 */
public boolean generateRandomKeyFile(String keyPath, String algo, int strength)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    OutputStream os = null;
    try {
        KeyGenerator kg = KeyGenerator.getInstance(algo, securityProvider.getName());
        SecretKey cipherKey = kg.generateKey();
        SecureRandom sr = new SecureRandom();
        kg.init(strength, sr);
        os = new FileOutputStream(keyPath);
        os.write(cipherKey.getEncoded());
    } catch (IOException e) {
        LOGGER.error("Unable to write new generated key in " + keyPath + ". Encountered exception is : "
                + e.getLocalizedMessage(), e);
        return false;
    } finally {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException e1) {
        }
    }
    return true;
}

From source file:sec_algo.commonenc.java

/**
* Creates a new AES key/*from w  ww  .  ja  v a 2 s.  c  om*/
*/
public void makeKey() {
    try {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(AES_Key_Size);
        SecretKey aeskey = kgen.generateKey();
        key = aeskey.getEncoded();
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.apimgt.core.impl.FileEncryptionUtility.java

/**
 * Creates and stores an AES key//  w  ww . ja  va2s. co m
 *
 * @throws APIManagementException if an error occurs while creating or storing AES key
 */
void createAndStoreAESKey() throws APIManagementException {
    try {
        //create a new AES key
        KeyGenerator keyGenerator = KeyGenerator.getInstance(EncryptionConstants.AES);
        keyGenerator.init(AES_Key_Size);
        byte[] aesKey = keyGenerator.generateKey().getEncoded();

        //store key => encrypt -> encode -> chars -> string
        byte[] encryptedKeyBytes = SecureVaultUtils.base64Encode(getSecureVault().encrypt(aesKey));
        String encryptedKeyString = new String(SecureVaultUtils.toChars(encryptedKeyBytes));

        Files.deleteIfExists(Paths.get(getAesKeyFileLocation()));
        APIFileUtils.createFile(getAesKeyFileLocation());
        APIFileUtils.writeToFile(getAesKeyFileLocation(), encryptedKeyString);
        log.debug("AES key successfully created and stored");
    } catch (NoSuchAlgorithmException | SecureVaultException | APIMgtDAOException | IOException e) {
        String msg = "Error while creating or storing created AES key";
        throw new APIManagementException(msg, e);
    }
}

From source file:wssec.TestWSSecurityNew17.java

/**
 * Setup method//  w  w  w .j av  a  2 s.  c om
 * <p/>
 * 
 * @throws Exception Thrown when there is a problem in setup
 */
protected void setUp() throws Exception {
    AxisClient tmpEngine = new AxisClient(new NullProvider());
    msgContext = new MessageContext(tmpEngine);
    message = getSOAPMessage();

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    SecretKey key = keyGen.generateKey();
    keyData = key.getEncoded();
}

From source file:org.pentaho.di.trans.steps.symmetriccrypto.symmetricalgorithm.SymmetricCrypto.java

public byte[] generateKey(int keySize) throws CryptoKeyException {
    try {//from w  w w  . ja  v a  2 s . c  o m
        // Get a key generator for algorithm
        KeyGenerator kg = KeyGenerator.getInstance(meta.getAlgorithm());
        // SecureRandom random = new SecureRandom();
        kg.init(keySize);
        // Use it to generate a key
        SecretKey secretKey = kg.generateKey();

        return secretKey.getEncoded();

    } catch (Exception e) {
        throw new CryptoKeyException(e);
    }
}

From source file:org.openanzo.security.keystore.SecretKeyStore.java

/**
 * Loads the secret key to use for encryption and decryption. It will read the key from the keystore if it exists. Otherwise it will create a new randomly
 * generated key and save it in a keystore at the given file. It will use the algorithm defined in the <code>algorithm</code> member.
 * /*from w w  w . j ava  2 s . co m*/
 * @param keyStoreStream
 *            stream from which to read the keystore which holds the secret key. If null, a new keystore is created.
 * @param password
 *            password used to protect the and integrity-check the secret key.
 * @param keyStoreDestination
 *            File path to which to save the keystore in case it is newly created or a new key was added. If null, then nothing is written out.
 * @return the loaded or newly generated secret key.
 * @throws AnzoException
 */
private SecretKey loadKey(InputStream keyStoreStream, String password, File keyStoreDestination,
        String keystoreType) throws AnzoException {

    try {
        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(keyStoreStream, password.toCharArray());

        Key key = null;
        if (keyStore.containsAlias(KEY_NAME)) {
            key = keyStore.getKey(KEY_NAME, password.toCharArray());
        } else {
            log.warn("Could not find key '{}' within keystore. Generating a new key.", KEY_NAME);
            KeyGenerator kgen = KeyGenerator.getInstance(algorithm);
            key = kgen.generateKey();
            keyStore.setKeyEntry(KEY_NAME, key, password.toCharArray(), new Certificate[0]);
            if (keyStoreDestination != null) {
                log.warn("Storing new key in the keystore.");
                OutputStream outputStream = null;
                try {
                    outputStream = FileUtils.openOutputStream(keyStoreDestination);
                    keyStore.store(outputStream, password.toCharArray());
                } finally {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                }

            }
        }

        if (!(key instanceof SecretKey))
            throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR,
                    "key must be of type SecretKey: " + key);
        return (SecretKey) key;
    } catch (GeneralSecurityException e) {
        throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, e);
    } catch (IOException e) {
        throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, e);
    }

}

From source file:net.spfbl.core.Server.java

private static SecretKey getPrivateKey() {
    if (privateKey == null) {
        try {//  w w  w .java 2 s .c o m
            File file = new File("./data/server.key");
            if (file.exists()) {
                FileInputStream fileInputStream = new FileInputStream(file);
                try {
                    privateKey = SerializationUtils.deserialize(fileInputStream);
                } finally {
                    fileInputStream.close();
                }
            } else {
                KeyGenerator keyGen = KeyGenerator.getInstance("AES");
                keyGen.init(new SecureRandom());
                SecretKey key = keyGen.generateKey();
                FileOutputStream outputStream = new FileOutputStream(file);
                try {
                    SerializationUtils.serialize(key, outputStream);
                } finally {
                    outputStream.close();
                }
                privateKey = key;
            }
        } catch (Exception ex) {
            Server.logError(ex);
        }
    }
    return privateKey;
}