Example usage for java.security Security addProvider

List of usage examples for java.security Security addProvider

Introduction

In this page you can find the example usage for java.security Security addProvider.

Prototype

public static int addProvider(Provider provider) 

Source Link

Document

Adds a provider to the next position available.

Usage

From source file:ListAlgorithmsBC.java

public static void main(String[] args) {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    new ListAlgorithmsBC().setVisible(true);
}

From source file:com.simple.sftpfetch.App.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Options options = getOptions();//from  ww  w .  j  ava 2  s. c om

    List<String> requiredProperties = asList("c");

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption("h")) {
            printUsage(options);
            System.exit(0);
        }

        for (String opt : requiredProperties) {
            if (!commandLine.hasOption(opt)) {
                System.err.println("The option: " + opt + " is required.");
                printUsage(options);
                System.exit(1);
            }
        }

        Pattern pattern;
        if (commandLine.hasOption("p")) {
            pattern = Pattern.compile(commandLine.getOptionValue("p"));
        } else {
            pattern = MATCH_EVERYTHING;
        }

        String filename = commandLine.getOptionValue("c");
        Properties properties = new Properties();
        try {
            InputStream stream = new FileInputStream(new File(filename));
            properties.load(stream);
        } catch (IOException ioe) {
            System.err.println("Unable to read properties from: " + filename);
            System.exit(2);
        }

        String routingKey = "";
        if (commandLine.hasOption("r")) {
            routingKey = commandLine.getOptionValue("r");
        } else if (properties.containsKey("rabbit.routingkey")) {
            routingKey = properties.getProperty("rabbit.routingkey");
        }

        int daysToFetch;
        if (commandLine.hasOption("d")) {
            daysToFetch = Integer.valueOf(commandLine.getOptionValue("d"));
        } else {
            daysToFetch = Integer.valueOf(properties.getProperty(FETCH_DAYS));
        }

        FileDecrypter decrypter = null;
        if (properties.containsKey("decryption.key.path")) {
            decrypter = new PGPFileDecrypter(new File(properties.getProperty("decryption.key.path")));
        } else {
            decrypter = new NoopDecrypter();
        }

        SftpClient sftpClient = new SftpClient(new JSch(), new SftpConnectionInfo(properties));
        try {
            App app = new App(sftpClient, s3FromProperties(properties),
                    new RabbitClient(new ConnectionFactory(), new RabbitConnectionInfo(properties)), decrypter,
                    System.out);
            app.run(routingKey, daysToFetch, pattern, commandLine.hasOption("n"), commandLine.hasOption("o"));
        } finally {
            sftpClient.close();
        }
        System.exit(0);
    } catch (UnrecognizedOptionException uoe) {
        System.err.println(uoe.getMessage());
        printUsage(options);
        System.exit(10);
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    X509Certificate[] chain = buildChain();

    PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(System.out));

    pemWrt.writeObject(chain[0]);// w  w  w.  jav  a2 s . co  m
    pemWrt.writeObject(chain[1]);

    pemWrt.close();
}

From source file:com.edduarte.protbox.Protbox.java

