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:org.candlepin.util.X509CRLStreamWriterTest.java

@Before
public void setUp() throws Exception {
    issuer = new X500Name("CN=Test Issuer");

    generator = KeyPairGenerator.getInstance("RSA");
    generator.initialize(2048);//from   w w  w .jav a2  s  . c  o  m
    keyPair = generator.generateKeyPair();

    signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(keyPair.getPrivate());

    outfile = new File(folder.getRoot(), "new.crl");
    Security.addProvider(BC);
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplIT.java

/**
 * @throws java.lang.Exception/*  ww w .  java2  s .  c om*/
 */
@BeforeClass
@Ignore
public static void setUpBeforeCLass() throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    // Create some test username and passwords for services
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");
    serviceURI2 = new URI("http://someservice2");
    usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2");
    serviceURI3 = new URI("http://someservice3");
    usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }
    // Load the test trusted certificate (belonging to heater.cs.man.ac.uk)
    File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile2);
    trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    credentialManager = new CredentialManagerImpl();

    //      // The code below sets up the Keystore and Truststore files and loads some data into them
    //      // and saves them into a temp directory. These files can later be used for testing the Credential
    //      // Manager with non-empty keystores.
    //      Random randomGenerator = new Random();
    //      String credentialManagerDirectoryPath = System
    //            .getProperty("java.io.tmpdir")
    //            + System.getProperty("file.separator")
    //            + "taverna-security-"
    //            + randomGenerator.nextInt(1000000);
    //      System.out.println("Credential Manager's directory path: "
    //            + credentialManagerDirectoryPath);
    //      credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    //      credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
    //      
    //      // Create the dummy master password provider
    //      masterPasswordProvider = new DummyMasterPasswordProvider();
    //      masterPasswordProvider.setMasterPassword(masterPassword);
    //      List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    //      masterPasswordProviders.add(masterPasswordProvider);
    //      credentialManager.setMasterPasswordProviders(masterPasswordProviders);
    //      
    //      // Add some stuff into Credential Manager
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3);
    //      credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    //      credentialManager.addTrustedCertificate(trustedCertficate);

    // Set up a random temp directory and copy the test keystore files 
    // from resources/security
    Random randomGenerator = new Random();
    String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir")
            + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000);
    System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath);
    credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    if (!credentialManagerDirectory.exists()) {
        credentialManagerDirectory.mkdir();
    }
    URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr");
    File keystoreFile = new File(keystoreFileURL.getPath());
    File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr");
    URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr");
    File truststoreFile = new File(truststroreFileURL.getPath());
    File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr");
    FileUtils.copyFile(keystoreFile, keystoreDestFile);
    FileUtils.copyFile(truststoreFile, truststoreDestFile);
    credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory.toPath());

    // Create the dummy master password provider
    masterPasswordProvider = new DummyMasterPasswordProvider();
    masterPasswordProvider.setMasterPassword(masterPassword);
    List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    masterPasswordProviders.add(masterPasswordProvider);
    credentialManager.setMasterPasswordProviders(masterPasswordProviders);

    // Set an empty list for trust confirmation providers
    credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {
        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub
        }
    };
    credentialManager.addObserver(keystoreChangedObserver);
}

From source file:be.fedict.hsm.model.KeyStoreLoaderBean.java

private Map<String, PrivateKeyEntry> loadPKCS11(KeyStoreEntity keyStoreEntity) throws KeyStoreException,
        IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException {
    File tmpConfigFile = File.createTempFile("pkcs11-", ".conf");
    tmpConfigFile.deleteOnExit();//from  w  w w .j a  v a2s .c o  m
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile));
    configWriter.println("name=HSM-" + keyStoreEntity.getId());
    String path = keyStoreEntity.getPath();
    LOG.debug("PKCS11 path: " + path);
    LOG.debug("slot list index: " + keyStoreEntity.getSlotListIndex());
    configWriter.println("library=" + path);
    configWriter.println("slotListIndex=" + keyStoreEntity.getSlotListIndex());
    configWriter.close();
    SunPKCS11 sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    LOG.debug("adding SunPKCS11 JCA provider: " + sunPKCS11.getName());
    /*
     * Reloads also need to work properly.
     */
    Security.removeProvider(sunPKCS11.getName());
    Security.addProvider(sunPKCS11);
    KeyStore keyStore = KeyStore.getInstance("PKCS11", sunPKCS11);
    if (null != keyStoreEntity.getPassword()) {
        keyStore.load(null, keyStoreEntity.getPassword().toCharArray());
    } else {
        keyStore.load(null, null);
    }
    String keyStorePassword = keyStoreEntity.getPassword();
    return loadKeys(keyStoreEntity, keyStore, keyStorePassword);
}

