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:be.fedict.eid.idp.model.bean.IdentityServiceSingletonBean.java

/**
 * Load identity keystore/*www.j a va2  s.  co m*/
 * 
 * @param idPIdentityConfig
 *            identity configuration
 * @return private key entry of identity
 * @throws KeyStoreLoadException
 *             failed to load keystore
 */
public IdPIdentity loadIdentity(IdPIdentityConfig idPIdentityConfig) throws KeyStoreLoadException {

    try {

        if (null == idPIdentityConfig) {
            throw new KeyStoreLoadException("Identity config is empty!");
        }

        FileInputStream keyStoreInputStream = null;
        if (idPIdentityConfig.getKeyStoreType().equals(KeyStoreType.PKCS11)) {
            Security.addProvider(new SunPKCS11(idPIdentityConfig.getKeyStorePath()));
        } else {
            try {
                keyStoreInputStream = new FileInputStream(idPIdentityConfig.getKeyStorePath());
            } catch (FileNotFoundException e) {
                throw new KeyStoreLoadException("Can't load keystore from config-specified location: "
                        + idPIdentityConfig.getKeyStorePath(), e);
            }
        }

        // load keystore
        KeyStore keyStore = KeyStore.getInstance(idPIdentityConfig.getKeyStoreType().getJavaKeyStoreType());
        char[] password;
        if (null != idPIdentityConfig.getKeyStorePassword()
                && !idPIdentityConfig.getKeyStorePassword().isEmpty()) {
            password = idPIdentityConfig.getKeyStorePassword().toCharArray();
        } else {
            password = null;
        }
        keyStore.load(keyStoreInputStream, password);

        // find entry alias
        Enumeration<String> aliases = keyStore.aliases();
        if (!aliases.hasMoreElements()) {
            throw new KeyStoreLoadException("no keystore aliases present");
        }

        String alias;
        if (null != idPIdentityConfig.getKeyEntryAlias()
                && !idPIdentityConfig.getKeyEntryAlias().trim().isEmpty()) {
            boolean found = false;
            while (aliases.hasMoreElements()) {
                if (aliases.nextElement().equals(idPIdentityConfig.getKeyEntryAlias())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new KeyStoreLoadException(
                        "no keystore entry with alias \"" + idPIdentityConfig.getKeyEntryAlias() + "\"");
            }
            alias = idPIdentityConfig.getKeyEntryAlias();
        } else {
            alias = aliases.nextElement();
        }
        LOG.debug("keystore alias: " + alias);

        // get keystore entry
        char[] entryPassword;
        if (null != idPIdentityConfig.getKeyEntryPassword()
                && !idPIdentityConfig.getKeyEntryPassword().isEmpty()) {
            entryPassword = idPIdentityConfig.getKeyEntryPassword().toCharArray();
        } else {
            entryPassword = null;
        }

        KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(entryPassword));
        if (!(entry instanceof PrivateKeyEntry)) {
            throw new KeyStoreLoadException("private key entry expected");
        }
        return new IdPIdentity(idPIdentityConfig.getName(), (PrivateKeyEntry) entry);
    } catch (KeyStoreException e) {
        throw new KeyStoreLoadException(e);
    } catch (CertificateException e) {
        throw new KeyStoreLoadException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreLoadException(e);
    } catch (UnrecoverableEntryException e) {
        throw new KeyStoreLoadException(e);
    } catch (IOException e) {
        throw new KeyStoreLoadException(e);
    }
}

From source file:com.bitsofproof.supernode.test.APITest.java

@BeforeClass
public static void provider() {
    Security.addProvider(new BouncyCastleProvider());
}

From source file:org.apache.gobblin.crypto.GPGFileEncryptor.java

/**
 * Taking in an input {@link OutputStream}, keyring inputstream and a passPhrase, generate an encrypted {@link OutputStream}.
 * @param outputStream {@link OutputStream} that will receive the encrypted content
 * @param keyIn keyring inputstream. This InputStream is owned by the caller.
 * @param keyId key identifier/*from   w w  w .  j a v a2  s . co m*/
 * @param cipher the symmetric cipher to use for encryption. If null or empty then a default cipher is used.
 * @return an {@link OutputStream} to write content to for encryption
 * @throws IOException
 */