public static void main(String... args) {

    // activate debug / verbose mode
    if (args.length != 0) {
        List<String> argsList = Arrays.asList(args);
        if (argsList.contains("-v")) {
            Constants.verbose = true;/*from   ww  w . j a  va 2 s . com*/
        }
    }

    // use System's look and feel
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        // If the System's look and feel is not obtainable, continue execution with JRE look and feel
    }

    // check this is a single instance
    try {
        new ServerSocket(1882);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null,
                "Another instance of Protbox is already running.\n" + "Please close the other instance first.",
                "Protbox already running", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // check if System Tray is supported by this operative system
    if (!SystemTray.isSupported()) {
        JOptionPane.showMessageDialog(null,
                "Your operative system does not support system tray functionality.\n"
                        + "Please try running Protbox on another operative system.",
                "System tray not supported", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // add PKCS11 providers
    FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")),
            HiddenFileFilter.VISIBLE);

    File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter);

    if (providersConfigFiles != null) {
        for (File f : providersConfigFiles) {
            try {
                List<String> lines = FileUtils.readLines(f);
                String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get();
                lines.remove(aliasLine);
                String alias = aliasLine.split("=")[1].trim();

                StringBuilder sb = new StringBuilder();
                for (String s : lines) {
                    sb.append(s);
                    sb.append("\n");
                }

                Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString())));
                Security.addProvider(p);

                pkcs11Providers.put(p.getName(), alias);

            } catch (IOException | ProviderException ex) {
                if (ex.getMessage().equals("Initialization failed")) {
                    ex.printStackTrace();

                    String s = "The following error occurred:\n" + ex.getCause().getMessage()
                            + "\n\nIn addition, make sure you have "
                            + "an available smart card reader connected before opening the application.";
                    JTextArea textArea = new JTextArea(s);
                    textArea.setColumns(60);
                    textArea.setLineWrap(true);
                    textArea.setWrapStyleWord(true);
                    textArea.setSize(textArea.getPreferredSize().width, 1);

                    JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider",
                            JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                } else {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "Error while setting up PKCS11 provider from configuration file " + f.getName()
                                    + ".\n" + ex.getMessage(),
                            "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    // adds a shutdown hook to save instantiated directories into files when the application is being closed
    Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit));

    // get system tray and run tray applet
    tray = SystemTray.getSystemTray();
    SwingUtilities.invokeLater(() -> {

        if (Constants.verbose) {
            logger.info("Starting application");
        }

        //Start a new TrayApplet object
        trayApplet = TrayApplet.getInstance();
    });

    // prompts the user to choose which provider to use
    ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> {

        // loads eID token
        eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> {
            user = returnedUser;
            certificateData = returnedCertificateData;

            // gets a password to use on the saved registry files (for loading and saving)
            final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null);
            consumerHolder.set(password -> {
                registriesPasswordKey = password;
                try {
                    // if there are serialized files, load them if they can be decoded by this user's private key
                    final List<SavedRegistry> serializedDirectories = new ArrayList<>();
                    if (Constants.verbose) {
                        logger.info("Reading serialized registry files...");
                    }

                    File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles();
                    if (registryFileList != null) {
                        for (File f : registryFileList) {
                            if (f.isFile()) {
                                byte[] data = FileUtils.readFileToByteArray(f);
                                try {
                                    Cipher cipher = Cipher.getInstance("AES");
                                    cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey);
                                    byte[] registryDecryptedData = cipher.doFinal(data);
                                    serializedDirectories.add(new SavedRegistry(f, registryDecryptedData));
                                } catch (GeneralSecurityException ex) {
                                    if (Constants.verbose) {
                                        logger.info("Inserted Password does not correspond to " + f.getName());
                                    }
                                }
                            }
                        }
                    }

                    // if there were no serialized directories, show NewDirectory window to configure the first folder
                    if (serializedDirectories.isEmpty() || registryFileList == null) {
                        if (Constants.verbose) {
                            logger.info("No registry files were found: running app as first time!");
                        }
                        NewRegistryWindow.start(true);

                    } else { // there were serialized directories
                        loadRegistry(serializedDirectories);
                        trayApplet.repaint();
                        showTrayApplet();
                    }

                } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException
                        | ProtboxException ex) {

                    JOptionPane.showMessageDialog(null,
                            "The inserted password was invalid! Please try another one!", "Invalid password!",
                            JOptionPane.ERROR_MESSAGE);
                    insertPassword(consumerHolder.get());
                }
            });
            insertPassword(consumerHolder.get());
        });
    });
}

From source file:com.trsst.Command.java

