Example usage for java.security Provider getName

List of usage examples for java.security Provider getName

Introduction

In this page you can find the example usage for java.security Provider getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of this provider.

Usage

From source file:Main.java

public static void main(String[] args) throws NoSuchAlgorithmException {
    int numBytes = (new Integer("1111")).intValue();

    SecureRandom srand = new SecureRandom(new byte[] { 1, 2, 3, 4 });

    Provider provider = srand.getProvider();
    System.out.println(provider.getName());

    byte[] bytes = new byte[numBytes];
    srand.nextBytes(bytes);// www. ja v a 2 s .com
    System.out.println(bytes);
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Provider p = Security.getProvider("Rot13Provider");
    System.out.println("Provider name: " + p.getName());
    System.out.println("Provider version: " + p.getVersion());
    System.out.println("Provider information: " + p.getInfo());

    Cipher cipher = Cipher.getInstance("ROT13", "Rot13Provider");
    System.out.println("Cipher: " + cipher.getAlgorithm());
    String testString = "This is a test!";
    cipher.init(Cipher.ENCRYPT_MODE, (Key) null, new SecureRandom());
    byte[] b1 = cipher.doFinal(testString.getBytes());
    cipher.init(Cipher.DECRYPT_MODE, (Key) null, new SecureRandom());
    byte[] b2 = cipher.doFinal(b1);
    System.out.println("Decrypted data as a String: " + new String(b2));
}

From source file:Main.java

public static void main(String[] args) throws NoSuchAlgorithmException {
    int numBytes = (new Integer("1111")).intValue();

    SecureRandom srand = new SecureRandom(new byte[] { 1, 2, 3, 4 });

    Provider provider = srand.getProvider();

    SecureRandom newRandom = SecureRandom.getInstance("SHA1PRNG", provider);

    System.out.println(provider.getName());

    byte[] bytes = new byte[numBytes];
    srand.nextBytes(bytes);//  w ww.j  av  a  2 s. co  m
    System.out.println(bytes);
}

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;/*  www . j a  va2 s .  c  o m*/
        }
    }

    // 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.aqnote.shared.cryptology.util.ProviderUtil.java

public static void removeAllProvider() {
    for (Provider p : Security.getProviders()) {
        Security.removeProvider(p.getName());
    }/*from  ww w .jav  a2  s  . c  o m*/
}

From source file:com.aqnote.shared.cryptology.util.ProviderUtil.java

public static void addProvider(Provider provider) throws Exception {
    if (provider == null || Security.getProvider(provider.getName()) != null)
        return;// w  ww  .  j  a  v a2 s  . c o  m
    Security.insertProviderAt(provider, 1);
}

From source file:com.aqnote.shared.cryptology.util.ProviderUtil.java

public static void removeProvider(Provider provider) throws Exception {
    if (provider == null || Security.getProvider(provider.getName()) == null)
        return;// w  w  w. j  a v a2 s  .c o m
    Security.removeProvider(provider.getName());
}

From source file:it.cnr.icar.eric.common.security.KeyToolStripped.java

public static void dumpProviderInfo(String msg) {
    Provider[] providers = Security.getProviders();
    System.err.println(msg);/*  w w w . j  a  v  a 2  s  .  c o  m*/
    for (int i = 0; i < providers.length; i++) {

        Provider provider = providers[i];
        System.err.println("Provider name: " + provider.getName());
        //System.err.println("Provider class: " + provider.getClass().getName());
        //System.err.println("Provider information: " + provider.getInfo());
        //System.err.println("Provider version: " + provider.getVersion());
        Set<Entry<Object, Object>> entries = provider.entrySet();
        @SuppressWarnings("unused")
        Iterator<Entry<Object, Object>> iterator = entries.iterator();

        /*
        while (iterator.hasNext()) {
        System.err.println("    Property entry: " + iterator.next());
        }
         */
    }
}

From source file:net.sf.jsignpdf.Signer.java

/**
 * Writes info about security providers to the {@link Logger} instance. The
 * log-level for messages is TRACE./*from w w w.j  a v a2s  .co m*/
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private static void traceInfo() {
    if (LOGGER.isTraceEnabled()) {
        try {
            Provider[] aProvider = Security.getProviders();
            for (int i = 0; i < aProvider.length; i++) {
                Provider provider = aProvider[i];
                LOGGER.trace(
                        "Provider " + (i + 1) + " : " + provider.getName() + " " + provider.getInfo() + " :");
                List keyList = new ArrayList(provider.keySet());
                try {
                    Collections.sort(keyList);
                } catch (Exception e) {
                    LOGGER.trace("Provider's properties keys can't be sorted", e);
                }
                Iterator keyIterator = keyList.iterator();
                while (keyIterator.hasNext()) {
                    String key = (String) keyIterator.next();
                    LOGGER.trace(key + ": " + provider.getProperty(key));
                }
                LOGGER.trace("------------------------------------------------");
            }
        } catch (Exception e) {
            LOGGER.trace("Listing security providers failed", e);
        }
    }
}

From source file:net.sf.jsignpdf.utils.PKCS11Utils.java

/**
 * Tries to register the sun.security.pkcs11.SunPKCS11 provider with
 * configuration provided in the given file.
 * /* w ww .j a  v a2 s . c  o  m*/
 * @param configPath
 *            path to PKCS#11 provider configuration file
 * @return newly registered PKCS#11 provider name if provider successfully
 *         registered; <code>null</code> otherwise
 */
public static String registerProvider(final String configPath) {
    if (StringUtils.isEmpty(configPath)) {
        return null;
    }
    LOGGER.debug("Registering SunPKCS11 provider from configuration in " + configPath);
    final File cfgFile = new File(configPath);
    final String absolutePath = cfgFile.getAbsolutePath();
    if (cfgFile.isFile()) {
        try {
            Provider pkcs11Provider = (Provider) Class.forName("sun.security.pkcs11.SunPKCS11")
                    .getConstructor(String.class).newInstance(absolutePath);
            Security.addProvider(pkcs11Provider);
            final String name = pkcs11Provider.getName();
            LOGGER.debug("SunPKCS11 provider registered with name " + name);
            return name;
        } catch (Exception e) {
            System.err.println("Unable to register SunPKCS11 security provider.");
            e.printStackTrace();
        }
    } else {
        System.err.println(
                "The PKCS#11 provider is not registered. Configuration file doesn't exist: " + absolutePath);
    }
    return null;
}