Example usage for java.security Security getProvider

List of usage examples for java.security Security getProvider

Introduction

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

Prototype

public static Provider getProvider(String name) 

Source Link

Document

Returns the provider installed with the specified name, if any.

Usage

From source file:org.renci.ahab.ndllib.transport.OrcaSMXMLRPCProxy.java

private KeyStore loadX509Data(FileInputStream certIS, FileInputStream keyIS, String keyAlias,
        String keyPassword) throws Exception {

    if (Security.getProvider("BC") == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/*www.  j a  va  2  s  .  c  o  m*/

    /*
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                    if (Security.getProvider("BC") == null) {
                            Security.addProvider(new BouncyCastleProvider());
                    }
                    System.out.println("Currently loaded security providers:");
                    for (Provider p: Security.getProviders()) {
                            System.out.println("Provider " + p + " - " +  p.getName());
                    }
                    System.out.println("End of security provider list.");
                    return null;
            }
    });
    */

    JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC");
    JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter().setProvider("BC");

    Object object;

    PEMParser pemParser = new PEMParser(new BufferedReader(new InputStreamReader(keyIS, "UTF-8")));

    PrivateKey privKey = null;

    while ((object = pemParser.readObject()) != null) {
        if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            InputDecryptorProvider decProv = new JceOpenSSLPKCS8DecryptorProviderBuilder()
                    .build(keyPassword.toCharArray());
            privKey = keyConverter
                    .getPrivateKey(((PKCS8EncryptedPrivateKeyInfo) object).decryptPrivateKeyInfo(decProv));
            break;
        } else if (object instanceof PEMEncryptedKeyPair) {
            PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder()
                    .build(keyPassword.toCharArray());
            privKey = keyConverter.getPrivateKey(
                    (((PEMEncryptedKeyPair) object).decryptKeyPair(decProv)).getPrivateKeyInfo());
            break;
        } else if (object instanceof PEMKeyPair) {
            privKey = keyConverter.getPrivateKey(((PEMKeyPair) object).getPrivateKeyInfo());
            break;
        }
    }

    if (privKey == null)
        throw new Exception("Private key file did not contain a private key.");

    pemParser = new PEMParser(new BufferedReader(new InputStreamReader(certIS, "UTF-8")));

    ArrayList<Certificate> certs = new ArrayList<Certificate>();

    while ((object = pemParser.readObject()) != null) {
        if (object instanceof X509CertificateHolder) {
            certs.add(certConverter.getCertificate((X509CertificateHolder) object));
        }
    }

    if (certs.isEmpty())
        throw new Exception("Certificate file contained no certificates.");

    KeyStore ks = KeyStore.getInstance("jks");
    ks.load(null);
    ks.setKeyEntry(keyAlias, privKey, keyPassword.toCharArray(), certs.toArray(new Certificate[certs.size()]));

    return ks;
}

From source file:org.talend.utils.security.AES.java

public AES() {
    try {//from w  w  w. jav a  2 s  .co m
        // TDI-28380: Database password in tac db configuration page becomes empty once restart tomcat on Solaris.
        // TDI-30348: Whole tac configuration lost for the passwords.

        Provider p = Security.getProvider("BC");
        KeyGenerator keyGen = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM, p);

        SecureRandom random = SecureRandom.getInstance(RANDOM_SHA1PRNG);
        random.setSeed(KeyValues);
        keyGen.init(128, random);

        Key key = keyGen.generateKey();

        ecipher = Cipher.getInstance(ENCRYPTION_ALGORITHM, p);
        dcipher = Cipher.getInstance(ENCRYPTION_ALGORITHM, p);

        ecipher.init(Cipher.ENCRYPT_MODE, key);
        dcipher.init(Cipher.DECRYPT_MODE, key);
    } catch (Exception e) {
        // log the error to avoid that break GWT service
        log.error(e.getMessage(), e);
    }
}

From source file:org.texai.x509.X509Utils.java

/** Logs the capabilities of the cryptography providers.
 * @param providerString the provider identifier
 *///from  w ww.  j a va2  s.com