public static void main(String[] argv) {

    // during alpha period: expire after one week
    Date builtOn = Common.getBuildDate();
    if (builtOn != null) {
        long weekMillis = 1000 * 60 * 60 * 24 * 7;
        Date expiry = new Date(builtOn.getTime() + weekMillis);
        if (new Date().after(expiry)) {
            System.err.println("Build expired on: " + expiry);
            System.err.println("Please obtain a more recent build for testing.");
            System.exit(1);/*from   w w  w  .  j  a  va2s.  co m*/
        } else {
            System.err.println("Build will expire on: " + expiry);
        }
    }

    // experimental tor support
    boolean wantsTor = false;
    for (String s : argv) {
        if ("--tor".equals(s)) {
            wantsTor = true;
            break;
        }
    }
    if (wantsTor && !HAS_TOR) {
        try {
            log.info("Attempting to connect to tor network...");
            Security.addProvider(new BouncyCastleProvider());
            JvmGlobalUtil.init();
            NetLayer netLayer = NetFactory.getInstance().getNetLayerById(NetLayerIDs.TOR);
            JvmGlobalUtil.setNetLayerAndNetAddressNameService(netLayer, true);
            log.info("Connected to tor network");
            HAS_TOR = true;
        } catch (Throwable t) {
            log.error("Could not connect to tor: exiting", t);
            System.exit(1);
        }
    }

    // if unspecified, default relay to home.trsst.com
    if (System.getProperty("com.trsst.server.relays") == null) {
        System.setProperty("com.trsst.server.relays", "https://home.trsst.com/feed");
    }

    // default to user-friendlier file names
    String home = System.getProperty("user.home", ".");
    if (System.getProperty("com.trsst.client.storage") == null) {
        File client = new File(home, "Trsst Accounts");
        System.setProperty("com.trsst.client.storage", client.getAbsolutePath());
    }
    if (System.getProperty("com.trsst.server.storage") == null) {
        File server = new File(home, "Trsst System Cache");
        System.setProperty("com.trsst.server.storage", server.getAbsolutePath());
    }
    // TODO: try to detect if launching from external volume like a flash
    // drive and store on the local flash drive instead

    Console console = System.console();
    int result;
    try {
        if (console == null && argv.length == 0) {
            argv = new String[] { "serve", "--gui" };
        }
        result = new Command().doBegin(argv, System.out, System.in);

        // task queue prevents exit unless stopped
        if (TrsstAdapter.TASK_QUEUE != null) {
            TrsstAdapter.TASK_QUEUE.cancel();
        }
    } catch (Throwable t) {
        result = 1; // "general catchall error code"
        log.error("Unexpected error, exiting.", t);
    }

    // if error
    if (result != 0) {
        // force exit
        System.exit(result);
    }
}

From source file:org.candlepin.client.CLIMain.java

public static void main(String[] args) {
    Security.addProvider(new BouncyCastleProvider());
    CLIMain cli = new CLIMain();
    cli.execute(args);/*  w  ww  .  j a va  2  s . c  om*/
}

From source file:com.oneops.cms.crypto.CmsCryptoDES.java

/**
 * The main method./*from   w  w  w. j  a v  a2  s  . co  m*/
 *
 * @param args the arguments
 */
public static void main(String[] args) {
    if (args.length < 1) {
        System.err.println("Usage: java " + CmsCryptoDES.class.getName() + " keyfile");
        System.exit(1);
    }

    System.out.println("Generate DES key file");

    Security.addProvider(new BouncyCastleProvider());
    try {
        CmsCryptoDES.generateDESKey(args[0]);
        System.out.println("DES key generated successfully.");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.mb.framework.util.SecurityUtil.java

/**
 * Thisis main method to run program// www.j  ava  2s. com
 * 
 * @param args
 *            []
 */
public static void main(String args[]) {

    try {
        Security.addProvider(new com.sun.crypto.provider.SunJCE());// step 1
        // PasswordUtil passwordEncryptAgent = new PasswordUtil("ASCII");
        String password = "Abcd@1234";
        System.out.println("Plain Password : " + password + "\n");

        /******************************* START - MD5 *****************************************/
        System.out.println("MD5 - Encrypted Password:  " + encryptMd5(password) + "\n");
        /******************************* END - MD5 *******************************************/

        /******************************* START - ASE_ALGO ************************************/
        String passwordEnc = encryptAES(password);
        String passwordDec = decryptAES(passwordEnc);

        System.out.println("ASE - Encrypted Password : " + passwordEnc);
        System.out.println("ASE - Decrypted Password : " + passwordDec + "\n");
        /******************************* END - ASE_ALGO ************************************/

        /****** START - 256-bit AES/CBC/PKCS5Padding (based on PKCS#5s PBKDF2) ************/

        String encryptedText = encryptAESPBKDF2(password);
        System.out.println(
                "256-bit AES/CBC/PKCS5Padding (based on PKCS#5s PBKDF2) - Encrypted string:" + encryptedText);
        System.out.println("256-bit AES/CBC/PKCS5Padding (based on PKCS#5s PBKDF2) - Decrypted string:"
                + decryptAESPBKDF2(encryptedText));

        /******** END - 256-bit AES/CBC/PKCS5Padding (based on PKCS#5s PBKDF2) ************/
    } catch (Exception ex) {
        LOGGER.error("error " + ex.getMessage());
    }

}

From source file:Main.java

protected static boolean initProvider(String providerName, String className) {
    try {//w  ww.j a va  2s. c  o m
        Provider provider = Security.getProvider(providerName);
        if (provider == null) {
            @SuppressWarnings("rawtypes")
            Class clazz = Class.forName(className);
            provider = (Provider) clazz.newInstance();
            Security.addProvider(provider);
        }
        return true;
    } catch (Throwable ignored) {
    }
    return false;
}

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  w w  w. j a v 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();

    }

}