From source file:eu.europa.ejusticeportal.dss.applet.model.token.MoccaDssActionTest.java

/**
 * Test that we can sign with MOCCA//from   ww  w.  j  ava 2s  . c  om
 * @throws CodeException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public void testSign() throws CodeException, FileNotFoundException, IOException, NoSuchAlgorithmException {
    CardProfile cp = new CardProfile();
    cp.setApi(SignatureTokenType.MOCCA.name());
    cp.setAtr("00 00 00 00 00 00 00 00 00 00");
    cp.setCardDescription("A test card");
    cp.setDigestAlgo(DigestAlgorithm.SHA1.name());

    Security.addProvider(new BouncyCastleProvider());
    MOCCADSSAction m = new MOCCADSSAction();
    m.setCardProfile(cp);
    m.setChosenDigestAlgo(DigestAlgorithm.SHA1);
    m.setPasswordProvider(new MoccaPasswordProvider());
    m.connect();
    List<DSSPrivateKeyEntry> keys = m.getCertificates();
    MessageBundle mb = new MessageBundle();
    mb.setMessages(new HashMap<String, String>());
    MessageBundleHome.getInstance().init(mb);

    InMemoryDocument toBeSigned = new InMemoryDocument(
            IOUtils.toByteArray(new FileInputStream(new File("src/test/resources/hello-world.pdf"))));
    //        m.sign(toBeSigned, keys.get(0));

    for (DSSPrivateKeyEntry key : keys) {
        //DSSPrivateKeyEntry key = keys.get(1);
        String name = key.getCertificate().getSubjectDN().getName();
        QcStatementCondition cond = new QcStatementCondition(ETSIQCObjectIdentifiers.id_etsi_qcs_QcSSCD);
        if (key.getCertificate().getKeyUsage()[1]) {
            m.sign(toBeSigned, key);
        }

    }

}

From source file:de.brendamour.jpasskit.signing.PKFileBasedSigningUtilTest.java

@Test
public void testJson() throws IOException, Exception {
    Security.addProvider(new BouncyCastleProvider());

    PKBarcode barcode = new PKBarcode();
    barcode.setFormat(PKBarcodeFormat.PKBarcodeFormatQR);
    barcode.setMessage("abcdefg");
    barcode.setMessageEncoding(Charset.forName("UTF-8"));

    PKPass pass = new PKPass();
    pass.setBarcodes(Arrays.asList(barcode));
    pass.setPassTypeIdentifier("pti");
    pass.setTeamIdentifier("ti");

    PKSigningInformation pkSigningInformation = new PKSigningInformationUtil()
            .loadSigningInformationFromPKCS12AndIntermediateCertificate(keyStorePath, keyStorePassword,
                    appleWWDRCA);//from ww  w  .j  a v  a2 s . c o m
    byte[] signedAndZippedPkPassArchive = new PKFileBasedSigningUtil(new ObjectMapper())
            .createSignedAndZippedPkPassArchive(pass, new PKPassTemplateFolder(getPassFolderPath()),
                    pkSigningInformation);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(signedAndZippedPkPassArchive);

    File passJsonFile = new File("target/passJson.zip");
    if (passJsonFile.exists()) {
        passJsonFile.delete();
    }
    IOUtils.copy(inputStream, new FileOutputStream(passJsonFile));
    Assert.assertTrue(passJsonFile.exists());
    Assert.assertTrue(passJsonFile.length() > 0);
}

From source file:org.openanzo.security.ldap.LdapConnectionFactory.java

/**
 * //from ww  w.  ja va  2 s .  com
 * @param connProperties
 */