public static void logProviderCapabilities(final String providerString) {
    //Preconditions
    assert providerString != null : "providerString must not be null";
    assert !providerString.isEmpty() : "providerString must not be empty";

    final Provider provider = Security.getProvider(providerString);

    final Iterator<Object> propertyKey_iter = provider.keySet().iterator();

    LOGGER.info("cryptography provider " + providerString + " capabilities ...");
    final List<String> propertyStrings = new ArrayList<>();
    while (propertyKey_iter.hasNext()) {
        String propertyString = (String) propertyKey_iter.next();
        if (propertyString.startsWith("Alg.Alias.")) {
            // this indicates the entry refers to another entry
            propertyString = propertyString.substring("Alg.Alias.".length());
        }
        propertyStrings.add(propertyString);
    }
    Collections.sort(propertyStrings);
    for (final String propertyString : propertyStrings) {
        final String factoryClass = propertyString.substring(0, propertyString.indexOf('.'));
        final String name = propertyString.substring(factoryClass.length() + 1);
        LOGGER.info("  " + factoryClass + ": " + name);
    }
}

From source file:org.wildfly.security.tool.Command.java

protected Supplier<Provider[]> getProvidersSupplier(final String providersList) {
    return () -> {
        if (providersList != null && !providersList.isEmpty()) {
            final String[] providerNames = providersList.split(",");
            List<Provider> providers = new ArrayList<>(providerNames.length);
            for (String p : providerNames) {
                Provider provider = Security.getProvider(p.trim());
                if (provider != null) {
                    providers.add(provider);
                }/*from  w ww .j  a  va2 s .co m*/
            }
            ServiceLoader<Provider> providerLoader = ServiceLoader.load(Provider.class);
            for (Provider provider : providerLoader) {
                for (String p : providerNames) {
                    if (provider.getName().equals(p)) {
                        providers.add(provider);
                        break;
                    }
                }
            }
            if (providers.isEmpty()) {
                throw ElytronToolMessages.msg.unknownProvider(providersList);
            }
            return providers.toArray(new Provider[providers.size()]);
        } else {
            // when no provider list is specified, load all Providers from service loader except WildFlyElytron Provider
            ServiceLoader<Provider> providerLoader = ServiceLoader.load(Provider.class);
            Iterator<Provider> providerIterator = providerLoader.iterator();
            List<Provider> providers = new ArrayList<>();
            while (providerIterator.hasNext()) {
                Provider provider = providerIterator.next();
                if (provider.getName().equals("WildFlyElytron"))
                    continue;
                providers.add(provider);
            }
            return providers.toArray(new Provider[providers.size()]);
        }
    };
}

From source file:org.wso2.andes.server.security.auth.manager.PrincipalDatabaseAuthenticationManagerTest.java

/**
 * Tests that the PDAM registers SASL mechanisms correctly with the runtime.
 *//*from ww  w  .ja va2 s .c  om*/
public void testRegisteredMechanisms() throws Exception {
    assertNotNull(_manager.getMechanisms());
    // relies on those mechanisms attached to PropertiesPrincipalDatabaseManager
    assertEquals("AMQPLAIN PLAIN CRAM-MD5", _manager.getMechanisms());

    Provider qpidProvider = Security.getProvider(PrincipalDatabaseAuthenticationManager.PROVIDER_NAME);
    assertNotNull(qpidProvider);
}

From source file:org.wso2.andes.server.security.auth.manager.PrincipalDatabaseAuthenticationManagerTest.java

/**
 * Tests the ability to de-register the provider.
 *//* w w  w . j a  v a 2  s  .co  m*/
public void testClose() throws Exception {
    assertEquals("AMQPLAIN PLAIN CRAM-MD5", _manager.getMechanisms());
    assertNotNull(Security.getProvider(PrincipalDatabaseAuthenticationManager.PROVIDER_NAME));

    _manager.close();

    // Check provider has been removed.
    assertNull(_manager.getMechanisms());
    assertNull(Security.getProvider(PrincipalDatabaseAuthenticationManager.PROVIDER_NAME));
    _manager = null;
}

From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java