public OutputStream encryptFile(OutputStream outputStream, InputStream keyIn, long keyId, String cipher)
        throws IOException {
    try {
        if (Security.getProvider(PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }

        PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(symmetricKeyAlgorithmNameToTag(cipher))
                        .setSecureRandom(new SecureRandom()).setProvider(PROVIDER_NAME));

        PGPPublicKey publicKey;
        PGPPublicKeyRingCollection keyRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyIn),
                new BcKeyFingerprintCalculator());
        publicKey = keyRings.getPublicKey(keyId);

        if (publicKey == null) {
            throw new IllegalArgumentException("public key for encryption not found");
        }

        cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setProvider(PROVIDER_NAME));

        OutputStream cOut = cPk.open(outputStream, new byte[BUFFER_SIZE]);

        PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
        OutputStream _literalOut = literalGen.open(cOut, PGPLiteralDataGenerator.BINARY, PAYLOAD_NAME,
                new Date(), new byte[BUFFER_SIZE]);

        return new ClosingWrapperOutputStream(_literalOut, cOut, outputStream);
    } catch (PGPException e) {
        throw new IOException(e);
    }
}

From source file:com.xpn.xwiki.plugin.ldap.XWikiLDAPConnection.java

/**
 * Open LDAP connection.//from w w  w.j av a  2 s  .com
 * 
 * @param ldapHost the host of the server to connect to.
 * @param ldapPort the port of the server to connect to.
 * @param loginDN the user DN to connect to LDAP server.
 * @param password the password to connect to LDAP server.
 * @param pathToKeys the path to SSL keystore to use.
 * @param ssl if true connect using SSL.
 * @param context the XWiki context.
 * @return true if the connection succeed, false otherwise.
 * @throws XWikiLDAPException error when trying to open connection.
 */