public LdapConnectionFactory(Dictionary<? extends Object, ? extends Object> connProperties)
        throws AnzoException {
    host = LDAPDictionary.getHost(connProperties, "localhost");
    port = LDAPDictionary.getPort(connProperties, 10389);
    ldapAdminDN = LDAPDictionary.getLdapServerUser(connProperties);
    ldapAdminPassword = LDAPDictionary.getLdapServerPassword(connProperties);
    Boolean useSSL = LDAPDictionary.getUseSSL(connProperties);
    if (useSSL != null) {
        this.useSSL = useSSL.booleanValue();
    }
    if (this.useSSL) {

        String keystoreFile = KeyStoreDictionary.getKeyFileLocation(connProperties);
        String keystorePassword = KeyStoreDictionary.getKeyPassword(connProperties);
        String keystoreType = KeyStoreDictionary.getKeystoreType(connProperties);
        String truststoreFile = KeyStoreDictionary.getClientTrustFileLocation(connProperties);
        String truststorePassword = KeyStoreDictionary.getClientTrustPassword(connProperties);
        String truststoreType = KeyStoreDictionary.getClientTruststoreType(connProperties);
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        ssf = new LDAPJSSESecureSocketFactory(Utils.getSSLSocketFactory(keystoreFile, keystorePassword,
                keystoreType, truststoreFile, truststorePassword, truststoreType));
    }
}

From source file:com.liferay.util.Encryptor.java

public static String encrypt(Key key, String plainText) throws EncryptorException {

    try {/*from  w w  w  . j  a  v a 2 s  . c o  m*/
        Security.addProvider(getProvider());

        Cipher cipher = Cipher.getInstance(key.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] decryptedBytes = plainText.getBytes(ENCODING);
        byte[] encryptedBytes = cipher.doFinal(decryptedBytes);

        String encryptedString = Base64.encode(encryptedBytes);

        return encryptedString;
    } catch (Exception e) {
        throw new EncryptorException(e);
    }
}

From source file:org.tolven.config.model.CredentialManager.java

public CredentialManager(TolvenConfigWrapper tolvenConfigWrapper) {
    setTolvenConfigWrapper(tolvenConfigWrapper);
    //TODO Is this the best place for loading the provider
    Security.addProvider(new BouncyCastleProvider());
}

From source file:test.integ.be.agiv.security.CrabReadTest.java

@Test
public void testServiceBeID() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);// w w w  . j av a2s .  co m
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate certificate = (X509Certificate) keyStore.getCertificate("Authentication");

    CrabReadService crabReadService = new CrabReadService();

    ICrabRead iCrabRead = crabReadService.getWS2007FederationHttpBindingICrabRead(new AddressingFeature());

    AGIVSecurity agivSecurity = new AGIVSecurity(
            "https://auth.beta.agiv.be/ipsts/Services/DaliSecurityTokenServiceConfiguration.svc/CertificateMessage",
            "https://auth.beta.agiv.be/sts/Services/SalvadorSecurityTokenServiceConfiguration.svc/IWSTrust13",
            AGIVSecurity.BETA_REALM, certificate, privateKey);

    BindingProvider bindingProvider = (BindingProvider) iCrabRead;
    agivSecurity.enable(bindingProvider, "https://crab.beta.agiv.be/read/crabreadservice.svc/wsfed", false,
            "urn:agiv.be/crab/beta");

    ArrayOfstring gemeentes = iCrabRead.listGemeente();
    List<String> gemeenteList = gemeentes.getString();
    for (String gemeente : gemeenteList) {
        LOG.debug("gemeente: " + gemeente);
    }
    assertTrue(gemeenteList.contains("Vilvoorde"));

    agivSecurity.refreshSecurityTokens();
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

@BeforeClass
public static void beforeClass() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    classPath = KeyStoreTestUtil.getClasspathDir(TestHopsworksRMAppSecurityActions.class);
    byte[] jwtIssuerSecret = new byte[32];
    Random rand = new Random();
    rand.nextBytes(jwtIssuerSecret);/*from  w w  w  . j  a  v a  2  s. co  m*/
    jwtIssuer = new MockJWTIssuer(jwtIssuerSecret);
}