public CMSSignedData SignedData(Element InputDocument) {

    try {/*w  w  w . j a v  a2  s.co  m*/
        X509Certificate cert = getCertificate();
        PrivateKey privatekey = getPrivateKey();
        if (privatekey == null) {
            return null;
        } else {
            String Document = PrepareDocumentToBeSign(InputDocument);
            System.out.println(Document);
            System.out.println("Certificate loaded");
            // define the provider Bouncy castle  
            if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
                Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            }

            //register the user certificate in the collection 
            ArrayList certList = new ArrayList();
            certList.add(cert);
            CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                    "BC");

            System.out.println("provider loaded");
            // create the CMSSignedData
            CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();
            System.out.println("CMS created");
            signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
            signGen.addCertificatesAndCRLs(certs);
            System.out.println("Signer loaded");

            CMSProcessable content = new CMSProcessableByteArray(Document.getBytes());
            System.out.println("BytesArray loaded");
            // the second variable "true" means that the content will be wrap with the signature
            return signGen.generate(content, true, "BC");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:sernet.gs.ui.rcp.main.security.VeriniceSecurityProvider.java

/** Does the registration of verinice's built-in security provider when the
 * respective preferences have been set.
 * //w  ww  .  j av a 2  s.c  om
 * <p>Changing the security provider has modifies the way the SSL engine
 * does client and server certificate validation.</p>
 * 
 * <p>Unfortunately changing the parameters makes it neccessary to restart
 * the VM. Otherwise it is not possible to make sure SSL does the right
 * things.</p>
 *  
 * @param prefs
 */
public static void register(Preferences prefs) {
    if (LOG.isInfoEnabled()) {
        logProperties(prefs);
    }
    if (prefs.getBoolean(PreferenceConstants.CRYPTO_VERINICE_SSL_SECURITY_ENABLED)
            && Security.getProvider(VeriniceSecurityProvider.NAME) == null) {
        // Create and register the provider
        VeriniceSecurityProvider provider = new VeriniceSecurityProvider(prefs);
        Security.addProvider(provider);

        // Add some services to the provider - can also cause the initialization
        // of a PKCS#11 library (which in turn depends on the existance of an
        // installed VeriniceSecurityProvider - hence the split of things between
        // the constructor and the init() method).
        provider.init();

        // Routes Key- and TrustManager calls through our code.
        Security.setProperty("ssl.KeyManagerFactory.algorithm", PRODUCTNAME);
        Security.setProperty("ssl.TrustManagerFactory.algorithm", PRODUCTNAME);

        // Routes Key- and TrustStore generation through our code.
        System.setProperty("javax.net.ssl.trustStoreType", VERINICE_TRUSTSTORE);
        System.setProperty("javax.net.ssl.keyStoreType", VERINICE_KEYSTORE);
    } else if (prefs.getBoolean(PreferenceConstants.CRYPTO_PKCS11_LIBRARY_ENABLED)) {
        // If the SSL thing was not necessary it is still possible that the user wanted
        // PKCS#11-based crypto. As the support for PKCS#11 is primarilary used by the
        // VeriniceSecurityProvider class we at least need an instance of that - however
        // without registering it as the systems - security provider.
        VeriniceSecurityProvider provider = new VeriniceSecurityProvider(prefs);
        provider.setupSunPKCS11Provider();
    }
}

From source file:sernet.gs.ui.rcp.main.security.VeriniceSecurityProvider.java

private void setupSunPKCS11Provider() {
    // Prevents installing the provider twice.
    if (Security.getProvider("SunPKCS11-verinice") != null) {
        return;/* ww w.j  a v  a 2 s .c o m*/
    }
    // If the user enabled anything PKCS#11 related we need to lead the PKCS#11 library and add its
    // provider.
    String configFile = createPKCS11ConfigFile();
    if (configFile != null) {
        // The availability of this class in an OSGi environment depends on a system property. If
        // get errors of this class not being available check that you have
        // -Dosgi.parentClassloader=ext
        // in your VM arguments.
        if (LOG.isDebugEnabled()) {
            LOG.debug("Setup SunPKCS11 AuthProvider with config file: " + configFile);
        }
        SunPKCS11 p = new SunPKCS11(configFile);
        p.setCallbackHandler(new Helper() {
            @Override
            protected void handle(PasswordCallback cb) {
                cb.setPassword(getTokenPIN());
            }
        });
        Security.addProvider(p);
    }
}

From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractCMSSignatureServiceTest.java

@BeforeClass
public static void beforeClass() {
    if (null == Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)) {
        Security.addProvider(new BouncyCastleProvider());
    }/*from  ww w .  j  a va2  s.c  o m*/
}