Example usage for javax.crypto KeyGenerator init

List of usage examples for javax.crypto KeyGenerator init

Introduction

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

Prototype

public final void init(int keysize, SecureRandom random) 

Source Link

Document

Initializes this key generator for a certain keysize, using a user-provided source of randomness.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {

    KeyGenerator keyGen = KeyGenerator.getInstance("DES");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    random.setSeed(101L);/* w  w w  .  j ava  2  s. c o  m*/
    keyGen.init(56, random);
    SecretKey sKey = keyGen.generateKey();
    SecretKeyFactory kfactory = SecretKeyFactory.getInstance("DES");

    DESKeySpec kspec = (DESKeySpec) kfactory.getKeySpec(sKey, DESKeySpec.class);

    System.out.println(sKey);
    FileOutputStream fos = new FileOutputStream("secretKeys");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeObject(kspec.getKey());

    FileInputStream fin = new FileInputStream("secretKeys");
    ObjectInputStream ois = new ObjectInputStream(fin);

    byte[] kMaterial = (byte[]) ois.readObject();

    DESKeySpec keyspec = new DESKeySpec(kMaterial);
    SecretKey newKey = kfactory.generateSecret(keyspec);
    System.out.println(newKey);
    System.out.println("Do the keys equal :" + newKey.equals(sKey));

}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

public static void main(String[] args) throws Exception {

    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());

    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true,
            "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }/*from  www  .j av  a2  s. co m*/

    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);

    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }

    logger.info("Configuration loaded");

    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);

    KeyStore ks = loadKeyStore(ksPath, ttRead);

    logger.info("...loaded");

    if (action.equalsIgnoreCase("import-sp-metadata")) {

        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);

    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");

        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);

        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);

    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");

        String backupFileName = unisonXMLFile + ".bak";

        logger.info("Backing up to '" + backupFileName + "'");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();

    }

}

From source file:MainClass.java

public static SecretKey createKeyForAES(int bitLength, SecureRandom random)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
    generator.init(128, random);
    return generator.generateKey();
}

From source file:Main.java

public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128, new SecureRandom(encryptKey.getBytes()));

    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));

    return cipher.doFinal(content.getBytes("utf-8"));
}

From source file:Main.java

public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128, new SecureRandom(decryptKey.getBytes()));

    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
    byte[] decryptBytes = cipher.doFinal(encryptBytes);

    return new String(decryptBytes);
}

From source file:Main.java

/**
 * do not work/*from   w  w  w.j  av  a  2  s .  co m*/
 */
private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(128, new SecureRandom(seed)); // 192 and 256 bits may not be available
    return keyGenerator.generateKey().getEncoded();
}

From source file:MainClass.java

public static SecretKey createKeyForAES(int bitLength, SecureRandom random)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");

    generator.init(128, random);

    return generator.generateKey();
}

From source file:MainClass.java

static SecretKey createKeyForAES(int bitLength, SecureRandom random)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
    generator.init(256, random);
    return generator.generateKey();
}

From source file:de.openflorian.crypt.CipherKeyGenerator.java

/**
 * Generate Cipher Secret<br/>//from  w  w  w.  j a  v a2 s  .c o m
 * <br/>
 * Secret is generated by Blowfish {@link KeyGenerator} and a system default
 * {@link SecureRandom} provider and Base64 encoded afterwards.
 * 
 * @return Base64 encoded {@link SecureRandom} generated encryption key
 * @throws GeneralSecurityException
 */
public static String generateKey() throws GeneralSecurityException {
    try {
        KeyGenerator gen = KeyGenerator.getInstance("Blowfish");
        gen.init(192, new SecureRandom());
        SecretKey key = gen.generateKey();

        return new String(new Base64().encode(key.getEncoded())).trim();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new GeneralSecurityException(e.getMessage(), e);
    }
}

From source file:Main.java

private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);//from ww  w. j  a v a 2  s .co  m
    kgen.init(128, sr);
    SecretKey sKey = kgen.generateKey();
    byte[] raw = sKey.getEncoded();

    return raw;
}