public boolean open(String ldapHost, int ldapPort, String loginDN, String password, String pathToKeys,
        boolean ssl, XWikiContext context) throws XWikiLDAPException {
    int port = ldapPort;

    if (port <= 0) {
        port = ssl ? LDAPConnection.DEFAULT_SSL_PORT : LDAPConnection.DEFAULT_PORT;
    }

    try {
        if (ssl) {
            XWikiLDAPConfig config = XWikiLDAPConfig.getInstance();

            // Dynamically set JSSE as a security provider
            Security.addProvider(config.getSecureProvider(context));

            if (pathToKeys != null && pathToKeys.length() > 0) {
                // Dynamically set the property that JSSE uses to identify
                // the keystore that holds trusted root certificates

                System.setProperty("javax.net.ssl.trustStore", pathToKeys);
                // obviously unnecessary: sun default pwd = "changeit"
                // System.setProperty("javax.net.ssl.trustStorePassword", sslpwd);
            }

            LDAPSocketFactory ssf = new LDAPJSSESecureSocketFactory();

            // Set the socket factory as the default for all future connections
            // LDAPConnection.setSocketFactory(ssf);

            // Note: the socket factory can also be passed in as a parameter
            // to the constructor to set it for this connection only.
            this.connection = new LDAPConnection(ssf);
        } else {
            this.connection = new LDAPConnection();
        }

        // connect
        connect(ldapHost, port);

        // set referral following
        LDAPConstraints constraints = this.connection.getConstraints();
        constraints.setTimeLimit(1000);
        constraints.setReferralFollowing(true);
        constraints.setReferralHandler(new LDAPPluginReferralHandler(loginDN, password, context));
        this.connection.setConstraints(constraints);

        // bind
        bind(loginDN, password);
    } catch (UnsupportedEncodingException e) {
        throw new XWikiLDAPException("LDAP bind failed with UnsupportedEncodingException.", e);
    } catch (LDAPException e) {
        throw new XWikiLDAPException("LDAP bind failed with LDAPException.", e);
    }

    return true;
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSignerTest.java

/**
 * /* w w  w  . ja v a  2s  .co  m*/
 * Faz a leitura do token em LINUX, precisa setar a lib (.SO) e a senha do token.
 */
@SuppressWarnings("restriction")
private KeyStore getKeyStoreToken() {

    try {
        // ATENO ALTERAR CONFIGURAO ABAIXO CONFORME O TOKEN USADO

        // Para TOKEN Branco a linha abaixo
        // String pkcs11LibraryPath =
        // "/usr/lib/watchdata/ICP/lib/libwdpkcs_icp.so";

        // Para TOKEN Azul a linha abaixo
        String pkcs11LibraryPath = "/usr/lib/libeToken.so";

        StringBuilder buf = new StringBuilder();
        buf.append("library = ").append(pkcs11LibraryPath).append("\nname = Provedor\n");
        Provider p = new sun.security.pkcs11.SunPKCS11(new ByteArrayInputStream(buf.toString().getBytes()));
        Security.addProvider(p);
        // ATENO ALTERAR "SENHA" ABAIXO
        Builder builder = KeyStore.Builder.newInstance("PKCS11", p,
                new KeyStore.PasswordProtection("senha".toCharArray()));
        KeyStore ks;
        ks = builder.getKeyStore();

        return ks;

    } catch (Exception e1) {
        e1.printStackTrace();
        return null;
    } finally {
    }

}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testRecoveryAfterRemoval() throws Exception {
    Security.addProvider(new BeIDProvider());

    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//w w w  .  j av  a2s. co m

    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    final Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(authnPrivateKey);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    signature.sign();

    JOptionPane.showMessageDialog(null, "Please remove/insert eID card...");

    keyStore.load(null); // reload the keystore.
    authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    signature.initSign(authnPrivateKey);
    signature.update(toBeSigned);
    signature.sign();
}

From source file:org.apache.abdera2.common.security.KeyHelper.java

public static boolean prepareJceProvider(Class<?> provider) {
    try {/*w  ww  . j a  v a  2s  .  co m*/
        Provider p = (Provider) provider.newInstance();
        Security.addProvider(p);
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:test.integ.be.fedict.hsm.client.HSMProxyClientTest.java

@Test
public void testSign() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);/*  w  ww  .j  ava2  s . co  m*/
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    String location = "http://localhost:8080/hsm-proxy-ws/dss";
    // String location = "https://www.e-contract.be/hsm-proxy-ws/dss";
    HSMProxyClient client = new HSMProxyClient(location, authnPrivateKey, authnCert);
    // client.setProxy("proxy.yourict.net", 8080);

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();

    String keyAlias = "alias";

    byte[] signatureValue = client.sign(digestValue, "SHA1", keyAlias);
    assertNotNull(signatureValue);
    LOG.debug("signature value length: " + signatureValue.length);

    X509Certificate certificate = client.getCertificateChain(keyAlias).get(0);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(certificate.getPublicKey());
    signature.update(toBeSigned);
    assertTrue(signature.verify(signatureValue));
}

From source file:test.be.fedict.eid.applet.PKCS11Test.java

@Test
public void testTokenHasBeenRemovedWorkaround() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();/*from  www.  j  a  va  2  s.  co  m*/
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile), true);
    configWriter.println("name=SmartCard");
    configWriter.println("library=/usr/lib/libbeidpkcs11.so.0");
    configWriter.println("slotListIndex=1");

    SunPKCS11 provider = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(provider);
    {
        KeyStore keyStore = KeyStore.getInstance("PKCS11", provider);
        keyStore.load(null, null);
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKeyEntry.getPrivateKey());
        byte[] toBeSigned = "hello world".getBytes();
        signature.update(toBeSigned);
        byte[] signatureValue = signature.sign();

    }
    JOptionPane.showMessageDialog(null, "Please remove and re-insert the token...");
    Security.removeProvider(provider.getName());
    {
        SunPKCS11 provider2 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
        Security.addProvider(provider2);
        KeyStore keyStore = KeyStore.getInstance("PKCS11", provider2);
        keyStore.load(null, null);
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(privateKeyEntry.getPrivateKey());
        byte[] toBeSigned = "hello world".getBytes();
        signature.update(toBeSigned);
        byte[] signatureValue = signature.sign();
        Security.removeProvider(provider2.getName());
    }
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private void addProvider() {
    Security.addProvider(new BouncyCastleProvider());
}